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 666915e
Showing 1 changed file with 50 additions and 0 deletions.
50 changes: 50 additions & 0 deletions src/sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,12 @@ 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;

use std::sync::TryLockError;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::AtomicPtr;
use std::sync::atomic::AtomicUsize;
Expand All @@ -27,6 +29,30 @@ pub struct FrozenMap<K, V> {
map: RwLock<HashMap<K, V>>,
}

impl<K: fmt::Debug, V: fmt::Debug> 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::Poisoned(err)) => {
d.field("map", &&**err.get_ref());
}
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 +413,30 @@ pub struct FrozenVec<T> {
vec: RwLock<Vec<T>>,
}

impl<T: fmt::Debug> fmt::Debug for FrozenVec<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut d = f.debug_struct("FrozenVec");
match self.vec.try_read() {
Ok(guard) => {
d.field("vec", &&*guard);
},
Err(TryLockError::Poisoned(err)) => {
d.field("vec", &&**err.get_ref());
}
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 666915e

Please sign in to comment.