Skip to content

Commit

Permalink
Prevent "index out of bounds" error when sync::SegmentedCache was c…
Browse files Browse the repository at this point in the history
…reated with

a non-power-of-two segments
  • Loading branch information
tatsuya6502 committed Apr 12, 2022
1 parent 5872342 commit 6939473
Showing 1 changed file with 20 additions and 1 deletion.
21 changes: 20 additions & 1 deletion src/sync/segment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -507,7 +507,7 @@ where
let seg_init_capacity = initial_capacity.map(|cap| cap / actual_num_segments);
// NOTE: We cannot initialize the segments as `vec![cache; actual_num_segments]`
// because Cache::clone() does not clone its inner but shares the same inner.
let segments = (0..num_segments)
let segments = (0..actual_num_segments)
.map(|_| {
Cache::with_everything(
seg_max_capacity,
Expand Down Expand Up @@ -620,6 +620,25 @@ mod tests {
assert!(!cache.contains_key(&"b"));
}

#[test]
fn non_power_of_two_segments() {
let mut cache = SegmentedCache::new(100, 5);
cache.reconfigure_for_testing();

// Make the cache exterior immutable.
let cache = cache;

assert_eq!(cache.iter().count(), 0);

cache.insert("a", "alice");
cache.insert("b", "bob");
cache.insert("c", "cindy");

assert_eq!(cache.iter().count(), 3);
cache.sync();
assert_eq!(cache.iter().count(), 3);
}

#[test]
fn size_aware_eviction() {
let weigher = |_k: &&str, v: &(&str, u32)| v.1;
Expand Down

0 comments on commit 6939473

Please sign in to comment.