diff --git a/src/key.rs b/src/key.rs index 1114070..0c6dfa9 100644 --- a/src/key.rs +++ b/src/key.rs @@ -9,12 +9,12 @@ use std::marker::PhantomData; /// a key from a value that is Hash. /// #[derive(Clone)] -pub struct S3FIFOKey { +pub struct S3FIFOKey { hash: u64, _phantom: PhantomData, } -impl PartialEq for S3FIFOKey { +impl PartialEq for S3FIFOKey { fn eq(&self, other: &Self) -> bool { self.hash == other.hash } @@ -36,7 +36,7 @@ impl S3FIFOKey { } } -impl std::fmt::Debug for S3FIFOKey { +impl std::fmt::Debug for S3FIFOKey { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("S3FIFOKey") .field("hash", &self.hash) @@ -44,8 +44,8 @@ impl std::fmt::Debug for S3FIFOKey { } } -impl Display for S3FIFOKey { +impl Display for S3FIFOKey { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{:#x}", self.hash) } -} \ No newline at end of file +} diff --git a/src/lib.rs b/src/lib.rs index 013d761..703c384 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -3,6 +3,7 @@ use std::{ collections::VecDeque, + fmt::{self, Debug}, sync::atomic::{AtomicI8, Ordering}, }; @@ -42,6 +43,19 @@ pub struct S3FIFO { main: VecDeque>, ghost: VecDeque>, } +impl std::fmt::Debug for S3FIFO +where + K: std::fmt::Debug, + V: std::fmt::Debug, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("S3FIFO") + .field("small", &self.small) + .field("main", &self.main) + .field("ghost", &self.ghost) + .finish() + } +} impl S3FIFO { /// @@ -155,7 +169,7 @@ impl S3FIFO { evicted = self.evict_main(); } self.main.push_front(item); - return (&mut self.main.front_mut().unwrap().value, evicted); + (&mut self.main.front_mut().unwrap().value, evicted) } else { let item = Item { key, @@ -166,7 +180,7 @@ impl S3FIFO { evicted = self.evict_small(); } self.small.push_front(item); - return (&mut self.small.front_mut().unwrap().value, evicted); + (&mut self.small.front_mut().unwrap().value, evicted) } } @@ -220,9 +234,7 @@ impl S3FIFO { // then the maximum number of iterations is 3 * main.len() + 1 let mut iters = (3 * self.main.len() + 1) as isize; while iters > 0 { - let Some(item) = self.main.pop_back() else { - return None; - }; + let item = self.main.pop_back()?; iters -= 1; let freq = item.freq.load(Ordering::Relaxed); if freq > 0 { @@ -242,11 +254,37 @@ struct Item { freq: AtomicI8, // not thread-safe } +impl Debug for Item +where + K: Debug, + V: Debug, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Item") + .field("key", &self.key) + .field("value", &self.value) + .field("freq", &self.freq) + .finish() + } +} + struct Key { key: K, freq: AtomicI8, // not thread-safe } +impl Debug for Key +where + K: Debug, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Key") + .field("key", &self.key) + .field("freq", &self.freq) + .finish() + } +} + #[cfg(test)] mod tests { use super::*;