Skip to content

Commit

Permalink
feat: Implement Debug trait for sync variants FrozenMap and FrozenVec
Browse files Browse the repository at this point in the history
- partially contributes to #32,
- Implements `Debug` trait for those structures where checking for reentrancy is straightforward.
  • Loading branch information
huitseeker committed Sep 27, 2023
1 parent 2061108 commit 6149511
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions src/sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use std::alloc::Layout;
use std::borrow::Borrow;
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::fmt;
use std::hash::Hash;
use std::iter::{FromIterator, IntoIterator};
use std::ops::Index;
Expand All @@ -27,6 +28,26 @@ pub struct FrozenMap<K, V> {
map: RwLock<HashMap<K, V>>,
}

impl<K, V> fmt::Debug for FrozenMap<K, V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut d = f.debug_struct("FrozenMap");
match self.map.try_read() {
Ok(guard) => {
d.field("map", &&*guard);
},
Err(TryLockError::WouldBlock) => {
struct LockedPlaceholder;
impl fmt::Debug for LockedPlaceholder {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("<locked>")
}
}
d.field("map", &LockedPlaceholder);
},
}
d.finish_non_exhaustive()
}

impl<K, V> Default for FrozenMap<K, V> {
fn default() -> Self {
Self {
Expand Down Expand Up @@ -387,6 +408,26 @@ pub struct FrozenVec<T> {
vec: RwLock<Vec<T>>,
}

impl<K, V> fmt::Debug for FrozenVec<K, V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut d = f.debug_struct("FrozenVec");
match self.map.try_read() {
Ok(guard) => {
d.field("vec", &&*guard);
},
Err(TryLockError::WouldBlock) => {
struct LockedPlaceholder;
impl fmt::Debug for LockedPlaceholder {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("<locked>")
}
}
d.field("vec", &LockedPlaceholder);
},
}
d.finish_non_exhaustive()
}

impl<T> FrozenVec<T> {
/// Returns the number of elements in the vector.
pub fn len(&self) -> usize {
Expand Down

0 comments on commit 6149511

Please sign in to comment.