Skip to content

Commit 270437c

Browse files
committed
refactor: simplify LruCache::flush
1 parent 1035f7b commit 270437c

File tree

1 file changed

+11
-26
lines changed

1 file changed

+11
-26
lines changed

stacks-common/src/util/lru_cache.rs

Lines changed: 11 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515

1616
use std::fmt::Display;
1717

18-
use hashbrown::{HashMap, HashSet};
18+
use hashbrown::HashMap;
1919

2020
/// Node in the doubly linked list
2121
struct Node<K, V> {
@@ -198,30 +198,11 @@ impl<K: Eq + std::hash::Hash + Clone, V: Copy> LruCache<K, V> {
198198
&mut self,
199199
mut f: impl FnMut(&K, V) -> Result<(), E>,
200200
) -> Result<Result<(), E>, LruCacheCorrupted> {
201-
let mut current = self.head;
202-
203-
// Keep track of visited nodes to detect cycles
204-
let mut visited = HashSet::new();
205-
206-
while current != self.capacity {
207-
// Detect cycles
208-
if !visited.insert(current) {
209-
return Err(LruCacheCorrupted);
210-
}
211-
212-
let node = self.order.get_mut(current).ok_or(LruCacheCorrupted)?;
213-
let next = node.next;
214-
if node.dirty {
215-
let value = node.value;
216-
217-
// Call the flush function
218-
match f(&node.key, value) {
219-
Ok(()) => node.dirty = false,
220-
Err(e) => return Ok(Err(e)),
221-
}
222-
node.dirty = false;
201+
for node in self.order.iter_mut().filter(|n| n.dirty) {
202+
match f(&node.key, node.value) {
203+
Ok(()) => node.dirty = false,
204+
Err(e) => return Ok(Err(e)),
223205
}
224-
current = next;
225206
}
226207
Ok(Ok(()))
227208
}
@@ -374,7 +355,8 @@ mod tests {
374355
.expect("cache corrupted")
375356
.expect("flush failed");
376357

377-
assert_eq!(flushed, vec![(2, 2), (1, 3)]);
358+
flushed.sort();
359+
assert_eq!(flushed, vec![(1, 3), (2, 2)]);
378360
}
379361

380362
#[test]
@@ -407,7 +389,8 @@ mod tests {
407389
.expect("cache corrupted")
408390
.expect("flush failed");
409391

410-
assert_eq!(flushed, [(3, 3), (2, 2)]);
392+
flushed.sort();
393+
assert_eq!(flushed, [(2, 2), (3, 3)]);
411394
}
412395

413396
/// Simple LRU implementation for testing
@@ -573,6 +556,8 @@ mod property_tests {
573556
simple_flushed.push((*k, v));
574557
Ok::<(), ()>(())
575558
}).unwrap();
559+
flushed.sort();
560+
simple_flushed.sort();
576561
prop_assert_eq!(flushed, simple_flushed);
577562
}
578563
};

0 commit comments

Comments
 (0)