Skip to content

Commit a9594da

Browse files
committed
feat(cache): add peek by policy
Signed-off-by: Chojan Shang <psiace@apache.org>
1 parent 2bc0671 commit a9594da

File tree

1 file changed

+20
-5
lines changed
  • src/common/cache/src/cache

1 file changed

+20
-5
lines changed

src/common/cache/src/cache/lru.rs

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -161,18 +161,29 @@ impl<K: Eq + Hash, V, S: BuildHasher> LruCache<K, V, S, Count> {
161161

162162
impl<K: Eq + Hash, V, S: BuildHasher, M: CountableMeter<K, V>> LruCache<K, V, S, M> {
163163
fn find_evict_candidate(&mut self) -> Option<K> {
164-
let mut iter = self.visited.iter_mut();
164+
let iter = self.visited.iter_mut();
165165
let mut p: Option<K> = None;
166-
while let Some((key, value)) = iter.next() {
167-
if *value == false && p.is_none() {
166+
for (key, value) in iter {
167+
if !(*value) && p.is_none() {
168168
p = Some(unsafe { std::ptr::read(key) })
169169
}
170-
if *value == true {
170+
if *value {
171171
*value = false;
172172
}
173173
}
174174
p
175175
}
176+
177+
fn peek_evict_candidate(&self) -> Option<K> {
178+
let iter = self.visited.iter();
179+
let mut p: Option<K> = None;
180+
for (key, value) in iter {
181+
if !(*value) && p.is_none() {
182+
p = Some(unsafe { std::ptr::read(key) })
183+
}
184+
}
185+
p
186+
}
176187
}
177188

178189
impl<K: Eq + Hash, V, S: BuildHasher, M: CountableMeter<K, V>> Cache<K, V, S, M>
@@ -271,7 +282,11 @@ impl<K: Eq + Hash, V, S: BuildHasher, M: CountableMeter<K, V>> Cache<K, V, S, M>
271282
/// assert_eq!(cache.peek_by_policy(), Some((&1, &"a")));
272283
/// ```
273284
fn peek_by_policy(&self) -> Option<(&K, &V)> {
274-
todo!()
285+
if let Some(old_key) = self.peek_evict_candidate() {
286+
self.map.get_key_value(&old_key)
287+
} else {
288+
self.map.front()
289+
}
275290
}
276291

277292
/// Checks if the map contains the given key.

0 commit comments

Comments
 (0)