@@ -462,6 +462,42 @@ impl<K: Hash + Eq, V, S: BuildHasher> LruCache<K, V, S> {
462
462
}
463
463
}
464
464
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
+
465
501
/// Returns a reference to the value of the key in the cache if it is
466
502
/// present in the cache and moves the key to the head of the LRU list.
467
503
/// If the key does not exist the provided `FnOnce` is used to populate
0 commit comments