Skip to content

Commit

Permalink
Properly reset weight when clearing
Browse files Browse the repository at this point in the history
  • Loading branch information
marmeladema committed Nov 27, 2022
1 parent 590a794 commit 59e572c
Showing 1 changed file with 20 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -421,6 +421,7 @@ impl<K: Clone + Eq + Hash, V, S: BuildHasher, W: WeightScale<K, V>> CLruCache<K,
pub fn clear(&mut self) {
self.lookup.clear();
self.storage.clear();
self.weight = 0;
}

/// Resizes the cache.
Expand Down Expand Up @@ -1804,6 +1805,25 @@ mod tests {
assert_eq!(cache.get(&"tomato"), Some(&"red"));
}

#[test]
fn test_weighted_clear() {
let mut cache = CLruCache::with_config(
CLruCacheConfig::new(NonZeroUsize::new(10).unwrap()).with_scale(StrStrScale),
);

assert_eq!(cache.put_with_weight("apple", "red"), Ok(None));
assert_eq!(cache.put_with_weight("banana", "yellow"), Ok(None));

assert_eq!(cache.len(), 1);
assert_eq!(cache.weight(), 6);
assert_eq!(cache.get(&"apple"), None);
assert_eq!(cache.get(&"banana"), Some(&"yellow"));

cache.clear();
assert_eq!(cache.len(), 0);
assert_eq!(cache.weight(), 0);
}

#[derive(Debug)]
struct IntStrScale;

Expand Down

0 comments on commit 59e572c

Please sign in to comment.