Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: implement Clone for LruCache #191

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
38 changes: 38 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@
}

impl<K: PartialEq> PartialEq for KeyRef<K> {
fn eq(&self, other: &KeyRef<K>) -> bool {

Check failure on line 101 in src/lib.rs

View workflow job for this annotation

GitHub Actions / ci (nightly)

function cannot return without recursing
unsafe { (*self.k).eq(&*other.k) }
}
}
Expand All @@ -124,7 +124,7 @@
}

impl<K: ?Sized + PartialEq> PartialEq for KeyWrapper<K> {
fn eq(&self, other: &Self) -> bool {

Check failure on line 127 in src/lib.rs

View workflow job for this annotation

GitHub Actions / ci (nightly)

function cannot return without recursing
self.0.eq(&other.0)
}
}
Expand Down Expand Up @@ -186,6 +186,22 @@
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 @@
);
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