Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -510,6 +510,9 @@ impl<K: Hash + Eq, V, S: BuildHasher> LruCache<K, V, S> {
match self.map.remove(&k) {
None => None,
Some(mut old_node) => {
unsafe {
ptr::drop_in_place(old_node.key.as_mut_ptr());
}
let node_ptr: *mut LruEntry<K, V> = &mut *old_node;
self.detach(node_ptr);
unsafe { Some(old_node.val.assume_init()) }
Expand Down Expand Up @@ -1576,6 +1579,38 @@ mod tests {
assert_eq!(DROP_COUNT.load(Ordering::SeqCst), n * n);
}

#[test]
fn test_no_memory_leaks_with_pop() {
static DROP_COUNT: AtomicUsize = AtomicUsize::new(0);

#[derive(Hash, Eq)]
struct KeyDropCounter(usize);

impl PartialEq for KeyDropCounter {
fn eq(&self, other: &Self) -> bool {
self.0.eq(&other.0)
}
}

impl Drop for KeyDropCounter {
fn drop(&mut self) {
DROP_COUNT.fetch_add(1, Ordering::SeqCst);
}
}

let n = 100;
for _ in 0..n {
let mut cache = LruCache::new(1);

for i in 0..100 {
cache.put(KeyDropCounter(i), i);
cache.pop(&KeyDropCounter(i));
}
}

assert_eq!(DROP_COUNT.load(Ordering::SeqCst), n * n * 2);
}

#[test]
fn test_zero_cap_no_crash() {
let mut cache = LruCache::new(0);
Expand Down