Skip to content

Commit

Permalink
WIP: add API to explicitly control LRUness of keys
Browse files Browse the repository at this point in the history
`promote` is mostly just `get`. `demote` is new, and wasn't expressible
before: it allows the caller to hint that the value likely won't be used
in the future.
  • Loading branch information
matklad committed Aug 22, 2022
1 parent b491112 commit e2bb61f
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions src/lib.rs
Expand Up @@ -719,6 +719,32 @@ impl<K: Hash + Eq, V, S: BuildHasher> LruCache<K, V, S> {
unsafe { Some((key.assume_init(), val.assume_init())) }
}

/// Marks the key as the most recently used one.
pub fn promote<'a, Q>(&'a mut self, k: &Q)
where
KeyRef<K>: Borrow<Q>,
Q: Hash + Eq + ?Sized,
{
if let Some(node) = self.map.get_mut(k) {
let node_ptr: *mut LruEntry<K, V> = &mut **node;
self.detach(node_ptr);
self.attach(node_ptr);
}
}

/// Marks the key as the least recently used one.
pub fn demote<'a, Q>(&'a mut self, k: &Q)
where
KeyRef<K>: Borrow<Q>,
Q: Hash + Eq + ?Sized,
{
if let Some(node) = self.map.get_mut(k) {
let node_ptr: *mut LruEntry<K, V> = &mut **node;
self.detach(node_ptr);
self.attach_last(node_ptr);
}
}

/// Returns the number of key-value pairs that are currently in the the cache.
///
/// # Example
Expand Down Expand Up @@ -926,6 +952,15 @@ impl<K: Hash + Eq, V, S: BuildHasher> LruCache<K, V, S> {
(*(*node).next).prev = node;
}
}

fn attach_last(&mut self, node: *mut LruEntry<K, V>) {
unsafe {
(*node).next = self.tail;
(*node).prev = (*self.tail).prev;
(*self.tail).prev = node;
(*(*node).prev).next = node;
}
}
}

impl<K, V, S> Drop for LruCache<K, V, S> {
Expand Down

0 comments on commit e2bb61f

Please sign in to comment.