Skip to content

Commit

Permalink
feat: implement Clone for LruCache
Browse files Browse the repository at this point in the history
  • Loading branch information
stormshield-frb committed Jan 24, 2024
1 parent 27ec1c7 commit 9eba7b9
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,22 @@ pub struct LruCache<K, V, S = DefaultHasher> {
tail: *mut LruEntry<K, V>,
}

impl<K, V> Clone for LruCache<K, V>
where
K: Hash + PartialEq + Eq + Clone,
V: Clone,
{
fn clone(&self) -> Self {
let mut new_lru = LruCache::new(self.cap());

for (key, value) in self.iter().rev() {
new_lru.push(key.clone(), value.clone());
}

new_lru
}
}

impl<K: Hash + Eq, V> LruCache<K, V> {
/// Creates a new LRU Cache that holds at most `cap` items.
///
Expand Down Expand Up @@ -2259,6 +2275,28 @@ mod tests {
);
assert_eq!(cache.get_key_value("banana"), None);
}

#[test]
fn test_clone() {
let mut cache = LruCache::new(NonZeroUsize::new(3).unwrap());
cache.put("a", 1);
cache.put("b", 2);
cache.put("c", 3);

let mut cloned = cache.clone();

assert_eq!(cache.pop_lru(), Some(("a", 1)));
assert_eq!(cloned.pop_lru(), Some(("a", 1)));

assert_eq!(cache.pop_lru(), Some(("b", 2)));
assert_eq!(cloned.pop_lru(), Some(("b", 2)));

assert_eq!(cache.pop_lru(), Some(("c", 3)));
assert_eq!(cloned.pop_lru(), Some(("c", 3)));

assert_eq!(cache.pop_lru(), None);
assert_eq!(cloned.pop_lru(), None);
}
}

/// Doctests for what should *not* compile
Expand Down

0 comments on commit 9eba7b9

Please sign in to comment.