Skip to content

Commit 39009f1

Browse files
authored
Merge pull request #186 from Rulexec/get-key-value-method
Add get_key_value method #185
2 parents 4e0d2ac + 81ac561 commit 39009f1

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

src/lib.rs

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -462,6 +462,42 @@ impl<K: Hash + Eq, V, S: BuildHasher> LruCache<K, V, S> {
462462
}
463463
}
464464

465+
/// Returns a key-value references pair of the key in the cache or `None` if it is not
466+
/// present in the cache. Moves the key to the head of the LRU list if it exists.
467+
///
468+
/// # Example
469+
///
470+
/// ```
471+
/// use lru::LruCache;
472+
/// use std::num::NonZeroUsize;
473+
/// let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
474+
///
475+
/// cache.put(String::from("1"), "a");
476+
/// cache.put(String::from("2"), "b");
477+
/// cache.put(String::from("2"), "c");
478+
/// cache.put(String::from("3"), "d");
479+
///
480+
/// assert_eq!(cache.get_key_value("1"), None);
481+
/// assert_eq!(cache.get_key_value("2"), Some((&String::from("2"), &"c")));
482+
/// assert_eq!(cache.get_key_value("3"), Some((&String::from("3"), &"d")));
483+
/// ```
484+
pub fn get_key_value<'a, Q>(&'a mut self, k: &Q) -> Option<(&'a K, &'a V)>
485+
where
486+
K: Borrow<Q>,
487+
Q: Hash + Eq + ?Sized,
488+
{
489+
if let Some(node) = self.map.get_mut(KeyWrapper::from_ref(k)) {
490+
let node_ptr: *mut LruEntry<K, V> = node.as_ptr();
491+
492+
self.detach(node_ptr);
493+
self.attach(node_ptr);
494+
495+
Some(unsafe { (&*(*node_ptr).key.as_ptr(), &*(*node_ptr).val.as_ptr()) })
496+
} else {
497+
None
498+
}
499+
}
500+
465501
/// Returns a reference to the value of the key in the cache if it is
466502
/// present in the cache and moves the key to the head of the LRU list.
467503
/// If the key does not exist the provided `FnOnce` is used to populate

0 commit comments

Comments
 (0)