Skip to main content

lru/
lib.rs

1// MIT License
2
3// Copyright (c) 2016 Jerome Froelich
4
5// Permission is hereby granted, free of charge, to any person obtaining a copy
6// of this software and associated documentation files (the "Software"), to deal
7// in the Software without restriction, including without limitation the rights
8// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9// copies of the Software, and to permit persons to whom the Software is
10// furnished to do so, subject to the following conditions:
11
12// The above copyright notice and this permission notice shall be included in all
13// copies or substantial portions of the Software.
14
15// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21// SOFTWARE.
22
23//! An implementation of a LRU cache. The cache supports `get`, `get_mut`, `put`,
24//! and `pop` operations, all of which are O(1). This crate was heavily influenced
25//! by the [LRU Cache implementation in an earlier version of Rust's std::collections crate](https://doc.rust-lang.org/0.12.0/std/collections/lru_cache/struct.LruCache.html).
26//!
27//! ## Example
28//!
29//! ```rust
30//! extern crate lru;
31//!
32//! use lru::LruCache;
33//! use std::num::NonZeroUsize;
34//!
35//! fn main() {
36//!         let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
37//!         cache.put("apple", 3);
38//!         cache.put("banana", 2);
39//!
40//!         assert_eq!(*cache.get(&"apple").unwrap(), 3);
41//!         assert_eq!(*cache.get(&"banana").unwrap(), 2);
42//!         assert!(cache.get(&"pear").is_none());
43//!
44//!         assert_eq!(cache.put("banana", 4), Some(2));
45//!         assert_eq!(cache.put("pear", 5), None);
46//!
47//!         assert_eq!(*cache.get(&"pear").unwrap(), 5);
48//!         assert_eq!(*cache.get(&"banana").unwrap(), 4);
49//!         assert!(cache.get(&"apple").is_none());
50//!
51//!         {
52//!             let v = cache.get_mut(&"banana").unwrap();
53//!             *v = 6;
54//!         }
55//!
56//!         assert_eq!(*cache.get(&"banana").unwrap(), 6);
57//! }
58//! ```
59
60#![no_std]
61
62#[cfg(feature = "hashbrown")]
63extern crate hashbrown;
64
65#[cfg(test)]
66extern crate scoped_threadpool;
67
68use alloc::borrow::Borrow;
69use alloc::boxed::Box;
70use core::fmt;
71use core::hash::{BuildHasher, Hash, Hasher};
72use core::iter::FusedIterator;
73use core::marker::PhantomData;
74use core::mem;
75use core::num::NonZeroUsize;
76use core::ptr::{self, NonNull};
77
78#[cfg(any(test, not(feature = "hashbrown")))]
79extern crate std;
80
81#[cfg(feature = "hashbrown")]
82use hashbrown::HashMap;
83#[cfg(not(feature = "hashbrown"))]
84use std::collections::HashMap;
85
86extern crate alloc;
87
88// Struct used to hold a reference to a key
89struct KeyRef<K> {
90    k: *const K,
91}
92
93impl<K: Hash> Hash for KeyRef<K> {
94    fn hash<H: Hasher>(&self, state: &mut H) {
95        unsafe { (*self.k).hash(state) }
96    }
97}
98
99impl<K: PartialEq> PartialEq for KeyRef<K> {
100    // NB: The unconditional_recursion lint was added in 1.76.0 and can be removed
101    // once the current stable version of Rust is 1.76.0 or higher.
102    #![allow(unknown_lints)]
103    #[allow(clippy::unconditional_recursion)]
104    fn eq(&self, other: &KeyRef<K>) -> bool {
105        unsafe { (*self.k).eq(&*other.k) }
106    }
107}
108
109impl<K: Eq> Eq for KeyRef<K> {}
110
111// This type exists to allow a "blanket" Borrow impl for KeyRef without conflicting with the
112//  stdlib blanket impl
113#[repr(transparent)]
114struct KeyWrapper<K: ?Sized>(K);
115
116impl<K: ?Sized> KeyWrapper<K> {
117    fn from_ref(key: &K) -> &Self {
118        // safety: KeyWrapper is transparent, so casting the ref like this is allowable
119        unsafe { &*(key as *const K as *const KeyWrapper<K>) }
120    }
121}
122
123impl<K: ?Sized + Hash> Hash for KeyWrapper<K> {
124    fn hash<H: Hasher>(&self, state: &mut H) {
125        self.0.hash(state)
126    }
127}
128
129impl<K: ?Sized + PartialEq> PartialEq for KeyWrapper<K> {
130    // NB: The unconditional_recursion lint was added in 1.76.0 and can be removed
131    // once the current stable version of Rust is 1.76.0 or higher.
132    #![allow(unknown_lints)]
133    #[allow(clippy::unconditional_recursion)]
134    fn eq(&self, other: &Self) -> bool {
135        self.0.eq(&other.0)
136    }
137}
138
139impl<K: ?Sized + Eq> Eq for KeyWrapper<K> {}
140
141impl<K, Q> Borrow<KeyWrapper<Q>> for KeyRef<K>
142where
143    K: Borrow<Q>,
144    Q: ?Sized,
145{
146    fn borrow(&self) -> &KeyWrapper<Q> {
147        let key = unsafe { &*self.k }.borrow();
148        KeyWrapper::from_ref(key)
149    }
150}
151
152// Struct used to hold a key value pair. Also contains references to previous and next entries
153// so we can maintain the entries in a linked list ordered by their use.
154struct LruEntry<K, V> {
155    key: mem::MaybeUninit<K>,
156    val: mem::MaybeUninit<V>,
157    prev: *mut LruEntry<K, V>,
158    next: *mut LruEntry<K, V>,
159}
160
161impl<K, V> LruEntry<K, V> {
162    fn new(key: K, val: V) -> Self {
163        LruEntry {
164            key: mem::MaybeUninit::new(key),
165            val: mem::MaybeUninit::new(val),
166            prev: ptr::null_mut(),
167            next: ptr::null_mut(),
168        }
169    }
170
171    fn new_sigil() -> Self {
172        LruEntry {
173            key: mem::MaybeUninit::uninit(),
174            val: mem::MaybeUninit::uninit(),
175            prev: ptr::null_mut(),
176            next: ptr::null_mut(),
177        }
178    }
179}
180
181#[cfg(feature = "hashbrown")]
182pub type DefaultHasher = hashbrown::DefaultHashBuilder;
183#[cfg(not(feature = "hashbrown"))]
184pub type DefaultHasher = std::collections::hash_map::RandomState;
185
186/// An LRU Cache
187pub struct LruCache<K, V, S = DefaultHasher> {
188    map: HashMap<KeyRef<K>, NonNull<LruEntry<K, V>>, S>,
189    cap: NonZeroUsize,
190
191    // head and tail are sigil nodes to facilitate inserting entries
192    head: *mut LruEntry<K, V>,
193    tail: *mut LruEntry<K, V>,
194}
195
196impl<K, V, S> Clone for LruCache<K, V, S>
197where
198    K: Hash + PartialEq + Eq + Clone,
199    V: Clone,
200    S: BuildHasher + Clone,
201{
202    fn clone(&self) -> Self {
203        let map_cap = if self.is_unbounded() {
204            self.len()
205        } else {
206            self.cap().get()
207        };
208        let mut new_lru = LruCache::construct(
209            self.cap(),
210            HashMap::with_capacity_and_hasher(map_cap, self.map.hasher().clone()),
211        );
212
213        for (key, value) in self.iter().rev() {
214            new_lru.push(key.clone(), value.clone());
215        }
216
217        new_lru
218    }
219}
220
221impl<K: Hash + Eq, V> LruCache<K, V> {
222    /// Creates a new LRU Cache that holds at most `cap` items.
223    ///
224    /// # Example
225    ///
226    /// ```
227    /// use lru::LruCache;
228    /// use std::num::NonZeroUsize;
229    /// let mut cache: LruCache<isize, &str> = LruCache::new(NonZeroUsize::new(10).unwrap());
230    /// ```
231    pub fn new(cap: NonZeroUsize) -> LruCache<K, V> {
232        LruCache::construct(cap, HashMap::with_capacity(cap.get()))
233    }
234
235    /// Creates a new LRU Cache that holds at most `cap` items without allocating storage space
236    /// for them.
237    ///
238    /// # Example
239    ///
240    /// ```
241    /// use lru::LruCache;
242    /// use std::num::NonZeroUsize;
243    /// let mut cache: LruCache<isize, &str> = LruCache::sparse(NonZeroUsize::new(1_000_000).unwrap());
244    /// ```
245    pub fn sparse(cap: NonZeroUsize) -> LruCache<K, V> {
246        LruCache::construct(cap, HashMap::default())
247    }
248
249    /// Creates a new LRU Cache that never automatically evicts items.
250    ///
251    /// # Example
252    ///
253    /// ```
254    /// use lru::LruCache;
255    /// use std::num::NonZeroUsize;
256    /// let mut cache: LruCache<isize, &str> = LruCache::unbounded();
257    /// ```
258    pub fn unbounded() -> LruCache<K, V> {
259        LruCache::construct(NonZeroUsize::MAX, HashMap::default())
260    }
261}
262
263impl<K: Hash + Eq, V, S: BuildHasher> LruCache<K, V, S> {
264    /// Creates a new LRU Cache that holds at most `cap` items and
265    /// uses the provided hash builder to hash keys.
266    ///
267    /// # Example
268    ///
269    /// ```
270    /// use lru::{LruCache, DefaultHasher};
271    /// use std::num::NonZeroUsize;
272    ///
273    /// let s = DefaultHasher::default();
274    /// let mut cache: LruCache<isize, &str> = LruCache::with_hasher(NonZeroUsize::new(10).unwrap(), s);
275    /// ```
276    pub fn with_hasher(cap: NonZeroUsize, hash_builder: S) -> LruCache<K, V, S> {
277        LruCache::construct(
278            cap,
279            HashMap::with_capacity_and_hasher(cap.into(), hash_builder),
280        )
281    }
282
283    /// Creates a new LRU Cache that never automatically evicts items and
284    /// uses the provided hash builder to hash keys.
285    ///
286    /// # Example
287    ///
288    /// ```
289    /// use lru::{LruCache, DefaultHasher};
290    ///
291    /// let s = DefaultHasher::default();
292    /// let mut cache: LruCache<isize, &str> = LruCache::unbounded_with_hasher(s);
293    /// ```
294    pub fn unbounded_with_hasher(hash_builder: S) -> LruCache<K, V, S> {
295        LruCache::construct(NonZeroUsize::MAX, HashMap::with_hasher(hash_builder))
296    }
297
298    /// Creates a new LRU Cache with the given capacity.
299    fn construct(
300        cap: NonZeroUsize,
301        map: HashMap<KeyRef<K>, NonNull<LruEntry<K, V>>, S>,
302    ) -> LruCache<K, V, S> {
303        // NB: The compiler warns that cache does not need to be marked as mutable if we
304        // declare it as such since we only mutate it inside the unsafe block.
305        let cache = LruCache {
306            map,
307            cap,
308            head: Box::into_raw(Box::new(LruEntry::new_sigil())),
309            tail: Box::into_raw(Box::new(LruEntry::new_sigil())),
310        };
311
312        unsafe {
313            (*cache.head).next = cache.tail;
314            (*cache.tail).prev = cache.head;
315        }
316
317        cache
318    }
319
320    /// Whether this LRU cache is unbounded.
321    fn is_unbounded(&self) -> bool {
322        self.cap() == NonZeroUsize::MAX
323    }
324
325    /// Puts a key-value pair into cache. If the key already exists in the cache, then it updates
326    /// the key's value and returns the old value. Otherwise, `None` is returned.
327    ///
328    /// # Example
329    ///
330    /// ```
331    /// use lru::LruCache;
332    /// use std::num::NonZeroUsize;
333    /// let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
334    ///
335    /// assert_eq!(None, cache.put(1, "a"));
336    /// assert_eq!(None, cache.put(2, "b"));
337    /// assert_eq!(Some("b"), cache.put(2, "beta"));
338    ///
339    /// assert_eq!(cache.get(&1), Some(&"a"));
340    /// assert_eq!(cache.get(&2), Some(&"beta"));
341    /// ```
342    pub fn put(&mut self, k: K, v: V) -> Option<V> {
343        self.capturing_put(k, v, false).map(|(_, v)| v)
344    }
345
346    /// Pushes a key-value pair into the cache. If an entry with key `k` already exists in
347    /// the cache or another cache entry is removed (due to the lru's capacity),
348    /// then it returns the old entry's key-value pair. Otherwise, returns `None`.
349    ///
350    /// # Example
351    ///
352    /// ```
353    /// use lru::LruCache;
354    /// use std::num::NonZeroUsize;
355    /// let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
356    ///
357    /// assert_eq!(None, cache.push(1, "a"));
358    /// assert_eq!(None, cache.push(2, "b"));
359    ///
360    /// // This push call returns (2, "b") because that was previously 2's entry in the cache.
361    /// assert_eq!(Some((2, "b")), cache.push(2, "beta"));
362    ///
363    /// // This push call returns (1, "a") because the cache is at capacity and 1's entry was the lru entry.
364    /// assert_eq!(Some((1, "a")), cache.push(3, "alpha"));
365    ///
366    /// assert_eq!(cache.get(&1), None);
367    /// assert_eq!(cache.get(&2), Some(&"beta"));
368    /// assert_eq!(cache.get(&3), Some(&"alpha"));
369    /// ```
370    pub fn push(&mut self, k: K, v: V) -> Option<(K, V)> {
371        self.capturing_put(k, v, true)
372    }
373
374    // Used internally by `put` and `push` to add a new entry to the lru.
375    // Takes ownership of and returns entries replaced due to the cache's capacity
376    // when `capture` is true.
377    fn capturing_put(&mut self, k: K, mut v: V, capture: bool) -> Option<(K, V)> {
378        let node_ref = self.map.get_mut(&KeyRef { k: &k });
379
380        match node_ref {
381            Some(node_ref) => {
382                // if the key is already in the cache just update its value and move it to the
383                // front of the list
384                let node_ptr: *mut LruEntry<K, V> = node_ref.as_ptr();
385
386                // gets a reference to the node to perform a swap and drops it right after
387                let node_ref = unsafe { &mut (*(*node_ptr).val.as_mut_ptr()) };
388                mem::swap(&mut v, node_ref);
389                let _ = node_ref;
390
391                self.detach(node_ptr);
392                self.attach(node_ptr);
393                Some((k, v))
394            }
395            None => {
396                let (replaced, node) = self.replace_or_create_node(k, v);
397                let node_ptr: *mut LruEntry<K, V> = node.as_ptr();
398
399                self.attach(node_ptr);
400
401                let keyref = unsafe { (*node_ptr).key.as_ptr() };
402                self.map.insert(KeyRef { k: keyref }, node);
403
404                replaced.filter(|_| capture)
405            }
406        }
407    }
408
409    // Used internally to swap out a node if the cache is full or to create a new node if space
410    // is available. Shared between `put`, `push`, and `get_or_(insert|push).*` methods.
411    #[allow(clippy::type_complexity)]
412    fn replace_or_create_node(&mut self, k: K, v: V) -> (Option<(K, V)>, NonNull<LruEntry<K, V>>) {
413        if self.len() == self.cap().get() {
414            // if the cache is full, remove the last entry so we can use it for the new key
415            let old_key = KeyRef {
416                k: unsafe { &(*(*(*self.tail).prev).key.as_ptr()) },
417            };
418            let old_node = self.map.remove(&old_key).unwrap();
419            let node_ptr: *mut LruEntry<K, V> = old_node.as_ptr();
420
421            // read out the node's old key and value and then replace it
422            let replaced = unsafe {
423                (
424                    mem::replace(&mut (*node_ptr).key, mem::MaybeUninit::new(k)).assume_init(),
425                    mem::replace(&mut (*node_ptr).val, mem::MaybeUninit::new(v)).assume_init(),
426                )
427            };
428
429            self.detach(node_ptr);
430
431            (Some(replaced), old_node)
432        } else {
433            // if the cache is not full allocate a new LruEntry
434            (
435                None,
436                NonNull::new(Box::into_raw(Box::new(LruEntry::new(k, v)))).unwrap(),
437            )
438        }
439    }
440
441    /// Returns a reference to the value of the key in the cache or `None` if it is not
442    /// present in the cache. Moves the key to the head of the LRU list if it exists.
443    ///
444    /// # Example
445    ///
446    /// ```
447    /// use lru::LruCache;
448    /// use std::num::NonZeroUsize;
449    /// let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
450    ///
451    /// cache.put(1, "a");
452    /// cache.put(2, "b");
453    /// cache.put(2, "c");
454    /// cache.put(3, "d");
455    ///
456    /// assert_eq!(cache.get(&1), None);
457    /// assert_eq!(cache.get(&2), Some(&"c"));
458    /// assert_eq!(cache.get(&3), Some(&"d"));
459    /// ```
460    pub fn get<'a, Q>(&'a mut self, k: &Q) -> Option<&'a V>
461    where
462        K: Borrow<Q>,
463        Q: Hash + Eq + ?Sized,
464    {
465        if let Some(node) = self.map.get_mut(KeyWrapper::from_ref(k)) {
466            let node_ptr: *mut LruEntry<K, V> = node.as_ptr();
467
468            self.detach(node_ptr);
469            self.attach(node_ptr);
470
471            Some(unsafe { &*(*node_ptr).val.as_ptr() })
472        } else {
473            None
474        }
475    }
476
477    /// Returns a mutable reference to the value of the key in the cache or `None` if it
478    /// is not present in the cache. Moves the key to the head of the LRU list if it exists.
479    ///
480    /// # Example
481    ///
482    /// ```
483    /// use lru::LruCache;
484    /// use std::num::NonZeroUsize;
485    /// let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
486    ///
487    /// cache.put("apple", 8);
488    /// cache.put("banana", 4);
489    /// cache.put("banana", 6);
490    /// cache.put("pear", 2);
491    ///
492    /// assert_eq!(cache.get_mut(&"apple"), None);
493    /// assert_eq!(cache.get_mut(&"banana"), Some(&mut 6));
494    /// assert_eq!(cache.get_mut(&"pear"), Some(&mut 2));
495    /// ```
496    pub fn get_mut<'a, Q>(&'a mut self, k: &Q) -> Option<&'a mut V>
497    where
498        K: Borrow<Q>,
499        Q: Hash + Eq + ?Sized,
500    {
501        if let Some(node) = self.map.get_mut(KeyWrapper::from_ref(k)) {
502            let node_ptr: *mut LruEntry<K, V> = node.as_ptr();
503
504            self.detach(node_ptr);
505            self.attach(node_ptr);
506
507            Some(unsafe { &mut *(*node_ptr).val.as_mut_ptr() })
508        } else {
509            None
510        }
511    }
512
513    /// Returns a key-value references pair of the key in the cache or `None` if it is not
514    /// present in the cache. Moves the key to the head of the LRU list if it exists.
515    ///
516    /// # Example
517    ///
518    /// ```
519    /// use lru::LruCache;
520    /// use std::num::NonZeroUsize;
521    /// let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
522    ///
523    /// cache.put(String::from("1"), "a");
524    /// cache.put(String::from("2"), "b");
525    /// cache.put(String::from("2"), "c");
526    /// cache.put(String::from("3"), "d");
527    ///
528    /// assert_eq!(cache.get_key_value("1"), None);
529    /// assert_eq!(cache.get_key_value("2"), Some((&String::from("2"), &"c")));
530    /// assert_eq!(cache.get_key_value("3"), Some((&String::from("3"), &"d")));
531    /// ```
532    pub fn get_key_value<'a, Q>(&'a mut self, k: &Q) -> Option<(&'a K, &'a V)>
533    where
534        K: Borrow<Q>,
535        Q: Hash + Eq + ?Sized,
536    {
537        if let Some(node) = self.map.get_mut(KeyWrapper::from_ref(k)) {
538            let node_ptr: *mut LruEntry<K, V> = node.as_ptr();
539
540            self.detach(node_ptr);
541            self.attach(node_ptr);
542
543            Some(unsafe { (&*(*node_ptr).key.as_ptr(), &*(*node_ptr).val.as_ptr()) })
544        } else {
545            None
546        }
547    }
548
549    /// Returns a key-value references pair of the key in the cache or `None` if it is not
550    /// present in the cache. The reference to the value of the key is mutable. Moves the key to
551    /// the head of the LRU list if it exists.
552    ///
553    /// # Example
554    ///
555    /// ```
556    /// use lru::LruCache;
557    /// use std::num::NonZeroUsize;
558    /// let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
559    ///
560    /// cache.put(1, "a");
561    /// cache.put(2, "b");
562    /// let (k, v) = cache.get_key_value_mut(&1).unwrap();
563    /// assert_eq!(k, &1);
564    /// assert_eq!(v, &mut "a");
565    /// *v = "aa";
566    /// cache.put(3, "c");
567    /// assert_eq!(cache.get_key_value(&2), None);
568    /// assert_eq!(cache.get_key_value(&1), Some((&1, &"aa")));
569    /// assert_eq!(cache.get_key_value(&3), Some((&3, &"c")));
570    /// ```
571    pub fn get_key_value_mut<'a, Q>(&'a mut self, k: &Q) -> Option<(&'a K, &'a mut V)>
572    where
573        K: Borrow<Q>,
574        Q: Hash + Eq + ?Sized,
575    {
576        if let Some(node) = self.map.get_mut(KeyWrapper::from_ref(k)) {
577            let node_ptr: *mut LruEntry<K, V> = node.as_ptr();
578
579            self.detach(node_ptr);
580            self.attach(node_ptr);
581
582            Some(unsafe {
583                (
584                    &*(*node_ptr).key.as_ptr(),
585                    &mut *(*node_ptr).val.as_mut_ptr(),
586                )
587            })
588        } else {
589            None
590        }
591    }
592
593    /// Returns a reference to the value of the key in the cache if it is
594    /// present in the cache and moves the key to the head of the LRU list.
595    /// If the key does not exist, the provided `FnOnce` is used to populate
596    /// the list and a reference is returned.
597    ///
598    /// # Example
599    ///
600    /// ```
601    /// use lru::LruCache;
602    /// use std::num::NonZeroUsize;
603    /// let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
604    ///
605    /// cache.put(1, "a");
606    /// cache.put(2, "b");
607    /// cache.put(2, "c");
608    /// cache.put(3, "d");
609    ///
610    /// assert_eq!(cache.get_or_insert(2, ||"a"), &"c");
611    /// assert_eq!(cache.get_or_insert(3, ||"a"), &"d");
612    /// assert_eq!(cache.get_or_insert(1, ||"a"), &"a");
613    /// assert_eq!(cache.get_or_insert(1, ||"b"), &"a");
614    /// ```
615    #[inline]
616    pub fn get_or_insert<F>(&mut self, k: K, f: F) -> &V
617    where
618        F: FnOnce() -> V,
619    {
620        self.get_or_push(k, f).0
621    }
622
623    /// Like [`Self::get_or_insert`], but also returns the entry evicted to
624    /// make room, if any.
625    ///
626    /// # Example
627    ///
628    /// ```
629    /// use lru::LruCache;
630    /// use std::num::NonZeroUsize;
631    /// let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
632    ///
633    /// cache.put(1, "a");
634    /// cache.put(2, "b");
635    /// cache.put(2, "c");
636    /// cache.put(3, "d");
637    ///
638    /// assert_eq!(cache.get_or_push(2, ||"a"), (&"c", None));
639    /// assert_eq!(cache.get_or_push(3, ||"a"), (&"d", None));
640    /// assert_eq!(cache.get_or_push(1, ||"a"), (&"a", Some((2, "c"))));
641    /// assert_eq!(cache.get_or_push(1, ||"b"), (&"a", None));
642    /// ```
643    #[inline]
644    pub fn get_or_push<F>(&mut self, k: K, f: F) -> (&V, Option<(K, V)>)
645    where
646        F: FnOnce() -> V,
647    {
648        self.get_or_push_with_key(k, |_| f())
649    }
650
651    /// Returns a reference to the value of the key in the cache if it is
652    /// present in the cache and moves the key to the head of the LRU list.
653    /// If the key does not exist, the provided `FnOnce` is used by passing
654    /// a reference to the key to populate the list and a reference is returned.
655    ///
656    /// # Example
657    ///
658    /// ```
659    /// use lru::LruCache;
660    /// use std::num::NonZeroUsize;
661    /// let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
662    ///
663    /// cache.put("One", 1);
664    /// cache.put("Two", 2);
665    /// cache.put("Two", 3);
666    /// cache.put("Three", 4);
667    ///
668    /// assert_eq!(cache.get_or_insert_with_key("Two", |_|1), &3);
669    /// assert_eq!(cache.get_or_insert_with_key("Three", |k|k.len()), &4);
670    /// assert_eq!(cache.get_or_insert_with_key("One", |_|1), &1);
671    /// assert_eq!(cache.get_or_insert_with_key("One", |k|k.len()), &1);
672    /// ```
673    #[inline]
674    pub fn get_or_insert_with_key<F>(&mut self, k: K, f: F) -> &V
675    where
676        F: FnOnce(&K) -> V,
677    {
678        self.get_or_push_with_key(k, f).0
679    }
680
681    /// Like [`Self::get_or_insert_with_key`], but also returns the entry
682    /// evicted to make room, if any.
683    ///
684    /// # Example
685    ///
686    /// ```
687    /// use lru::LruCache;
688    /// use std::num::NonZeroUsize;
689    /// let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
690    ///
691    /// cache.put("One", 1);
692    /// cache.put("Two", 2);
693    /// cache.put("Two", 3);
694    /// cache.put("Three", 4);
695    ///
696    /// assert_eq!(cache.get_or_push_with_key("Two", |_|1), (&3, None));
697    /// assert_eq!(cache.get_or_push_with_key("Three", |k|k.len()), (&4, None));
698    /// assert_eq!(cache.get_or_push_with_key("One", |_|1), (&1, Some(("Two", 3))));
699    /// assert_eq!(cache.get_or_push_with_key("One", |k|k.len()), (&1, None));
700    /// ```
701    pub fn get_or_push_with_key<F>(&mut self, k: K, f: F) -> (&V, Option<(K, V)>)
702    where
703        F: FnOnce(&K) -> V,
704    {
705        if let Some(node) = self.map.get_mut(&KeyRef { k: &k }) {
706            let node_ptr: *mut LruEntry<K, V> = node.as_ptr();
707
708            self.detach(node_ptr);
709            self.attach(node_ptr);
710
711            (unsafe { &*(*node_ptr).val.as_ptr() }, None)
712        } else {
713            let v = f(&k);
714            let (replaced, node) = self.replace_or_create_node(k, v);
715            let node_ptr: *mut LruEntry<K, V> = node.as_ptr();
716
717            self.attach(node_ptr);
718
719            let keyref = unsafe { (*node_ptr).key.as_ptr() };
720            self.map.insert(KeyRef { k: keyref }, node);
721
722            (unsafe { &*(*node_ptr).val.as_ptr() }, replaced)
723        }
724    }
725
726    /// Returns a reference to the value of the key in the cache if it is
727    /// present in the cache and moves the key to the head of the LRU list.
728    /// If the key does not exist, the provided `FnOnce` is used to populate
729    /// the list and a reference is returned. The value referenced by the
730    /// key is only cloned (using `to_owned()`) if it doesn't exist in the
731    /// cache.
732    ///
733    /// # Example
734    ///
735    /// ```
736    /// use lru::LruCache;
737    /// use std::num::NonZeroUsize;
738    /// use std::rc::Rc;
739    ///
740    /// let key1 = Rc::new("1".to_owned());
741    /// let key2 = Rc::new("2".to_owned());
742    /// let mut cache = LruCache::<Rc<String>, String>::new(NonZeroUsize::new(2).unwrap());
743    ///
744    /// assert_eq!(cache.get_or_insert_ref(&key1, ||"One".to_owned()), "One");
745    /// assert_eq!(cache.get_or_insert_ref(&key2, ||"Two".to_owned()), "Two");
746    /// assert_eq!(cache.get_or_insert_ref(&key2, ||"Not two".to_owned()), "Two");
747    /// assert_eq!(cache.get_or_insert_ref(&key2, ||"Again not two".to_owned()), "Two");
748    ///
749    /// assert_eq!(Rc::strong_count(&key1), 2);
750    /// // `key2` was only cloned once even though we queried it 3 times.
751    /// assert_eq!(Rc::strong_count(&key2), 2);
752    /// ```
753    #[inline]
754    pub fn get_or_insert_ref<'a, Q, F>(&'a mut self, k: &'_ Q, f: F) -> &'a V
755    where
756        K: Borrow<Q>,
757        Q: Hash + Eq + ?Sized + alloc::borrow::ToOwned<Owned = K>,
758        F: FnOnce() -> V,
759    {
760        self.get_or_push_ref(k, f).0
761    }
762
763    /// Like [`Self::get_or_insert_ref`], but also returns the entry evicted to
764    /// make room, if any.
765    ///
766    /// # Example
767    ///
768    /// ```
769    /// use lru::LruCache;
770    /// use std::num::NonZeroUsize;
771    /// use std::rc::Rc;
772    ///
773    /// let key1 = Rc::new("1".to_owned());
774    /// let key2 = Rc::new("2".to_owned());
775    /// let key3 = Rc::new("3".to_owned());
776    /// let mut cache = LruCache::<Rc<String>, String>::new(NonZeroUsize::new(2).unwrap());
777    ///
778    /// assert_eq!(
779    ///     cache.get_or_push_ref(&key1, ||"One".to_owned()),
780    ///     (&"One".to_owned(), None),
781    /// );
782    /// assert_eq!(
783    ///     cache.get_or_push_ref(&key2, ||"Two".to_owned()),
784    ///     (&"Two".to_owned(), None),
785    /// );
786    /// assert_eq!(
787    ///     cache.get_or_push_ref(&key3, ||"Three".to_owned()),
788    ///     (
789    ///         &"Three".to_owned(),
790    ///         Some((key1.clone(), "One".to_owned())),
791    ///     ),
792    /// );
793    /// assert_eq!(
794    ///     cache.get_or_push_ref(&key2, ||"Not two".to_owned()),
795    ///     (&"Two".to_owned(), None),
796    /// );
797    /// assert_eq!(
798    ///     cache.get_or_push_ref(&key2, ||"Again not two".to_owned()),
799    ///     (&"Two".to_owned(), None),
800    /// );
801    /// assert_eq!(
802    ///     cache.get_or_push_ref(&key1, ||"One again".to_owned()),
803    ///     (
804    ///         &"One again".to_owned(),
805    ///         Some((key3.clone(), "Three".to_owned())),
806    ///     ),
807    /// );
808    ///
809    /// assert_eq!(Rc::strong_count(&key1), 2);
810    /// // `key2` was only cloned once even though we queried it 3 times.
811    /// assert_eq!(Rc::strong_count(&key2), 2);
812    /// assert_eq!(Rc::strong_count(&key3), 1);
813    /// ```
814    pub fn get_or_push_ref<'a, Q, F>(&'a mut self, k: &'_ Q, f: F) -> (&'a V, Option<(K, V)>)
815    where
816        K: Borrow<Q>,
817        Q: Hash + Eq + ?Sized + alloc::borrow::ToOwned<Owned = K>,
818        F: FnOnce() -> V,
819    {
820        if let Some(node) = self.map.get_mut(KeyWrapper::from_ref(k)) {
821            let node_ptr: *mut LruEntry<K, V> = node.as_ptr();
822
823            self.detach(node_ptr);
824            self.attach(node_ptr);
825
826            (unsafe { &*(*node_ptr).val.as_ptr() }, None)
827        } else {
828            let v = f();
829            let (replaced, node) = self.replace_or_create_node(k.to_owned(), v);
830            let node_ptr: *mut LruEntry<K, V> = node.as_ptr();
831
832            self.attach(node_ptr);
833
834            let keyref = unsafe { (*node_ptr).key.as_ptr() };
835            self.map.insert(KeyRef { k: keyref }, node);
836
837            (unsafe { &*(*node_ptr).val.as_ptr() }, replaced)
838        }
839    }
840
841    /// Returns a reference to the value of the key in the cache if it is
842    /// present in the cache and moves the key to the head of the LRU list.
843    /// If the key does not exist, the provided `FnOnce` is used to populate
844    /// the list and a reference is returned. If `FnOnce` returns `Err`,
845    /// returns the `Err`.
846    ///
847    /// # Example
848    ///
849    /// ```
850    /// use lru::LruCache;
851    /// use std::num::NonZeroUsize;
852    /// let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
853    ///
854    /// cache.put(1, "a");
855    /// cache.put(2, "b");
856    /// cache.put(2, "c");
857    /// cache.put(3, "d");
858    ///
859    /// let f = ||->Result<&str, String> {Err("failed".to_owned())};
860    /// let a = ||->Result<&str, String> {Ok("a")};
861    /// let b = ||->Result<&str, String> {Ok("b")};
862    /// assert_eq!(cache.try_get_or_insert(2, a), Ok(&"c"));
863    /// assert_eq!(cache.try_get_or_insert(3, a), Ok(&"d"));
864    /// assert_eq!(cache.try_get_or_insert(4, f), Err("failed".to_owned()));
865    /// assert_eq!(cache.try_get_or_insert(5, b), Ok(&"b"));
866    /// assert_eq!(cache.try_get_or_insert(5, a), Ok(&"b"));
867    /// ```
868    #[inline]
869    pub fn try_get_or_insert<F, E>(&mut self, k: K, f: F) -> Result<&V, E>
870    where
871        F: FnOnce() -> Result<V, E>,
872    {
873        self.try_get_or_push(k, f).map(|(v, _)| v)
874    }
875
876    /// Like [`Self::try_get_or_insert`], but also returns the entry evicted to
877    /// make room, if any.
878    ///
879    /// # Example
880    ///
881    /// ```
882    /// use lru::LruCache;
883    /// use std::num::NonZeroUsize;
884    /// let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
885    ///
886    /// cache.put(1, "a");
887    /// cache.put(2, "b");
888    /// cache.put(2, "c");
889    /// cache.put(3, "d");
890    ///
891    /// let f = ||->Result<&str, String> {Err("failed".to_owned())};
892    /// let a = ||->Result<&str, String> {Ok("a")};
893    /// let b = ||->Result<&str, String> {Ok("b")};
894    /// assert_eq!(cache.try_get_or_push(2, a), Ok((&"c", None)));
895    /// assert_eq!(cache.try_get_or_push(3, a), Ok((&"d", None)));
896    /// assert_eq!(cache.try_get_or_push(4, f), Err("failed".to_owned()));
897    /// assert_eq!(cache.try_get_or_push(5, b), Ok((&"b", Some((2, "c")))));
898    /// assert_eq!(cache.try_get_or_push(5, a), Ok((&"b", None)));
899    /// ```
900    #[inline]
901    #[allow(clippy::type_complexity)]
902    pub fn try_get_or_push<F, E>(&mut self, k: K, f: F) -> Result<(&V, Option<(K, V)>), E>
903    where
904        F: FnOnce() -> Result<V, E>,
905    {
906        self.try_get_or_push_with_key(k, |_| f())
907    }
908
909    /// Returns a reference to the value of the key in the cache if it is
910    /// present in the cache and moves the key to the head of the LRU list.
911    /// If the key does not exist, the provided `FnOnce` is used by passing
912    /// a reference to the key to populate the list and a reference is returned.
913    /// If `FnOnce` returns `Err`, returns the `Err`.
914    ///
915    /// # Example
916    ///
917    /// ```
918    /// use lru::LruCache;
919    /// use std::num::NonZeroUsize;
920    /// let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
921    ///
922    /// cache.put("One", 1);
923    /// cache.put("Two", 2);
924    /// cache.put("Two", 3);
925    /// cache.put("Three", 4);
926    ///
927    /// let f = |_: &&str|->Result<usize, String> {Err("failed".to_owned())};
928    /// let len = |k: &&str|->Result<usize, String> {Ok(k.len())};
929    /// let zero = |_: &&str|->Result<usize, String> {Ok(0)};
930    /// assert_eq!(cache.try_get_or_insert_with_key("Two", len), Ok(&3));
931    /// assert_eq!(cache.try_get_or_insert_with_key("Three", len), Ok(&4));
932    /// assert_eq!(cache.try_get_or_insert_with_key("Four", f), Err("failed".to_owned()));
933    /// assert_eq!(cache.try_get_or_insert_with_key("Five", len), Ok(&4));
934    /// assert_eq!(cache.try_get_or_insert_with_key("Five", zero), Ok(&4));
935    /// ```
936    #[inline]
937    pub fn try_get_or_insert_with_key<F, E>(&mut self, k: K, f: F) -> Result<&V, E>
938    where
939        F: FnOnce(&K) -> Result<V, E>,
940    {
941        self.try_get_or_push_with_key(k, f).map(|(v, _)| v)
942    }
943
944    /// Like [`Self::try_get_or_insert_with_key`], but also returns the entry
945    /// evicted to make room, if any.
946    ///
947    /// # Example
948    ///
949    /// ```
950    /// use lru::LruCache;
951    /// use std::num::NonZeroUsize;
952    /// let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
953    ///
954    /// cache.put("One", 1);
955    /// cache.put("Two", 2);
956    /// cache.put("Two", 3);
957    /// cache.put("Three", 4);
958    ///
959    /// let f = |_: &&str|->Result<usize, String> {Err("failed".to_owned())};
960    /// let len = |k: &&str|->Result<usize, String> {Ok(k.len())};
961    /// let zero = |_: &&str|->Result<usize, String> {Ok(0)};
962    /// assert_eq!(cache.try_get_or_push_with_key("Two", len), Ok((&3, None)));
963    /// assert_eq!(cache.try_get_or_push_with_key("Three", len), Ok((&4, None)));
964    /// assert_eq!(cache.try_get_or_push_with_key("Four", f), Err("failed".to_owned()));
965    /// assert_eq!(cache.try_get_or_push_with_key("Five", len), Ok((&4, Some(("Two", 3)))));
966    /// assert_eq!(cache.try_get_or_push_with_key("Five", zero), Ok((&4, None)));
967    /// ```
968    #[allow(clippy::type_complexity)]
969    pub fn try_get_or_push_with_key<F, E>(&mut self, k: K, f: F) -> Result<(&V, Option<(K, V)>), E>
970    where
971        F: FnOnce(&K) -> Result<V, E>,
972    {
973        if let Some(node) = self.map.get_mut(&KeyRef { k: &k }) {
974            let node_ptr: *mut LruEntry<K, V> = node.as_ptr();
975
976            self.detach(node_ptr);
977            self.attach(node_ptr);
978
979            unsafe { Ok((&*(*node_ptr).val.as_ptr(), None)) }
980        } else {
981            let v = f(&k)?;
982            let (replaced, node) = self.replace_or_create_node(k, v);
983            let node_ptr: *mut LruEntry<K, V> = node.as_ptr();
984
985            self.attach(node_ptr);
986
987            let keyref = unsafe { (*node_ptr).key.as_ptr() };
988            self.map.insert(KeyRef { k: keyref }, node);
989
990            Ok((unsafe { &*(*node_ptr).val.as_ptr() }, replaced))
991        }
992    }
993
994    /// Returns a reference to the value of the key in the cache if it is
995    /// present in the cache and moves the key to the head of the LRU list.
996    /// If the key does not exist, the provided `FnOnce` is used to populate
997    /// the list and a reference is returned. If `FnOnce` returns `Err`,
998    /// returns the `Err`. The value referenced by the key is only cloned
999    /// (using `to_owned()`) if it doesn't exist in the cache and `FnOnce`
1000    /// succeeds.
1001    ///
1002    /// # Example
1003    ///
1004    /// ```
1005    /// use lru::LruCache;
1006    /// use std::num::NonZeroUsize;
1007    /// use std::rc::Rc;
1008    ///
1009    /// let key1 = Rc::new("1".to_owned());
1010    /// let key2 = Rc::new("2".to_owned());
1011    /// let mut cache = LruCache::<Rc<String>, String>::new(NonZeroUsize::new(2).unwrap());
1012    /// let f = ||->Result<String, ()> {Err(())};
1013    /// let a = ||->Result<String, ()> {Ok("One".to_owned())};
1014    /// let b = ||->Result<String, ()> {Ok("Two".to_owned())};
1015    ///
1016    /// assert_eq!(cache.try_get_or_insert_ref(&key1, a), Ok(&"One".to_owned()));
1017    /// assert_eq!(cache.try_get_or_insert_ref(&key2, f), Err(()));
1018    /// assert_eq!(cache.try_get_or_insert_ref(&key2, b), Ok(&"Two".to_owned()));
1019    /// assert_eq!(cache.try_get_or_insert_ref(&key2, a), Ok(&"Two".to_owned()));
1020    ///
1021    /// assert_eq!(Rc::strong_count(&key1), 2);
1022    /// // `key2` was only cloned once even though we queried it 3 times.
1023    /// assert_eq!(Rc::strong_count(&key2), 2);
1024    /// ```
1025    #[inline]
1026    pub fn try_get_or_insert_ref<'a, Q, F, E>(&'a mut self, k: &'_ Q, f: F) -> Result<&'a V, E>
1027    where
1028        K: Borrow<Q>,
1029        Q: Hash + Eq + ?Sized + alloc::borrow::ToOwned<Owned = K>,
1030        F: FnOnce() -> Result<V, E>,
1031    {
1032        self.try_get_or_push_ref(k, f).map(|(v, _)| v)
1033    }
1034
1035    /// Like [`Self::try_get_or_insert_ref`], but also returns the entry
1036    /// evicted to make room, if any.
1037    ///
1038    /// # Example
1039    ///
1040    /// ```
1041    /// use lru::LruCache;
1042    /// use std::num::NonZeroUsize;
1043    /// use std::rc::Rc;
1044    ///
1045    /// let key1 = Rc::new("1".to_owned());
1046    /// let key2 = Rc::new("2".to_owned());
1047    /// let key3 = Rc::new("3".to_owned());
1048    /// let mut cache = LruCache::<Rc<String>, String>::new(NonZeroUsize::new(2).unwrap());
1049    /// let f = ||->Result<String, ()> {Err(())};
1050    /// let a = ||->Result<String, ()> {Ok("One".to_owned())};
1051    /// let b = ||->Result<String, ()> {Ok("Two".to_owned())};
1052    /// let c = ||->Result<String, ()> {Ok("Three".to_owned())};
1053    ///
1054    /// assert_eq!(
1055    ///     cache.try_get_or_push_ref(&key1, a),
1056    ///     Ok((&"One".to_owned(), None)),
1057    /// );
1058    /// assert_eq!(
1059    ///     cache.try_get_or_push_ref(&key2, f),
1060    ///     Err(()),
1061    /// );
1062    /// assert_eq!(
1063    ///     cache.try_get_or_push_ref(&key2, b),
1064    ///     Ok((&"Two".to_owned(), None)),
1065    /// );
1066    /// assert_eq!(
1067    ///     cache.try_get_or_push_ref(&key3, c),
1068    ///     Ok((
1069    ///         &"Three".to_owned(),
1070    ///         Some((key1.clone(), "One".to_owned())),
1071    ///     )),
1072    /// );
1073    /// assert_eq!(
1074    ///     cache.try_get_or_push_ref(&key2, a),
1075    ///     Ok((&"Two".to_owned(), None)),
1076    /// );
1077    ///
1078    /// assert_eq!(Rc::strong_count(&key1), 1);
1079    /// // `key2` was only cloned once even though we queried it 3 times.
1080    /// assert_eq!(Rc::strong_count(&key2), 2);
1081    /// assert_eq!(Rc::strong_count(&key3), 2);
1082    /// ```
1083    #[allow(clippy::type_complexity)]
1084    pub fn try_get_or_push_ref<'a, Q, F, E>(
1085        &'a mut self,
1086        k: &'_ Q,
1087        f: F,
1088    ) -> Result<(&'a V, Option<(K, V)>), E>
1089    where
1090        K: Borrow<Q>,
1091        Q: Hash + Eq + ?Sized + alloc::borrow::ToOwned<Owned = K>,
1092        F: FnOnce() -> Result<V, E>,
1093    {
1094        if let Some(node) = self.map.get_mut(KeyWrapper::from_ref(k)) {
1095            let node_ptr: *mut LruEntry<K, V> = node.as_ptr();
1096
1097            self.detach(node_ptr);
1098            self.attach(node_ptr);
1099
1100            unsafe { Ok((&*(*node_ptr).val.as_ptr(), None)) }
1101        } else {
1102            let v = f()?;
1103            let (replaced, node) = self.replace_or_create_node(k.to_owned(), v);
1104            let node_ptr: *mut LruEntry<K, V> = node.as_ptr();
1105
1106            self.attach(node_ptr);
1107
1108            let keyref = unsafe { (*node_ptr).key.as_ptr() };
1109            self.map.insert(KeyRef { k: keyref }, node);
1110
1111            Ok((unsafe { &*(*node_ptr).val.as_ptr() }, replaced))
1112        }
1113    }
1114
1115    /// Returns a mutable reference to the value of the key in the cache if it is
1116    /// present in the cache and moves the key to the head of the LRU list.
1117    /// If the key does not exist, the provided `FnOnce` is used to populate
1118    /// the list and a mutable reference is returned.
1119    ///
1120    /// # Example
1121    ///
1122    /// ```
1123    /// use lru::LruCache;
1124    /// use std::num::NonZeroUsize;
1125    /// let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
1126    ///
1127    /// cache.put(1, "a");
1128    /// cache.put(2, "b");
1129    ///
1130    /// let v = cache.get_or_insert_mut(2, ||"c");
1131    /// assert_eq!(v, &"b");
1132    /// *v = "d";
1133    /// assert_eq!(cache.get_or_insert_mut(2, ||"e"), &mut "d");
1134    /// assert_eq!(cache.get_or_insert_mut(3, ||"f"), &mut "f");
1135    /// assert_eq!(cache.get_or_insert_mut(3, ||"e"), &mut "f");
1136    /// ```
1137    #[inline]
1138    pub fn get_or_insert_mut<F>(&mut self, k: K, f: F) -> &mut V
1139    where
1140        F: FnOnce() -> V,
1141    {
1142        self.get_or_push_mut(k, f).0
1143    }
1144
1145    /// Like [`Self::get_or_insert_mut`], but also returns the entry evicted to
1146    /// make room, if any.
1147    ///
1148    /// # Example
1149    ///
1150    /// ```
1151    /// use lru::LruCache;
1152    /// use std::num::NonZeroUsize;
1153    /// let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
1154    ///
1155    /// cache.put(1, "a");
1156    /// cache.put(2, "b");
1157    /// cache.put(2, "c");
1158    /// cache.put(3, "d");
1159    ///
1160    /// assert_eq!(cache.get_or_push_mut(2, ||"a"), (&mut "c", None));
1161    /// assert_eq!(cache.get_or_push_mut(3, ||"a"), (&mut "d", None));
1162    /// assert_eq!(cache.get_or_push_mut(1, ||"a"), (&mut "a", Some((2, "c"))));
1163    /// assert_eq!(cache.get_or_push_mut(1, ||"b"), (&mut "a", None));
1164    /// ```
1165    #[inline]
1166    #[allow(clippy::type_complexity)]
1167    pub fn get_or_push_mut<F>(&mut self, k: K, f: F) -> (&mut V, Option<(K, V)>)
1168    where
1169        F: FnOnce() -> V,
1170    {
1171        self.get_or_push_mut_with_key(k, |_| f())
1172    }
1173
1174    /// Returns a mutable reference to the value of the key in the cache if it is
1175    /// present in the cache and moves the key to the head of the LRU list.
1176    /// If the key does not exist, the provided `FnOnce` is used by passing
1177    /// a reference to the key to populate the list and a mutable reference
1178    /// is returned.
1179    ///
1180    /// # Example
1181    ///
1182    /// ```
1183    /// use lru::LruCache;
1184    /// use std::num::NonZeroUsize;
1185    /// let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
1186    ///
1187    /// cache.put("One", 1);
1188    /// cache.put("Two", 2);
1189    /// cache.put("Two", 3);
1190    /// cache.put("Three", 4);
1191    ///
1192    /// assert_eq!(cache.get_or_insert_mut_with_key("Two", |_|1), &mut 3);
1193    /// assert_eq!(cache.get_or_insert_mut_with_key("Three", |k|k.len()), &mut 4);
1194    /// assert_eq!(cache.get_or_insert_mut_with_key("One", |_|1), &mut 1);
1195    /// assert_eq!(cache.get_or_insert_mut_with_key("One", |k|k.len()), &mut 1);
1196    /// ```
1197    #[inline]
1198    pub fn get_or_insert_mut_with_key<F>(&mut self, k: K, f: F) -> &mut V
1199    where
1200        F: FnOnce(&K) -> V,
1201    {
1202        self.get_or_push_mut_with_key(k, f).0
1203    }
1204
1205    /// Like [`Self::get_or_insert_mut_with_key`], but also returns the entry
1206    /// evicted to make room, if any.
1207    ///
1208    /// # Example
1209    ///
1210    /// ```
1211    /// use lru::LruCache;
1212    /// use std::num::NonZeroUsize;
1213    /// let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
1214    ///
1215    /// cache.put("One", 1);
1216    /// cache.put("Two", 2);
1217    /// cache.put("Two", 3);
1218    /// cache.put("Three", 4);
1219    ///
1220    /// assert_eq!(cache.get_or_push_mut_with_key("Two", |_|1), (&mut 3, None));
1221    /// assert_eq!(cache.get_or_push_mut_with_key("Three", |k|k.len()), (&mut 4, None));
1222    /// assert_eq!(cache.get_or_push_mut_with_key("One", |_|1), (&mut 1, Some(("Two", 3))));
1223    /// assert_eq!(cache.get_or_push_mut_with_key("One", |k|k.len()), (&mut 1, None));
1224    /// ```
1225    #[allow(clippy::type_complexity)]
1226    pub fn get_or_push_mut_with_key<F>(&mut self, k: K, f: F) -> (&mut V, Option<(K, V)>)
1227    where
1228        F: FnOnce(&K) -> V,
1229    {
1230        if let Some(node) = self.map.get_mut(&KeyRef { k: &k }) {
1231            let node_ptr: *mut LruEntry<K, V> = node.as_ptr();
1232
1233            self.detach(node_ptr);
1234            self.attach(node_ptr);
1235
1236            (unsafe { &mut *(*node_ptr).val.as_mut_ptr() }, None)
1237        } else {
1238            let v = f(&k);
1239            let (replaced, node) = self.replace_or_create_node(k, v);
1240            let node_ptr: *mut LruEntry<K, V> = node.as_ptr();
1241
1242            self.attach(node_ptr);
1243
1244            let keyref = unsafe { (*node_ptr).key.as_ptr() };
1245            self.map.insert(KeyRef { k: keyref }, node);
1246
1247            (unsafe { &mut *(*node_ptr).val.as_mut_ptr() }, replaced)
1248        }
1249    }
1250
1251    /// Returns a mutable reference to the value of the key in the cache if it is
1252    /// present in the cache and moves the key to the head of the LRU list.
1253    /// If the key does not exist, the provided `FnOnce` is used to populate
1254    /// the list and a mutable reference is returned. The value referenced by the
1255    /// key is only cloned (using `to_owned()`) if it doesn't exist in the cache.
1256    ///
1257    /// # Example
1258    ///
1259    /// ```
1260    /// use lru::LruCache;
1261    /// use std::num::NonZeroUsize;
1262    /// use std::rc::Rc;
1263    ///
1264    /// let key1 = Rc::new("1".to_owned());
1265    /// let key2 = Rc::new("2".to_owned());
1266    /// let mut cache = LruCache::<Rc<String>, &'static str>::new(NonZeroUsize::new(2).unwrap());
1267    /// cache.get_or_insert_mut_ref(&key1, ||"One");
1268    /// let v = cache.get_or_insert_mut_ref(&key2, ||"Two");
1269    /// *v = "New two";
1270    /// assert_eq!(cache.get_or_insert_mut_ref(&key2, ||"Two"), &mut "New two");
1271    /// assert_eq!(Rc::strong_count(&key1), 2);
1272    /// // `key2` was only cloned once even though we queried it 2 times.
1273    /// assert_eq!(Rc::strong_count(&key2), 2);
1274    /// ```
1275    #[inline]
1276    pub fn get_or_insert_mut_ref<'a, Q, F>(&'a mut self, k: &'_ Q, f: F) -> &'a mut V
1277    where
1278        K: Borrow<Q>,
1279        Q: Hash + Eq + ?Sized + alloc::borrow::ToOwned<Owned = K>,
1280        F: FnOnce() -> V,
1281    {
1282        self.get_or_push_mut_ref(k, f).0
1283    }
1284
1285    /// Like [`Self::get_or_insert_mut_ref`], but also returns the entry
1286    /// evicted to make room, if any.
1287    ///
1288    /// # Example
1289    ///
1290    /// ```
1291    /// use lru::LruCache;
1292    /// use std::num::NonZeroUsize;
1293    /// use std::rc::Rc;
1294    ///
1295    /// let key1 = Rc::new("1".to_owned());
1296    /// let key2 = Rc::new("2".to_owned());
1297    /// let key3 = Rc::new("3".to_owned());
1298    /// let mut cache = LruCache::<Rc<String>, String>::new(NonZeroUsize::new(2).unwrap());
1299    ///
1300    /// assert_eq!(
1301    ///     cache.get_or_push_mut_ref(&key1, ||"One".to_owned()),
1302    ///     (&mut "One".to_owned(), None),
1303    /// );
1304    /// assert_eq!(
1305    ///     cache.get_or_push_mut_ref(&key2, ||"Two".to_owned()),
1306    ///     (&mut "Two".to_owned(), None),
1307    /// );
1308    /// assert_eq!(
1309    ///     cache.get_or_push_mut_ref(&key3, ||"Three".to_owned()),
1310    ///     (
1311    ///         &mut "Three".to_owned(),
1312    ///         Some((key1.clone(), "One".to_owned())),
1313    ///     ),
1314    /// );
1315    /// assert_eq!(
1316    ///     cache.get_or_push_mut_ref(&key2, ||"Not two".to_owned()),
1317    ///     (&mut "Two".to_owned(), None),
1318    /// );
1319    /// assert_eq!(
1320    ///     cache.get_or_push_mut_ref(&key2, ||"Again not two".to_owned()),
1321    ///     (&mut "Two".to_owned(), None),
1322    /// );
1323    /// assert_eq!(
1324    ///     cache.get_or_push_mut_ref(&key1, ||"One again".to_owned()),
1325    ///     (
1326    ///         &mut "One again".to_owned(),
1327    ///         Some((key3.clone(), "Three".to_owned())),
1328    ///     ),
1329    /// );
1330    ///
1331    /// assert_eq!(Rc::strong_count(&key1), 2);
1332    /// // `key2` was only cloned once even though we queried it 3 times.
1333    /// assert_eq!(Rc::strong_count(&key2), 2);
1334    /// assert_eq!(Rc::strong_count(&key3), 1);
1335    /// ```
1336    #[allow(clippy::type_complexity)]
1337    pub fn get_or_push_mut_ref<'a, Q, F>(
1338        &'a mut self,
1339        k: &'_ Q,
1340        f: F,
1341    ) -> (&'a mut V, Option<(K, V)>)
1342    where
1343        K: Borrow<Q>,
1344        Q: Hash + Eq + ?Sized + alloc::borrow::ToOwned<Owned = K>,
1345        F: FnOnce() -> V,
1346    {
1347        if let Some(node) = self.map.get_mut(KeyWrapper::from_ref(k)) {
1348            let node_ptr: *mut LruEntry<K, V> = node.as_ptr();
1349
1350            self.detach(node_ptr);
1351            self.attach(node_ptr);
1352
1353            (unsafe { &mut *(*node_ptr).val.as_mut_ptr() }, None)
1354        } else {
1355            let v = f();
1356            let (replaced, node) = self.replace_or_create_node(k.to_owned(), v);
1357            let node_ptr: *mut LruEntry<K, V> = node.as_ptr();
1358
1359            self.attach(node_ptr);
1360
1361            let keyref = unsafe { (*node_ptr).key.as_ptr() };
1362            self.map.insert(KeyRef { k: keyref }, node);
1363
1364            (unsafe { &mut *(*node_ptr).val.as_mut_ptr() }, replaced)
1365        }
1366    }
1367
1368    /// Returns a mutable reference to the value of the key in the cache if it is
1369    /// present in the cache and moves the key to the head of the LRU list.
1370    /// If the key does not exist, the provided `FnOnce` is used to populate
1371    /// the list and a mutable reference is returned. If `FnOnce` returns `Err`,
1372    /// returns the `Err`.
1373    ///
1374    /// # Example
1375    ///
1376    /// ```
1377    /// use lru::LruCache;
1378    /// use std::num::NonZeroUsize;
1379    /// let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
1380    ///
1381    /// cache.put(1, "a");
1382    /// cache.put(2, "b");
1383    /// cache.put(2, "c");
1384    ///
1385    /// let f = ||->Result<&str, String> {Err("failed".to_owned())};
1386    /// let a = ||->Result<&str, String> {Ok("a")};
1387    /// let b = ||->Result<&str, String> {Ok("b")};
1388    /// if let Ok(v) = cache.try_get_or_insert_mut(2, a) {
1389    ///     *v = "d";
1390    /// }
1391    /// assert_eq!(cache.try_get_or_insert_mut(2, a), Ok(&mut "d"));
1392    /// assert_eq!(cache.try_get_or_insert_mut(3, f), Err("failed".to_owned()));
1393    /// assert_eq!(cache.try_get_or_insert_mut(4, b), Ok(&mut "b"));
1394    /// assert_eq!(cache.try_get_or_insert_mut(4, a), Ok(&mut "b"));
1395    /// ```
1396    #[inline]
1397    pub fn try_get_or_insert_mut<F, E>(&mut self, k: K, f: F) -> Result<&mut V, E>
1398    where
1399        F: FnOnce() -> Result<V, E>,
1400    {
1401        self.try_get_or_push_mut(k, f).map(|(v, _)| v)
1402    }
1403
1404    /// Like [`Self::try_get_or_insert_mut`], but also returns the entry
1405    /// evicted to make room, if any.
1406    ///
1407    /// # Example
1408    ///
1409    /// ```
1410    /// use lru::LruCache;
1411    /// use std::num::NonZeroUsize;
1412    /// let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
1413    ///
1414    /// cache.put(1, "a");
1415    /// cache.put(2, "b");
1416    /// cache.put(2, "c");
1417    /// cache.put(3, "d");
1418    ///
1419    /// let f = ||->Result<&str, String> {Err("failed".to_owned())};
1420    /// let a = ||->Result<&str, String> {Ok("a")};
1421    /// let b = ||->Result<&str, String> {Ok("b")};
1422    /// assert_eq!(cache.try_get_or_push_mut(2, a), Ok((&mut "c", None)));
1423    /// assert_eq!(cache.try_get_or_push_mut(3, a), Ok((&mut "d", None)));
1424    /// assert_eq!(cache.try_get_or_push_mut(4, f), Err("failed".to_owned()));
1425    /// assert_eq!(cache.try_get_or_push_mut(5, b), Ok((&mut "b", Some((2, "c")))));
1426    /// assert_eq!(cache.try_get_or_push_mut(5, a), Ok((&mut "b", None)));
1427    /// ```
1428    #[inline]
1429    #[allow(clippy::type_complexity)]
1430    pub fn try_get_or_push_mut<F, E>(&mut self, k: K, f: F) -> Result<(&mut V, Option<(K, V)>), E>
1431    where
1432        F: FnOnce() -> Result<V, E>,
1433    {
1434        self.try_get_or_push_mut_with_key(k, |_| f())
1435    }
1436
1437    /// Returns a mutable reference to the value of the key in the cache if it is
1438    /// present in the cache and moves the key to the head of the LRU list.
1439    /// If the key does not exist, the provided `FnOnce` is used by passing
1440    /// a reference to the key to populate the list and a mutable reference
1441    /// is returned. If `FnOnce` returns `Err`, returns the `Err`.
1442    ///
1443    /// # Example
1444    ///
1445    /// ```
1446    /// use lru::LruCache;
1447    /// use std::num::NonZeroUsize;
1448    /// let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
1449    ///
1450    /// cache.put("One", 1);
1451    /// cache.put("Two", 2);
1452    /// cache.put("Two", 3);
1453    /// cache.put("Three", 4);
1454    ///
1455    /// let f = |_: &&str|->Result<usize, String> {Err("failed".to_owned())};
1456    /// let len = |k: &&str|->Result<usize, String> {Ok(k.len())};
1457    /// let zero = |_: &&str|->Result<usize, String> {Ok(0)};
1458    /// assert_eq!(cache.try_get_or_insert_mut_with_key("Two", len), Ok(&mut 3));
1459    /// assert_eq!(cache.try_get_or_insert_mut_with_key("Three", len), Ok(&mut 4));
1460    /// assert_eq!(cache.try_get_or_insert_mut_with_key("Four", f), Err("failed".to_owned()));
1461    /// assert_eq!(cache.try_get_or_insert_mut_with_key("Five", len), Ok(&mut 4));
1462    /// assert_eq!(cache.try_get_or_insert_mut_with_key("Five", zero), Ok(&mut 4));
1463    /// ```
1464    #[inline]
1465    pub fn try_get_or_insert_mut_with_key<F, E>(&mut self, k: K, f: F) -> Result<&mut V, E>
1466    where
1467        F: FnOnce(&K) -> Result<V, E>,
1468    {
1469        self.try_get_or_push_mut_with_key(k, f).map(|(v, _)| v)
1470    }
1471
1472    /// Like [`Self::try_get_or_insert_mut_with_key`], but also returns the
1473    /// entry evicted to make room, if any.
1474    ///
1475    /// # Example
1476    ///
1477    /// ```
1478    /// use lru::LruCache;
1479    /// use std::num::NonZeroUsize;
1480    /// let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
1481    ///
1482    /// cache.put("One", 1);
1483    /// cache.put("Two", 2);
1484    /// cache.put("Two", 3);
1485    /// cache.put("Three", 4);
1486    ///
1487    /// let f = |_: &&str|->Result<usize, String> {Err("failed".to_owned())};
1488    /// let len = |k: &&str|->Result<usize, String> {Ok(k.len())};
1489    /// let zero = |_: &&str|->Result<usize, String> {Ok(0)};
1490    /// assert_eq!(cache.try_get_or_push_mut_with_key("Two", len), Ok((&mut 3, None)));
1491    /// assert_eq!(cache.try_get_or_push_mut_with_key("Three", len), Ok((&mut 4, None)));
1492    /// assert_eq!(cache.try_get_or_push_mut_with_key("Four", f), Err("failed".to_owned()));
1493    /// assert_eq!(cache.try_get_or_push_mut_with_key("Five", len), Ok((&mut 4, Some(("Two", 3)))));
1494    /// assert_eq!(cache.try_get_or_push_mut_with_key("Five", zero), Ok((&mut 4, None)));
1495    /// ```
1496    #[allow(clippy::type_complexity)]
1497    pub fn try_get_or_push_mut_with_key<F, E>(
1498        &mut self,
1499        k: K,
1500        f: F,
1501    ) -> Result<(&mut V, Option<(K, V)>), E>
1502    where
1503        F: FnOnce(&K) -> Result<V, E>,
1504    {
1505        if let Some(node) = self.map.get_mut(&KeyRef { k: &k }) {
1506            let node_ptr: *mut LruEntry<K, V> = node.as_ptr();
1507
1508            self.detach(node_ptr);
1509            self.attach(node_ptr);
1510
1511            unsafe { Ok((&mut *(*node_ptr).val.as_mut_ptr(), None)) }
1512        } else {
1513            let v = f(&k)?;
1514            let (replaced, node) = self.replace_or_create_node(k, v);
1515            let node_ptr: *mut LruEntry<K, V> = node.as_ptr();
1516
1517            self.attach(node_ptr);
1518
1519            let keyref = unsafe { (*node_ptr).key.as_ptr() };
1520            self.map.insert(KeyRef { k: keyref }, node);
1521
1522            unsafe { Ok((&mut *(*node_ptr).val.as_mut_ptr(), replaced)) }
1523        }
1524    }
1525
1526    /// Returns a mutable reference to the value of the key in the cache if it is
1527    /// present in the cache and moves the key to the head of the LRU list.
1528    /// If the key does not exist, the provided `FnOnce` is used to populate
1529    /// the list and a mutable reference is returned. If `FnOnce` returns `Err`,
1530    /// returns the `Err`. The value referenced by the key is only cloned
1531    /// (using `to_owned()`) if it doesn't exist in the cache and `FnOnce`
1532    /// succeeds.
1533    ///
1534    /// # Example
1535    ///
1536    /// ```
1537    /// use lru::LruCache;
1538    /// use std::num::NonZeroUsize;
1539    /// use std::rc::Rc;
1540    ///
1541    /// let key1 = Rc::new("1".to_owned());
1542    /// let key2 = Rc::new("2".to_owned());
1543    /// let mut cache = LruCache::<Rc<String>, String>::new(NonZeroUsize::new(2).unwrap());
1544    /// let f = ||->Result<String, ()> {Err(())};
1545    /// let a = ||->Result<String, ()> {Ok("One".to_owned())};
1546    /// let b = ||->Result<String, ()> {Ok("Two".to_owned())};
1547    /// assert_eq!(cache.try_get_or_insert_mut_ref(&key1, a), Ok(&mut "One".to_owned()));
1548    /// assert_eq!(cache.try_get_or_insert_mut_ref(&key2, f), Err(()));
1549    /// if let Ok(v) = cache.try_get_or_insert_mut_ref(&key2, b) {
1550    ///     *v = "New two".to_owned();
1551    /// }
1552    /// assert_eq!(cache.try_get_or_insert_mut_ref(&key2, a), Ok(&mut "New two".to_owned()));
1553    /// assert_eq!(Rc::strong_count(&key1), 2);
1554    /// // `key2` was only cloned once even though we queried it 3 times.
1555    /// assert_eq!(Rc::strong_count(&key2), 2);
1556    /// ```
1557    #[inline]
1558    pub fn try_get_or_insert_mut_ref<'a, Q, F, E>(
1559        &'a mut self,
1560        k: &'_ Q,
1561        f: F,
1562    ) -> Result<&'a mut V, E>
1563    where
1564        K: Borrow<Q>,
1565        Q: Hash + Eq + ?Sized + alloc::borrow::ToOwned<Owned = K>,
1566        F: FnOnce() -> Result<V, E>,
1567    {
1568        self.try_get_or_push_mut_ref(k, f).map(|(v, _)| v)
1569    }
1570
1571    /// Like [`Self::try_get_or_insert_mut_ref`], but also returns the entry
1572    /// evicted to make room, if any.
1573    ///
1574    /// # Example
1575    ///
1576    /// ```
1577    /// use lru::LruCache;
1578    /// use std::num::NonZeroUsize;
1579    /// use std::rc::Rc;
1580    ///
1581    /// let key1 = Rc::new("1".to_owned());
1582    /// let key2 = Rc::new("2".to_owned());
1583    /// let key3 = Rc::new("3".to_owned());
1584    /// let mut cache = LruCache::<Rc<String>, String>::new(NonZeroUsize::new(2).unwrap());
1585    /// let f = ||->Result<String, ()> {Err(())};
1586    /// let a = ||->Result<String, ()> {Ok("One".to_owned())};
1587    /// let b = ||->Result<String, ()> {Ok("Two".to_owned())};
1588    /// let c = ||->Result<String, ()> {Ok("Three".to_owned())};
1589    ///
1590    /// assert_eq!(
1591    ///     cache.try_get_or_push_mut_ref(&key1, a),
1592    ///     Ok((&mut "One".to_owned(), None)),
1593    /// );
1594    /// assert_eq!(
1595    ///     cache.try_get_or_push_mut_ref(&key2, f),
1596    ///     Err(()),
1597    /// );
1598    /// assert_eq!(
1599    ///     cache.try_get_or_push_mut_ref(&key2, b),
1600    ///     Ok((&mut "Two".to_owned(), None)),
1601    /// );
1602    /// assert_eq!(
1603    ///     cache.try_get_or_push_mut_ref(&key3, c),
1604    ///     Ok((
1605    ///         &mut "Three".to_owned(),
1606    ///         Some((key1.clone(), "One".to_owned())),
1607    ///     )),
1608    /// );
1609    /// assert_eq!(
1610    ///     cache.try_get_or_push_mut_ref(&key2, a),
1611    ///     Ok((&mut "Two".to_owned(), None)),
1612    /// );
1613    ///
1614    /// assert_eq!(Rc::strong_count(&key1), 1);
1615    /// // `key2` was only cloned once even though we queried it 3 times.
1616    /// assert_eq!(Rc::strong_count(&key2), 2);
1617    /// assert_eq!(Rc::strong_count(&key3), 2);
1618    /// ```
1619    #[allow(clippy::type_complexity)]
1620    pub fn try_get_or_push_mut_ref<'a, Q, F, E>(
1621        &'a mut self,
1622        k: &'_ Q,
1623        f: F,
1624    ) -> Result<(&'a mut V, Option<(K, V)>), E>
1625    where
1626        K: Borrow<Q>,
1627        Q: Hash + Eq + ?Sized + alloc::borrow::ToOwned<Owned = K>,
1628        F: FnOnce() -> Result<V, E>,
1629    {
1630        if let Some(node) = self.map.get_mut(KeyWrapper::from_ref(k)) {
1631            let node_ptr: *mut LruEntry<K, V> = node.as_ptr();
1632
1633            self.detach(node_ptr);
1634            self.attach(node_ptr);
1635
1636            unsafe { Ok((&mut *(*node_ptr).val.as_mut_ptr(), None)) }
1637        } else {
1638            let v = f()?;
1639            let (replaced, node) = self.replace_or_create_node(k.to_owned(), v);
1640            let node_ptr: *mut LruEntry<K, V> = node.as_ptr();
1641
1642            self.attach(node_ptr);
1643
1644            let keyref = unsafe { (*node_ptr).key.as_ptr() };
1645            self.map.insert(KeyRef { k: keyref }, node);
1646
1647            unsafe { Ok((&mut *(*node_ptr).val.as_mut_ptr(), replaced)) }
1648        }
1649    }
1650
1651    /// Returns a reference to the value corresponding to the key in the cache or `None` if it is
1652    /// not present in the cache. Unlike `get`, `peek` does not update the LRU list so the key's
1653    /// position will be unchanged.
1654    ///
1655    /// # Example
1656    ///
1657    /// ```
1658    /// use lru::LruCache;
1659    /// use std::num::NonZeroUsize;
1660    /// let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
1661    ///
1662    /// cache.put(1, "a");
1663    /// cache.put(2, "b");
1664    ///
1665    /// assert_eq!(cache.peek(&1), Some(&"a"));
1666    /// assert_eq!(cache.peek(&2), Some(&"b"));
1667    /// ```
1668    pub fn peek<'a, Q>(&'a self, k: &Q) -> Option<&'a V>
1669    where
1670        K: Borrow<Q>,
1671        Q: Hash + Eq + ?Sized,
1672    {
1673        self.map
1674            .get(KeyWrapper::from_ref(k))
1675            .map(|node| unsafe { &*node.as_ref().val.as_ptr() })
1676    }
1677
1678    /// Returns a mutable reference to the value corresponding to the key in the cache or `None`
1679    /// if it is not present in the cache. Unlike `get_mut`, `peek_mut` does not update the LRU
1680    /// list so the key's position will be unchanged.
1681    ///
1682    /// # Example
1683    ///
1684    /// ```
1685    /// use lru::LruCache;
1686    /// use std::num::NonZeroUsize;
1687    /// let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
1688    ///
1689    /// cache.put(1, "a");
1690    /// cache.put(2, "b");
1691    ///
1692    /// assert_eq!(cache.peek_mut(&1), Some(&mut "a"));
1693    /// assert_eq!(cache.peek_mut(&2), Some(&mut "b"));
1694    /// ```
1695    pub fn peek_mut<'a, Q>(&'a mut self, k: &Q) -> Option<&'a mut V>
1696    where
1697        K: Borrow<Q>,
1698        Q: Hash + Eq + ?Sized,
1699    {
1700        match self.map.get_mut(KeyWrapper::from_ref(k)) {
1701            None => None,
1702            Some(node) => Some(unsafe { &mut *(*node.as_ptr()).val.as_mut_ptr() }),
1703        }
1704    }
1705
1706    /// Returns the value corresponding to the least recently used item or `None` if the
1707    /// cache is empty. Like `peek`, `peek_lru` does not update the LRU list so the item's
1708    /// position will be unchanged.
1709    ///
1710    /// # Example
1711    ///
1712    /// ```
1713    /// use lru::LruCache;
1714    /// use std::num::NonZeroUsize;
1715    /// let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
1716    ///
1717    /// cache.put(1, "a");
1718    /// cache.put(2, "b");
1719    ///
1720    /// assert_eq!(cache.peek_lru(), Some((&1, &"a")));
1721    /// ```
1722    pub fn peek_lru(&self) -> Option<(&K, &V)> {
1723        if self.is_empty() {
1724            return None;
1725        }
1726
1727        let (key, val);
1728        unsafe {
1729            let node = (*self.tail).prev;
1730            key = &(*(*node).key.as_ptr()) as &K;
1731            val = &(*(*node).val.as_ptr()) as &V;
1732        }
1733
1734        Some((key, val))
1735    }
1736
1737    /// Returns the value corresponding to the most recently used item or `None` if the
1738    /// cache is empty. Like `peek`, `peek_mru` does not update the LRU list so the item's
1739    /// position will be unchanged.
1740    ///
1741    /// # Example
1742    ///
1743    /// ```
1744    /// use lru::LruCache;
1745    /// use std::num::NonZeroUsize;
1746    /// let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
1747    ///
1748    /// cache.put(1, "a");
1749    /// cache.put(2, "b");
1750    ///
1751    /// assert_eq!(cache.peek_mru(), Some((&2, &"b")));
1752    /// ```
1753    pub fn peek_mru(&self) -> Option<(&K, &V)> {
1754        if self.is_empty() {
1755            return None;
1756        }
1757
1758        let (key, val);
1759        unsafe {
1760            let node: *mut LruEntry<K, V> = (*self.head).next;
1761            key = &(*(*node).key.as_ptr()) as &K;
1762            val = &(*(*node).val.as_ptr()) as &V;
1763        }
1764
1765        Some((key, val))
1766    }
1767
1768    /// Returns a bool indicating whether the given key is in the cache. Does not update the
1769    /// LRU list.
1770    ///
1771    /// # Example
1772    ///
1773    /// ```
1774    /// use lru::LruCache;
1775    /// use std::num::NonZeroUsize;
1776    /// let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
1777    ///
1778    /// cache.put(1, "a");
1779    /// cache.put(2, "b");
1780    /// cache.put(3, "c");
1781    ///
1782    /// assert!(!cache.contains(&1));
1783    /// assert!(cache.contains(&2));
1784    /// assert!(cache.contains(&3));
1785    /// ```
1786    pub fn contains<Q>(&self, k: &Q) -> bool
1787    where
1788        K: Borrow<Q>,
1789        Q: Hash + Eq + ?Sized,
1790    {
1791        self.map.contains_key(KeyWrapper::from_ref(k))
1792    }
1793
1794    /// Removes and returns the value corresponding to the key from the cache or
1795    /// `None` if it does not exist.
1796    ///
1797    /// # Example
1798    ///
1799    /// ```
1800    /// use lru::LruCache;
1801    /// use std::num::NonZeroUsize;
1802    /// let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
1803    ///
1804    /// cache.put(2, "a");
1805    ///
1806    /// assert_eq!(cache.pop(&1), None);
1807    /// assert_eq!(cache.pop(&2), Some("a"));
1808    /// assert_eq!(cache.pop(&2), None);
1809    /// assert_eq!(cache.len(), 0);
1810    /// ```
1811    pub fn pop<Q>(&mut self, k: &Q) -> Option<V>
1812    where
1813        K: Borrow<Q>,
1814        Q: Hash + Eq + ?Sized,
1815    {
1816        match self.map.remove(KeyWrapper::from_ref(k)) {
1817            None => None,
1818            Some(old_node) => {
1819                let node_ptr: *mut LruEntry<K, V> = old_node.as_ptr();
1820
1821                // Detach the node from the linked list *before* freeing it and
1822                // dropping the key. `ptr::drop_in_place` below runs the key's
1823                // `Drop`, which may panic; if it does, unwinding must not leave
1824                // dangling `prev`/`next` pointers in the list. Detaching first
1825                // keeps the list consistent regardless of whether `Drop` panics.
1826                self.detach(node_ptr);
1827
1828                let mut old_node = unsafe { *Box::from_raw(node_ptr) };
1829                unsafe {
1830                    ptr::drop_in_place(old_node.key.as_mut_ptr());
1831                }
1832
1833                let LruEntry { key: _, val, .. } = old_node;
1834                unsafe { Some(val.assume_init()) }
1835            }
1836        }
1837    }
1838
1839    /// Removes and returns the key and the value corresponding to the key from the cache or
1840    /// `None` if it does not exist.
1841    ///
1842    /// # Example
1843    ///
1844    /// ```
1845    /// use lru::LruCache;
1846    /// use std::num::NonZeroUsize;
1847    /// let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
1848    ///
1849    /// cache.put(1, "a");
1850    /// cache.put(2, "a");
1851    ///
1852    /// assert_eq!(cache.pop(&1), Some("a"));
1853    /// assert_eq!(cache.pop_entry(&2), Some((2, "a")));
1854    /// assert_eq!(cache.pop(&1), None);
1855    /// assert_eq!(cache.pop_entry(&2), None);
1856    /// assert_eq!(cache.len(), 0);
1857    /// ```
1858    pub fn pop_entry<Q>(&mut self, k: &Q) -> Option<(K, V)>
1859    where
1860        K: Borrow<Q>,
1861        Q: Hash + Eq + ?Sized,
1862    {
1863        match self.map.remove(KeyWrapper::from_ref(k)) {
1864            None => None,
1865            Some(old_node) => {
1866                let mut old_node = unsafe { *Box::from_raw(old_node.as_ptr()) };
1867
1868                self.detach(&mut old_node);
1869
1870                let LruEntry { key, val, .. } = old_node;
1871                unsafe { Some((key.assume_init(), val.assume_init())) }
1872            }
1873        }
1874    }
1875
1876    /// Removes and returns the key and value corresponding to the least recently
1877    /// used item or `None` if the cache is empty.
1878    ///
1879    /// # Example
1880    ///
1881    /// ```
1882    /// use lru::LruCache;
1883    /// use std::num::NonZeroUsize;
1884    /// let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
1885    ///
1886    /// cache.put(2, "a");
1887    /// cache.put(3, "b");
1888    /// cache.put(4, "c");
1889    /// cache.get(&3);
1890    ///
1891    /// assert_eq!(cache.pop_lru(), Some((4, "c")));
1892    /// assert_eq!(cache.pop_lru(), Some((3, "b")));
1893    /// assert_eq!(cache.pop_lru(), None);
1894    /// assert_eq!(cache.len(), 0);
1895    /// ```
1896    pub fn pop_lru(&mut self) -> Option<(K, V)> {
1897        let node = self.remove_last()?;
1898        // N.B.: Can't destructure directly because of https://github.com/rust-lang/rust/issues/28536
1899        let node = *node;
1900        let LruEntry { key, val, .. } = node;
1901        unsafe { Some((key.assume_init(), val.assume_init())) }
1902    }
1903
1904    /// Removes and returns the key and value corresponding to the most recently
1905    /// used item or `None` if the cache is empty.
1906    ///
1907    /// # Example
1908    ///
1909    /// ```
1910    /// use lru::LruCache;
1911    /// use std::num::NonZeroUsize;
1912    /// let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
1913    ///
1914    /// cache.put(2, "a");
1915    /// cache.put(3, "b");
1916    /// cache.put(4, "c");
1917    /// cache.get(&3);
1918    ///
1919    /// assert_eq!(cache.pop_mru(), Some((3, "b")));
1920    /// assert_eq!(cache.pop_mru(), Some((4, "c")));
1921    /// assert_eq!(cache.pop_mru(), None);
1922    /// assert_eq!(cache.len(), 0);
1923    /// ```
1924    pub fn pop_mru(&mut self) -> Option<(K, V)> {
1925        let node = self.remove_first()?;
1926        // N.B.: Can't destructure directly because of https://github.com/rust-lang/rust/issues/28536
1927        let node = *node;
1928        let LruEntry { key, val, .. } = node;
1929        unsafe { Some((key.assume_init(), val.assume_init())) }
1930    }
1931
1932    /// Marks the key as the most recently used one. Returns true if the key
1933    /// was promoted because it exists in the cache, false otherwise.
1934    ///
1935    /// # Example
1936    ///
1937    /// ```
1938    /// use lru::LruCache;
1939    /// use std::num::NonZeroUsize;
1940    /// let mut cache = LruCache::new(NonZeroUsize::new(3).unwrap());
1941    ///
1942    /// cache.put(1, "a");
1943    /// cache.put(2, "b");
1944    /// cache.put(3, "c");
1945    /// cache.get(&1);
1946    /// cache.get(&2);
1947    ///
1948    /// // If we do `pop_lru` now, we would pop 3.
1949    /// // assert_eq!(cache.pop_lru(), Some((3, "c")));
1950    ///
1951    /// // By promoting 3, we make sure it isn't popped.
1952    /// assert!(cache.promote(&3));
1953    /// assert_eq!(cache.pop_lru(), Some((1, "a")));
1954    ///
1955    /// // Promoting an entry that doesn't exist doesn't do anything.
1956    /// assert!(!cache.promote(&4));
1957    /// ```
1958    pub fn promote<Q>(&mut self, k: &Q) -> bool
1959    where
1960        K: Borrow<Q>,
1961        Q: Hash + Eq + ?Sized,
1962    {
1963        if let Some(node) = self.map.get_mut(KeyWrapper::from_ref(k)) {
1964            let node_ptr: *mut LruEntry<K, V> = node.as_ptr();
1965            self.detach(node_ptr);
1966            self.attach(node_ptr);
1967            true
1968        } else {
1969            false
1970        }
1971    }
1972
1973    /// Marks the key as the least recently used one. Returns true if the key was demoted
1974    /// because it exists in the cache, false otherwise.
1975    ///
1976    /// # Example
1977    ///
1978    /// ```
1979    /// use lru::LruCache;
1980    /// use std::num::NonZeroUsize;
1981    /// let mut cache = LruCache::new(NonZeroUsize::new(3).unwrap());
1982    ///
1983    /// cache.put(1, "a");
1984    /// cache.put(2, "b");
1985    /// cache.put(3, "c");
1986    /// cache.get(&1);
1987    /// cache.get(&2);
1988    ///
1989    /// // If we do `pop_lru` now, we would pop 3.
1990    /// // assert_eq!(cache.pop_lru(), Some((3, "c")));
1991    ///
1992    /// // By demoting 1 and 2, we make sure those are popped first.
1993    /// assert!(cache.demote(&2));
1994    /// assert!(cache.demote(&1));
1995    /// assert_eq!(cache.pop_lru(), Some((1, "a")));
1996    /// assert_eq!(cache.pop_lru(), Some((2, "b")));
1997    ///
1998    /// // Demoting a key that doesn't exist does nothing.
1999    /// assert!(!cache.demote(&4));
2000    /// ```
2001    pub fn demote<Q>(&mut self, k: &Q) -> bool
2002    where
2003        K: Borrow<Q>,
2004        Q: Hash + Eq + ?Sized,
2005    {
2006        if let Some(node) = self.map.get_mut(KeyWrapper::from_ref(k)) {
2007            let node_ptr: *mut LruEntry<K, V> = node.as_ptr();
2008            self.detach(node_ptr);
2009            self.attach_last(node_ptr);
2010            true
2011        } else {
2012            false
2013        }
2014    }
2015
2016    /// Finds the first entry (in most-recently-used to least-recently-used iteration order)
2017    /// that matches the provided predicate and promotes it to the most recently used position.
2018    ///
2019    /// # Example
2020    ///
2021    /// ```
2022    /// use lru::LruCache;
2023    /// use std::num::NonZeroUsize;
2024    ///
2025    /// let mut cache = LruCache::new(NonZeroUsize::new(3).unwrap());
2026    /// cache.put(1, "a");
2027    /// cache.put(2, "b");
2028    /// cache.put(3, "c");
2029    ///
2030    /// let found = cache.find_and_promote(|(_, value)| *value == "b");
2031    /// assert_eq!(found, Some((&2, &"b")));
2032    /// assert_eq!(cache.pop_lru(), Some((1, "a")));
2033    /// assert_eq!(cache.pop_lru(), Some((3, "c")));
2034    /// assert_eq!(cache.pop_lru(), Some((2, "b")));
2035    /// ```
2036    pub fn find_and_promote<F>(&mut self, mut predicate: F) -> Option<(&K, &V)>
2037    where
2038        F: FnMut((&K, &V)) -> bool,
2039    {
2040        let mut node = unsafe { (*self.head).next };
2041
2042        while !core::ptr::eq(node, self.tail) {
2043            let matches = {
2044                let key = unsafe { &*(*node).key.as_ptr() };
2045                let val = unsafe { &*(*node).val.as_ptr() };
2046                predicate((key, val))
2047            };
2048
2049            if matches {
2050                self.detach(node);
2051                self.attach(node);
2052                return Some(unsafe { (&*(*node).key.as_ptr(), &*(*node).val.as_ptr()) });
2053            }
2054
2055            unsafe { node = (*node).next };
2056        }
2057
2058        None
2059    }
2060
2061    /// Retains only the entries for which the predicate `f` returns `true`, removing the rest.
2062    ///
2063    /// The entries are visited in most-recently-used to least-recently-used order and the
2064    /// relative order of the entries that are kept is preserved.
2065    ///
2066    /// # Example
2067    ///
2068    /// ```
2069    /// use lru::LruCache;
2070    /// use std::num::NonZeroUsize;
2071    ///
2072    /// let mut cache = LruCache::new(NonZeroUsize::new(4).unwrap());
2073    /// cache.put(1, "a");
2074    /// cache.put(2, "b");
2075    /// cache.put(3, "c");
2076    /// cache.put(4, "d");
2077    ///
2078    /// cache.retain(|k, _| k % 2 == 0);
2079    ///
2080    /// assert_eq!(cache.len(), 2);
2081    /// assert_eq!(cache.get(&2), Some(&"b"));
2082    /// assert_eq!(cache.get(&4), Some(&"d"));
2083    /// assert_eq!(cache.get(&1), None);
2084    /// assert_eq!(cache.get(&3), None);
2085    /// ```
2086    pub fn retain<F>(&mut self, mut f: F)
2087    where
2088        F: FnMut(&K, &mut V) -> bool,
2089    {
2090        let mut node = unsafe { (*self.head).next };
2091
2092        while !core::ptr::eq(node, self.tail) {
2093            // Grab the next node before we potentially free the current one.
2094            let next = unsafe { (*node).next };
2095
2096            let keep = {
2097                let key = unsafe { &*(*node).key.as_ptr() };
2098                let val = unsafe { &mut *(*node).val.as_mut_ptr() };
2099                f(key, val)
2100            };
2101
2102            if !keep {
2103                let key_ref = KeyRef {
2104                    k: unsafe { &*(*node).key.as_ptr() },
2105                };
2106                self.map.remove(&key_ref);
2107
2108                // Detach before dropping the key and value so that a panic in either
2109                // `Drop` cannot leave dangling pointers in the list.
2110                self.detach(node);
2111
2112                let mut old_node = unsafe { *Box::from_raw(node) };
2113                unsafe {
2114                    ptr::drop_in_place(old_node.key.as_mut_ptr());
2115                    ptr::drop_in_place(old_node.val.as_mut_ptr());
2116                }
2117            }
2118
2119            node = next;
2120        }
2121    }
2122
2123    /// Returns the number of key-value pairs that are currently in the the cache.
2124    ///
2125    /// # Example
2126    ///
2127    /// ```
2128    /// use lru::LruCache;
2129    /// use std::num::NonZeroUsize;
2130    /// let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
2131    /// assert_eq!(cache.len(), 0);
2132    ///
2133    /// cache.put(1, "a");
2134    /// assert_eq!(cache.len(), 1);
2135    ///
2136    /// cache.put(2, "b");
2137    /// assert_eq!(cache.len(), 2);
2138    ///
2139    /// cache.put(3, "c");
2140    /// assert_eq!(cache.len(), 2);
2141    /// ```
2142    pub fn len(&self) -> usize {
2143        self.map.len()
2144    }
2145
2146    /// Returns a bool indicating whether the cache is empty or not.
2147    ///
2148    /// # Example
2149    ///
2150    /// ```
2151    /// use lru::LruCache;
2152    /// use std::num::NonZeroUsize;
2153    /// let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
2154    /// assert!(cache.is_empty());
2155    ///
2156    /// cache.put(1, "a");
2157    /// assert!(!cache.is_empty());
2158    /// ```
2159    pub fn is_empty(&self) -> bool {
2160        self.map.len() == 0
2161    }
2162
2163    /// Returns the maximum number of key-value pairs the cache can hold.
2164    ///
2165    /// # Example
2166    ///
2167    /// ```
2168    /// use lru::LruCache;
2169    /// use std::num::NonZeroUsize;
2170    /// let mut cache: LruCache<isize, &str> = LruCache::new(NonZeroUsize::new(2).unwrap());
2171    /// assert_eq!(cache.cap().get(), 2);
2172    /// ```
2173    pub fn cap(&self) -> NonZeroUsize {
2174        self.cap
2175    }
2176
2177    /// Resizes the cache. If the new capacity is smaller than the size of the current
2178    /// cache any entries past the new capacity are discarded.
2179    ///
2180    /// # Example
2181    ///
2182    /// ```
2183    /// use lru::LruCache;
2184    /// use std::num::NonZeroUsize;
2185    /// let mut cache: LruCache<isize, &str> = LruCache::new(NonZeroUsize::new(2).unwrap());
2186    ///
2187    /// cache.put(1, "a");
2188    /// cache.put(2, "b");
2189    /// cache.resize(NonZeroUsize::new(4).unwrap());
2190    /// cache.put(3, "c");
2191    /// cache.put(4, "d");
2192    ///
2193    /// assert_eq!(cache.len(), 4);
2194    /// assert_eq!(cache.get(&1), Some(&"a"));
2195    /// assert_eq!(cache.get(&2), Some(&"b"));
2196    /// assert_eq!(cache.get(&3), Some(&"c"));
2197    /// assert_eq!(cache.get(&4), Some(&"d"));
2198    /// ```
2199    pub fn resize(&mut self, cap: NonZeroUsize) {
2200        // return early if capacity doesn't change
2201        if cap == self.cap {
2202            return;
2203        }
2204
2205        while self.map.len() > cap.get() {
2206            self.pop_lru();
2207        }
2208        self.map.shrink_to_fit();
2209
2210        self.cap = cap;
2211    }
2212
2213    /// Clears the contents of the cache.
2214    ///
2215    /// # Example
2216    ///
2217    /// ```
2218    /// use lru::LruCache;
2219    /// use std::num::NonZeroUsize;
2220    /// let mut cache: LruCache<isize, &str> = LruCache::new(NonZeroUsize::new(2).unwrap());
2221    /// assert_eq!(cache.len(), 0);
2222    ///
2223    /// cache.put(1, "a");
2224    /// assert_eq!(cache.len(), 1);
2225    ///
2226    /// cache.put(2, "b");
2227    /// assert_eq!(cache.len(), 2);
2228    ///
2229    /// cache.clear();
2230    /// assert_eq!(cache.len(), 0);
2231    /// ```
2232    pub fn clear(&mut self) {
2233        while self.pop_lru().is_some() {}
2234    }
2235
2236    /// An iterator visiting all entries in most-recently used order. The iterator element type is
2237    /// `(&K, &V)`.
2238    ///
2239    /// # Examples
2240    ///
2241    /// ```
2242    /// use lru::LruCache;
2243    /// use std::num::NonZeroUsize;
2244    ///
2245    /// let mut cache = LruCache::new(NonZeroUsize::new(3).unwrap());
2246    /// cache.put("a", 1);
2247    /// cache.put("b", 2);
2248    /// cache.put("c", 3);
2249    ///
2250    /// for (key, val) in cache.iter() {
2251    ///     println!("key: {} val: {}", key, val);
2252    /// }
2253    /// ```
2254    pub fn iter(&self) -> Iter<'_, K, V> {
2255        Iter {
2256            len: self.len(),
2257            ptr: unsafe { (*self.head).next },
2258            end: unsafe { (*self.tail).prev },
2259            phantom: PhantomData,
2260        }
2261    }
2262
2263    /// An iterator visiting all entries in most-recently-used order, giving a mutable reference on
2264    /// V.  The iterator element type is `(&K, &mut V)`.
2265    ///
2266    /// # Examples
2267    ///
2268    /// ```
2269    /// use lru::LruCache;
2270    /// use std::num::NonZeroUsize;
2271    ///
2272    /// struct HddBlock {
2273    ///     dirty: bool,
2274    ///     data: [u8; 512]
2275    /// }
2276    ///
2277    /// let mut cache = LruCache::new(NonZeroUsize::new(3).unwrap());
2278    /// cache.put(0, HddBlock { dirty: false, data: [0x00; 512]});
2279    /// cache.put(1, HddBlock { dirty: true,  data: [0x55; 512]});
2280    /// cache.put(2, HddBlock { dirty: true,  data: [0x77; 512]});
2281    ///
2282    /// // write dirty blocks to disk.
2283    /// for (block_id, block) in cache.iter_mut() {
2284    ///     if block.dirty {
2285    ///         // write block to disk
2286    ///         block.dirty = false
2287    ///     }
2288    /// }
2289    /// ```
2290    pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
2291        IterMut {
2292            len: self.len(),
2293            ptr: unsafe { (*self.head).next },
2294            end: unsafe { (*self.tail).prev },
2295            phantom: PhantomData,
2296        }
2297    }
2298
2299    fn remove_first(&mut self) -> Option<Box<LruEntry<K, V>>> {
2300        let next;
2301        unsafe { next = (*self.head).next }
2302        if !core::ptr::eq(next, self.tail) {
2303            let old_key = KeyRef {
2304                k: unsafe { &(*(*(*self.head).next).key.as_ptr()) },
2305            };
2306            let old_node = self.map.remove(&old_key).unwrap();
2307            let node_ptr: *mut LruEntry<K, V> = old_node.as_ptr();
2308            self.detach(node_ptr);
2309            unsafe { Some(Box::from_raw(node_ptr)) }
2310        } else {
2311            None
2312        }
2313    }
2314
2315    fn remove_last(&mut self) -> Option<Box<LruEntry<K, V>>> {
2316        let prev;
2317        unsafe { prev = (*self.tail).prev }
2318        if !core::ptr::eq(prev, self.head) {
2319            let old_key = KeyRef {
2320                k: unsafe { &(*(*(*self.tail).prev).key.as_ptr()) },
2321            };
2322            let old_node = self.map.remove(&old_key).unwrap();
2323            let node_ptr: *mut LruEntry<K, V> = old_node.as_ptr();
2324            self.detach(node_ptr);
2325            unsafe { Some(Box::from_raw(node_ptr)) }
2326        } else {
2327            None
2328        }
2329    }
2330
2331    fn detach(&mut self, node: *mut LruEntry<K, V>) {
2332        unsafe {
2333            (*(*node).prev).next = (*node).next;
2334            (*(*node).next).prev = (*node).prev;
2335        }
2336    }
2337
2338    // Attaches `node` after the sigil `self.head` node.
2339    fn attach(&mut self, node: *mut LruEntry<K, V>) {
2340        unsafe {
2341            (*node).next = (*self.head).next;
2342            (*node).prev = self.head;
2343            (*self.head).next = node;
2344            (*(*node).next).prev = node;
2345        }
2346    }
2347
2348    // Attaches `node` before the sigil `self.tail` node.
2349    fn attach_last(&mut self, node: *mut LruEntry<K, V>) {
2350        unsafe {
2351            (*node).next = self.tail;
2352            (*node).prev = (*self.tail).prev;
2353            (*self.tail).prev = node;
2354            (*(*node).prev).next = node;
2355        }
2356    }
2357}
2358
2359impl<K, V, S> Drop for LruCache<K, V, S> {
2360    fn drop(&mut self) {
2361        self.map.drain().for_each(|(_, node)| unsafe {
2362            let mut node = *Box::from_raw(node.as_ptr());
2363            ptr::drop_in_place((node).key.as_mut_ptr());
2364            ptr::drop_in_place((node).val.as_mut_ptr());
2365        });
2366        // We rebox the head/tail, and because these are maybe-uninit
2367        // they do not have the absent k/v dropped.
2368
2369        let _head = unsafe { *Box::from_raw(self.head) };
2370        let _tail = unsafe { *Box::from_raw(self.tail) };
2371    }
2372}
2373
2374impl<'a, K: Hash + Eq, V, S: BuildHasher> IntoIterator for &'a LruCache<K, V, S> {
2375    type Item = (&'a K, &'a V);
2376    type IntoIter = Iter<'a, K, V>;
2377
2378    fn into_iter(self) -> Iter<'a, K, V> {
2379        self.iter()
2380    }
2381}
2382
2383impl<'a, K: Hash + Eq, V, S: BuildHasher> IntoIterator for &'a mut LruCache<K, V, S> {
2384    type Item = (&'a K, &'a mut V);
2385    type IntoIter = IterMut<'a, K, V>;
2386
2387    fn into_iter(self) -> IterMut<'a, K, V> {
2388        self.iter_mut()
2389    }
2390}
2391
2392// The compiler does not automatically derive Send and Sync for LruCache because it contains
2393// raw pointers. The raw pointers are safely encapsulated by LruCache though so we can
2394// implement Send and Sync for it below.
2395unsafe impl<K: Send, V: Send, S: Send> Send for LruCache<K, V, S> {}
2396unsafe impl<K: Sync, V: Sync, S: Sync> Sync for LruCache<K, V, S> {}
2397
2398impl<K: Hash + Eq, V, S: BuildHasher> fmt::Debug for LruCache<K, V, S> {
2399    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2400        f.debug_struct("LruCache")
2401            .field("len", &self.len())
2402            .field("cap", &self.cap())
2403            .finish()
2404    }
2405}
2406
2407/// An iterator over the entries of an [`LruCache`].
2408///
2409/// This `struct` is created by the [`LruCache::iter`] method. See its
2410/// documentation for more.
2411///
2412/// An iterator can be sent to another thread only if its keys and values are
2413/// `Sync`, since it yields shared references to them.
2414///
2415/// ```compile_fail
2416/// use std::cell::Cell;
2417///
2418/// fn assert_send<T: Send>() {}
2419/// assert_send::<lru::Iter<'_, Cell<u8>, u8>>();
2420/// ```
2421///
2422/// ```compile_fail
2423/// use std::cell::Cell;
2424///
2425/// fn assert_send<T: Send>() {}
2426/// assert_send::<lru::Iter<'_, u8, Cell<u8>>>();
2427/// ```
2428pub struct Iter<'a, K: 'a, V: 'a> {
2429    len: usize,
2430
2431    ptr: *const LruEntry<K, V>,
2432    end: *const LruEntry<K, V>,
2433
2434    phantom: PhantomData<&'a K>,
2435}
2436
2437impl<'a, K, V> Iterator for Iter<'a, K, V> {
2438    type Item = (&'a K, &'a V);
2439
2440    fn next(&mut self) -> Option<(&'a K, &'a V)> {
2441        if self.len == 0 {
2442            return None;
2443        }
2444
2445        let key = unsafe { &(*(*self.ptr).key.as_ptr()) as &K };
2446        let val = unsafe { &(*(*self.ptr).val.as_ptr()) as &V };
2447
2448        self.len -= 1;
2449        self.ptr = unsafe { (*self.ptr).next };
2450
2451        Some((key, val))
2452    }
2453
2454    fn size_hint(&self) -> (usize, Option<usize>) {
2455        (self.len, Some(self.len))
2456    }
2457
2458    fn count(self) -> usize {
2459        self.len
2460    }
2461}
2462
2463impl<'a, K, V> DoubleEndedIterator for Iter<'a, K, V> {
2464    fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
2465        if self.len == 0 {
2466            return None;
2467        }
2468
2469        let key = unsafe { &(*(*self.end).key.as_ptr()) as &K };
2470        let val = unsafe { &(*(*self.end).val.as_ptr()) as &V };
2471
2472        self.len -= 1;
2473        self.end = unsafe { (*self.end).prev };
2474
2475        Some((key, val))
2476    }
2477}
2478
2479impl<'a, K, V> ExactSizeIterator for Iter<'a, K, V> {}
2480impl<'a, K, V> FusedIterator for Iter<'a, K, V> {}
2481
2482impl<'a, K, V> Clone for Iter<'a, K, V> {
2483    fn clone(&self) -> Iter<'a, K, V> {
2484        Iter {
2485            len: self.len,
2486            ptr: self.ptr,
2487            end: self.end,
2488            phantom: PhantomData,
2489        }
2490    }
2491}
2492
2493// The compiler does not automatically derive Send and Sync for Iter because it contains
2494// raw pointers.
2495unsafe impl<'a, K: Sync, V: Sync> Send for Iter<'a, K, V> {}
2496unsafe impl<'a, K: Sync, V: Sync> Sync for Iter<'a, K, V> {}
2497
2498/// An iterator over mutables entries of an [`LruCache`].
2499///
2500/// This `struct` is created by the [`LruCache::iter_mut`] method. See its
2501/// documentation for more.
2502pub struct IterMut<'a, K: 'a, V: 'a> {
2503    len: usize,
2504
2505    ptr: *mut LruEntry<K, V>,
2506    end: *mut LruEntry<K, V>,
2507
2508    phantom: PhantomData<&'a K>,
2509}
2510
2511impl<'a, K, V> Iterator for IterMut<'a, K, V> {
2512    type Item = (&'a K, &'a mut V);
2513
2514    fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
2515        if self.len == 0 {
2516            return None;
2517        }
2518
2519        let key = unsafe { &(*(*self.ptr).key.as_ptr()) as &K };
2520        let val = unsafe { &mut (*(*self.ptr).val.as_mut_ptr()) as &mut V };
2521
2522        self.len -= 1;
2523        self.ptr = unsafe { (*self.ptr).next };
2524
2525        Some((key, val))
2526    }
2527
2528    fn size_hint(&self) -> (usize, Option<usize>) {
2529        (self.len, Some(self.len))
2530    }
2531
2532    fn count(self) -> usize {
2533        self.len
2534    }
2535}
2536
2537impl<'a, K, V> DoubleEndedIterator for IterMut<'a, K, V> {
2538    fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
2539        if self.len == 0 {
2540            return None;
2541        }
2542
2543        let key = unsafe { &(*(*self.end).key.as_ptr()) as &K };
2544        let val = unsafe { &mut (*(*self.end).val.as_mut_ptr()) as &mut V };
2545
2546        self.len -= 1;
2547        self.end = unsafe { (*self.end).prev };
2548
2549        Some((key, val))
2550    }
2551}
2552
2553impl<'a, K, V> ExactSizeIterator for IterMut<'a, K, V> {}
2554impl<'a, K, V> FusedIterator for IterMut<'a, K, V> {}
2555
2556// The compiler does not automatically derive Send and Sync for Iter because it contains
2557// raw pointers.
2558unsafe impl<'a, K: Send, V: Send> Send for IterMut<'a, K, V> {}
2559unsafe impl<'a, K: Sync, V: Sync> Sync for IterMut<'a, K, V> {}
2560
2561/// An iterator that moves out of an [`LruCache`].
2562///
2563/// This `struct` is created by the [`LruCache::into_iter`] method. See its
2564/// documentation for more.
2565pub struct IntoIter<K, V>
2566where
2567    K: Hash + Eq,
2568{
2569    cache: LruCache<K, V>,
2570}
2571
2572impl<K, V> Iterator for IntoIter<K, V>
2573where
2574    K: Hash + Eq,
2575{
2576    type Item = (K, V);
2577
2578    fn next(&mut self) -> Option<(K, V)> {
2579        self.cache.pop_lru()
2580    }
2581
2582    fn size_hint(&self) -> (usize, Option<usize>) {
2583        let len = self.cache.len();
2584        (len, Some(len))
2585    }
2586
2587    fn count(self) -> usize {
2588        self.cache.len()
2589    }
2590}
2591
2592impl<K, V> ExactSizeIterator for IntoIter<K, V> where K: Hash + Eq {}
2593impl<K, V> FusedIterator for IntoIter<K, V> where K: Hash + Eq {}
2594
2595impl<K: Hash + Eq, V> IntoIterator for LruCache<K, V> {
2596    type Item = (K, V);
2597    type IntoIter = IntoIter<K, V>;
2598
2599    fn into_iter(self) -> IntoIter<K, V> {
2600        IntoIter { cache: self }
2601    }
2602}
2603
2604/// Doctests for what should *not* compile
2605///
2606/// ```compile_fail
2607/// let mut cache = lru::LruCache::<u32, u32>::unbounded();
2608/// let _: &'static u32 = cache.get_or_insert(0, || 92);
2609/// ```
2610///
2611/// ```compile_fail
2612/// let mut cache = lru::LruCache::<u32, u32>::unbounded();
2613/// let _: Option<(&'static u32, _)> = cache.peek_lru();
2614/// let _: Option<(_, &'static u32)> = cache.peek_lru();
2615/// ```
2616fn _test_lifetimes() {}
2617
2618#[cfg(test)]
2619mod tests {
2620    use super::LruCache;
2621    use core::{fmt::Debug, num::NonZeroUsize};
2622    use scoped_threadpool::Pool;
2623    use std::rc::Rc;
2624    use std::sync::atomic::{AtomicUsize, Ordering};
2625
2626    fn assert_opt_eq<V: PartialEq + Debug>(opt: Option<&V>, v: V) {
2627        assert!(opt.is_some());
2628        assert_eq!(opt.unwrap(), &v);
2629    }
2630
2631    fn assert_opt_eq_mut<V: PartialEq + Debug>(opt: Option<&mut V>, v: V) {
2632        assert!(opt.is_some());
2633        assert_eq!(opt.unwrap(), &v);
2634    }
2635
2636    fn assert_opt_eq_tuple<K: PartialEq + Debug, V: PartialEq + Debug>(
2637        opt: Option<(&K, &V)>,
2638        kv: (K, V),
2639    ) {
2640        assert!(opt.is_some());
2641        let res = opt.unwrap();
2642        assert_eq!(res.0, &kv.0);
2643        assert_eq!(res.1, &kv.1);
2644    }
2645
2646    fn assert_opt_eq_mut_tuple<K: PartialEq + Debug, V: PartialEq + Debug>(
2647        opt: Option<(&K, &mut V)>,
2648        kv: (K, V),
2649    ) {
2650        assert!(opt.is_some());
2651        let res = opt.unwrap();
2652        assert_eq!(res.0, &kv.0);
2653        assert_eq!(res.1, &kv.1);
2654    }
2655
2656    #[test]
2657    fn test_unbounded() {
2658        let mut cache = LruCache::unbounded();
2659        for i in 0..13370 {
2660            cache.put(i, ());
2661        }
2662        assert_eq!(cache.len(), 13370);
2663    }
2664
2665    #[test]
2666    #[cfg(feature = "hashbrown")]
2667    fn test_with_hasher() {
2668        use core::num::NonZeroUsize;
2669
2670        use hashbrown::DefaultHashBuilder;
2671
2672        let s = DefaultHashBuilder::default();
2673        let mut cache = LruCache::with_hasher(NonZeroUsize::new(16).unwrap(), s);
2674
2675        for i in 0..13370 {
2676            cache.put(i, ());
2677        }
2678        assert_eq!(cache.len(), 16);
2679    }
2680
2681    #[test]
2682    fn test_put_and_get() {
2683        let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
2684        assert!(cache.is_empty());
2685
2686        assert_eq!(cache.put("apple", "red"), None);
2687        assert_eq!(cache.put("banana", "yellow"), None);
2688
2689        assert_eq!(cache.cap().get(), 2);
2690        assert_eq!(cache.len(), 2);
2691        assert!(!cache.is_empty());
2692        assert_opt_eq(cache.get(&"apple"), "red");
2693        assert_opt_eq(cache.get(&"banana"), "yellow");
2694    }
2695
2696    #[test]
2697    fn test_put_and_get_or_insert() {
2698        let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
2699        assert!(cache.is_empty());
2700
2701        assert_eq!(cache.put("apple", "red"), None);
2702        assert_eq!(cache.put("banana", "yellow"), None);
2703
2704        assert_eq!(cache.cap().get(), 2);
2705        assert_eq!(cache.len(), 2);
2706        assert!(!cache.is_empty());
2707        assert_eq!(cache.get_or_insert("apple", || "orange"), &"red");
2708        assert_eq!(cache.get_or_insert("banana", || "orange"), &"yellow");
2709        assert_eq!(cache.get_or_insert("lemon", || "orange"), &"orange");
2710        assert_eq!(cache.get_or_insert("lemon", || "red"), &"orange");
2711    }
2712
2713    #[test]
2714    fn test_put_and_get_or_push() {
2715        let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
2716        assert!(cache.is_empty());
2717
2718        assert_eq!(cache.put("apple", "red"), None);
2719        assert_eq!(cache.put("banana", "yellow"), None);
2720
2721        assert_eq!(cache.cap().get(), 2);
2722        assert_eq!(cache.len(), 2);
2723        assert!(!cache.is_empty());
2724        assert_eq!(cache.get_or_push("apple", || "orange"), (&"red", None));
2725        assert_eq!(cache.get_or_push("banana", || "orange"), (&"yellow", None));
2726        assert_eq!(
2727            cache.get_or_push("lemon", || "orange"),
2728            (&"orange", Some(("apple", "red")))
2729        );
2730        assert_eq!(cache.get_or_push("lemon", || "red"), (&"orange", None));
2731    }
2732
2733    #[test]
2734    fn test_put_and_get_or_insert_with_key() {
2735        let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
2736        assert!(cache.is_empty());
2737
2738        assert_eq!(cache.put("apple", 2), None);
2739        assert_eq!(cache.put("banana", 8), None);
2740
2741        assert_eq!(cache.cap().get(), 2);
2742        assert_eq!(cache.len(), 2);
2743        assert!(!cache.is_empty());
2744        assert_eq!(cache.get_or_insert_with_key("apple", |k| k.len()), &2);
2745        assert_eq!(cache.get_or_insert_with_key("banana", |k| k.len()), &8);
2746        assert_eq!(cache.get_or_insert_with_key("lemon", |k| k.len()), &5);
2747        assert_eq!(cache.get_or_insert_with_key("lemon", |k| k.len() + 3), &5);
2748    }
2749
2750    #[test]
2751    fn test_put_and_get_or_push_with_key() {
2752        let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
2753        assert!(cache.is_empty());
2754
2755        assert_eq!(cache.put("apple", 2), None);
2756        assert_eq!(cache.put("banana", 8), None);
2757
2758        assert_eq!(cache.cap().get(), 2);
2759        assert_eq!(cache.len(), 2);
2760        assert!(!cache.is_empty());
2761        assert_eq!(cache.get_or_push_with_key("apple", |k| k.len()), (&2, None));
2762        assert_eq!(
2763            cache.get_or_push_with_key("banana", |k| k.len()),
2764            (&8, None)
2765        );
2766        assert_eq!(
2767            cache.get_or_push_with_key("lemon", |k| k.len()),
2768            (&5, Some(("apple", 2)))
2769        );
2770        assert_eq!(
2771            cache.get_or_push_with_key("lemon", |k| k.len() + 3),
2772            (&5, None)
2773        );
2774    }
2775
2776    #[test]
2777    fn test_get_or_insert_ref() {
2778        use alloc::borrow::ToOwned;
2779        use alloc::string::String;
2780
2781        let key1 = Rc::new("1".to_owned());
2782        let key2 = Rc::new("2".to_owned());
2783        let mut cache = LruCache::<Rc<String>, String>::new(NonZeroUsize::new(2).unwrap());
2784        assert!(cache.is_empty());
2785        assert_eq!(cache.get_or_insert_ref(&key1, || "One".to_owned()), "One");
2786        assert_eq!(cache.get_or_insert_ref(&key2, || "Two".to_owned()), "Two");
2787        assert_eq!(cache.len(), 2);
2788        assert!(!cache.is_empty());
2789        assert_eq!(
2790            cache.get_or_insert_ref(&key2, || "Not two".to_owned()),
2791            "Two"
2792        );
2793        assert_eq!(
2794            cache.get_or_insert_ref(&key2, || "Again not two".to_owned()),
2795            "Two"
2796        );
2797        assert_eq!(Rc::strong_count(&key1), 2);
2798        assert_eq!(Rc::strong_count(&key2), 2);
2799    }
2800
2801    #[test]
2802    fn test_get_or_push_ref() {
2803        use alloc::borrow::ToOwned;
2804        use alloc::string::String;
2805
2806        let key1 = Rc::new("1".to_owned());
2807        let key2 = Rc::new("2".to_owned());
2808        let key3 = Rc::new("3".to_owned());
2809        let mut cache = LruCache::<Rc<String>, String>::new(NonZeroUsize::new(2).unwrap());
2810        assert!(cache.is_empty());
2811        assert_eq!(
2812            cache.get_or_push_ref(&key1, || "One".to_owned()),
2813            (&"One".to_owned(), None)
2814        );
2815        assert_eq!(
2816            cache.get_or_push_ref(&key2, || "Two".to_owned()),
2817            (&"Two".to_owned(), None)
2818        );
2819        assert_eq!(
2820            cache.get_or_push_ref(&key3, || "Three".to_owned()),
2821            (&"Three".to_owned(), Some((key1.clone(), "One".to_owned())))
2822        );
2823        assert_eq!(cache.len(), 2);
2824        assert!(!cache.is_empty());
2825        assert_eq!(
2826            cache.get_or_push_ref(&key2, || "Not two".to_owned()),
2827            (&"Two".to_owned(), None),
2828        );
2829        assert_eq!(
2830            cache.get_or_push_ref(&key1, || "One again".to_owned()),
2831            (
2832                &"One again".to_owned(),
2833                Some((key3.clone(), "Three".to_owned()))
2834            ),
2835        );
2836        assert_eq!(
2837            cache.get_or_push_ref(&key2, || "Again not two".to_owned()),
2838            (&"Two".to_owned(), None),
2839        );
2840        assert_eq!(Rc::strong_count(&key1), 2);
2841        assert_eq!(Rc::strong_count(&key2), 2);
2842        assert_eq!(Rc::strong_count(&key3), 1);
2843    }
2844
2845    #[test]
2846    fn test_try_get_or_insert() {
2847        let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
2848
2849        assert_eq!(
2850            cache.try_get_or_insert::<_, &str>("apple", || Ok("red")),
2851            Ok(&"red")
2852        );
2853        assert_eq!(
2854            cache.try_get_or_insert::<_, &str>("apple", || Err("failed")),
2855            Ok(&"red")
2856        );
2857        assert_eq!(
2858            cache.try_get_or_insert::<_, &str>("banana", || Ok("orange")),
2859            Ok(&"orange")
2860        );
2861        assert_eq!(
2862            cache.try_get_or_insert::<_, &str>("lemon", || Err("failed")),
2863            Err("failed")
2864        );
2865        assert_eq!(
2866            cache.try_get_or_insert::<_, &str>("banana", || Err("failed")),
2867            Ok(&"orange")
2868        );
2869    }
2870
2871    #[test]
2872    fn test_try_get_or_push() {
2873        let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
2874
2875        assert_eq!(
2876            cache.try_get_or_push::<_, &str>("apple", || Ok("red")),
2877            Ok((&"red", None))
2878        );
2879        assert_eq!(
2880            cache.try_get_or_push::<_, &str>("apple", || Err("failed")),
2881            Ok((&"red", None))
2882        );
2883        assert_eq!(
2884            cache.try_get_or_push::<_, &str>("banana", || Ok("orange")),
2885            Ok((&"orange", None))
2886        );
2887        assert_eq!(
2888            cache.try_get_or_push::<_, &str>("lemon", || Err("failed")),
2889            Err("failed")
2890        );
2891        assert_eq!(
2892            cache.try_get_or_push::<_, &str>("lemon", || Ok("lemon")),
2893            Ok((&"lemon", Some(("apple", "red"))))
2894        );
2895        assert_eq!(
2896            cache.try_get_or_push::<_, &str>("banana", || Err("failed")),
2897            Ok((&"orange", None))
2898        );
2899    }
2900
2901    #[test]
2902    fn test_try_get_or_insert_with_key() {
2903        let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
2904
2905        assert_eq!(
2906            cache.try_get_or_insert_with_key::<_, &str>("apple", |k| Ok(k.len())),
2907            Ok(&5)
2908        );
2909        assert_eq!(
2910            cache.try_get_or_insert_with_key::<_, &str>("apple", |_| Err("failed")),
2911            Ok(&5)
2912        );
2913        assert_eq!(
2914            cache.try_get_or_insert_with_key::<_, &str>("banana", |k| Ok(k.len())),
2915            Ok(&6)
2916        );
2917        assert_eq!(
2918            cache.try_get_or_insert_with_key::<_, &str>("lemon", |_| Err("failed")),
2919            Err("failed")
2920        );
2921        assert_eq!(
2922            cache.try_get_or_insert_with_key::<_, &str>("banana", |_| Err("failed")),
2923            Ok(&6)
2924        );
2925    }
2926
2927    #[test]
2928    fn test_try_get_or_push_with_key() {
2929        let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
2930
2931        assert_eq!(
2932            cache.try_get_or_push_with_key::<_, &str>("apple", |k| Ok(k.len())),
2933            Ok((&5, None))
2934        );
2935        assert_eq!(
2936            cache.try_get_or_push_with_key::<_, &str>("apple", |_| Err("failed")),
2937            Ok((&5, None))
2938        );
2939        assert_eq!(
2940            cache.try_get_or_push_with_key::<_, &str>("banana", |k| Ok(k.len())),
2941            Ok((&6, None))
2942        );
2943        assert_eq!(
2944            cache.try_get_or_push_with_key::<_, &str>("lemon", |_| Err("failed")),
2945            Err("failed")
2946        );
2947        assert_eq!(
2948            cache.try_get_or_push_with_key::<_, &str>("lemo", |k| Ok(k.len())),
2949            Ok((&4, Some(("apple", 5))))
2950        );
2951        assert_eq!(
2952            cache.try_get_or_push_with_key::<_, &str>("banana", |_| Err("failed")),
2953            Ok((&6, None))
2954        );
2955    }
2956
2957    #[test]
2958    fn test_try_get_or_insert_ref() {
2959        use alloc::borrow::ToOwned;
2960        use alloc::string::String;
2961
2962        let key1 = Rc::new("1".to_owned());
2963        let key2 = Rc::new("2".to_owned());
2964        let mut cache = LruCache::<Rc<String>, String>::new(NonZeroUsize::new(2).unwrap());
2965        let f = || -> Result<String, ()> { Err(()) };
2966        let a = || -> Result<String, ()> { Ok("One".to_owned()) };
2967        let b = || -> Result<String, ()> { Ok("Two".to_owned()) };
2968        assert_eq!(cache.try_get_or_insert_ref(&key1, a), Ok(&"One".to_owned()));
2969        assert_eq!(cache.try_get_or_insert_ref(&key2, f), Err(()));
2970        assert_eq!(cache.try_get_or_insert_ref(&key2, b), Ok(&"Two".to_owned()));
2971        assert_eq!(cache.try_get_or_insert_ref(&key2, a), Ok(&"Two".to_owned()));
2972        assert_eq!(cache.len(), 2);
2973        assert_eq!(Rc::strong_count(&key1), 2);
2974        assert_eq!(Rc::strong_count(&key2), 2);
2975    }
2976
2977    #[test]
2978    fn test_try_get_or_push_ref() {
2979        use alloc::borrow::ToOwned;
2980        use alloc::string::String;
2981
2982        let key1 = Rc::new("1".to_owned());
2983        let key2 = Rc::new("2".to_owned());
2984        let key3 = Rc::new("3".to_owned());
2985        let mut cache = LruCache::<Rc<String>, String>::new(NonZeroUsize::new(2).unwrap());
2986        let f = || -> Result<String, ()> { Err(()) };
2987        let a = || -> Result<String, ()> { Ok("One".to_owned()) };
2988        let b = || -> Result<String, ()> { Ok("Two".to_owned()) };
2989        let c = || -> Result<String, ()> { Ok("Three".to_owned()) };
2990        assert_eq!(
2991            cache.try_get_or_push_ref(&key1, a),
2992            Ok((&"One".to_owned(), None))
2993        );
2994        assert_eq!(cache.try_get_or_push_ref(&key2, f), Err(()));
2995        assert_eq!(
2996            cache.try_get_or_push_ref(&key2, b),
2997            Ok((&"Two".to_owned(), None))
2998        );
2999        assert_eq!(
3000            cache.try_get_or_push_ref(&key3, c),
3001            Ok((&"Three".to_owned(), Some((key1.clone(), "One".to_owned()))))
3002        );
3003        assert_eq!(
3004            cache.try_get_or_push_ref(&key2, a),
3005            Ok((&"Two".to_owned(), None))
3006        );
3007        assert_eq!(cache.len(), 2);
3008        assert_eq!(Rc::strong_count(&key1), 1);
3009        assert_eq!(Rc::strong_count(&key2), 2);
3010        assert_eq!(Rc::strong_count(&key3), 2);
3011    }
3012
3013    #[test]
3014    fn test_put_and_get_or_insert_mut() {
3015        let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
3016        assert!(cache.is_empty());
3017
3018        assert_eq!(cache.put("apple", "red"), None);
3019        assert_eq!(cache.put("banana", "yellow"), None);
3020
3021        assert_eq!(cache.cap().get(), 2);
3022        assert_eq!(cache.len(), 2);
3023
3024        let v = cache.get_or_insert_mut("apple", || "orange");
3025        assert_eq!(v, &"red");
3026        *v = "blue";
3027
3028        assert_eq!(cache.get_or_insert_mut("apple", || "orange"), &"blue");
3029        assert_eq!(cache.get_or_insert_mut("banana", || "orange"), &"yellow");
3030        assert_eq!(cache.get_or_insert_mut("lemon", || "orange"), &"orange");
3031        assert_eq!(cache.get_or_insert_mut("lemon", || "red"), &"orange");
3032    }
3033
3034    #[test]
3035    fn test_put_and_get_or_push_mut() {
3036        let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
3037        assert!(cache.is_empty());
3038
3039        assert_eq!(cache.put("apple", "red"), None);
3040        assert_eq!(cache.put("banana", "yellow"), None);
3041
3042        assert_eq!(cache.cap().get(), 2);
3043        assert_eq!(cache.len(), 2);
3044
3045        let (v, r) = cache.get_or_push_mut("apple", || "orange");
3046        assert_eq!(v, &"red");
3047        assert_eq!(r, None);
3048        *v = "blue";
3049
3050        assert_eq!(
3051            cache.get_or_push_mut("apple", || "orange"),
3052            (&mut "blue", None)
3053        );
3054        assert_eq!(
3055            cache.get_or_push_mut("banana", || "orange"),
3056            (&mut "yellow", None)
3057        );
3058        assert_eq!(
3059            cache.get_or_push_mut("lemon", || "orange"),
3060            (&mut "orange", Some(("apple", "blue")))
3061        );
3062        assert_eq!(
3063            cache.get_or_push_mut("lemon", || "red"),
3064            (&mut "orange", None)
3065        );
3066    }
3067
3068    #[test]
3069    fn test_put_and_get_or_insert_mut_with_key() {
3070        let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
3071        assert!(cache.is_empty());
3072
3073        assert_eq!(cache.put("apple", 2), None);
3074        assert_eq!(cache.put("banana", 8), None);
3075
3076        assert_eq!(cache.cap().get(), 2);
3077        assert_eq!(cache.len(), 2);
3078
3079        let v = cache.get_or_insert_mut_with_key("apple", |k| k.len());
3080        assert_eq!(v, &2);
3081        *v = 4;
3082
3083        assert_eq!(cache.get_or_insert_mut_with_key("apple", |k| k.len()), &4);
3084        assert_eq!(cache.get_or_insert_mut_with_key("banana", |k| k.len()), &8);
3085        assert_eq!(cache.get_or_insert_mut_with_key("lemon", |k| k.len()), &5);
3086        assert_eq!(cache.get_or_insert_mut_with_key("lemon", |_| 0), &5);
3087    }
3088
3089    #[test]
3090    fn test_put_and_get_or_push_mut_with_key() {
3091        let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
3092        assert!(cache.is_empty());
3093
3094        assert_eq!(cache.put("apple", 2), None);
3095        assert_eq!(cache.put("banana", 8), None);
3096
3097        assert_eq!(cache.cap().get(), 2);
3098        assert_eq!(cache.len(), 2);
3099
3100        let (v, r) = cache.get_or_push_mut_with_key("apple", |k| k.len());
3101        assert_eq!(v, &2);
3102        assert_eq!(r, None);
3103        *v = 4;
3104
3105        assert_eq!(
3106            cache.get_or_push_mut_with_key("apple", |k| k.len()),
3107            (&mut 4, None)
3108        );
3109        assert_eq!(
3110            cache.get_or_push_mut_with_key("banana", |k| k.len()),
3111            (&mut 8, None)
3112        );
3113        assert_eq!(
3114            cache.get_or_push_mut_with_key("lemon", |k| k.len()),
3115            (&mut 5, Some(("apple", 4)))
3116        );
3117        assert_eq!(
3118            cache.get_or_push_mut_with_key("lemon", |_| 0),
3119            (&mut 5, None)
3120        );
3121    }
3122
3123    #[test]
3124    fn test_get_or_insert_mut_ref() {
3125        use alloc::borrow::ToOwned;
3126        use alloc::string::String;
3127
3128        let key1 = Rc::new("1".to_owned());
3129        let key2 = Rc::new("2".to_owned());
3130        let mut cache = LruCache::<Rc<String>, &'static str>::new(NonZeroUsize::new(2).unwrap());
3131        assert_eq!(cache.get_or_insert_mut_ref(&key1, || "One"), &mut "One");
3132        let v = cache.get_or_insert_mut_ref(&key2, || "Two");
3133        *v = "New two";
3134        assert_eq!(cache.get_or_insert_mut_ref(&key2, || "Two"), &mut "New two");
3135        assert_eq!(Rc::strong_count(&key1), 2);
3136        assert_eq!(Rc::strong_count(&key2), 2);
3137    }
3138
3139    #[test]
3140    fn test_get_or_push_mut_ref() {
3141        use alloc::borrow::ToOwned;
3142        use alloc::string::String;
3143
3144        let key1 = Rc::new("1".to_owned());
3145        let key2 = Rc::new("2".to_owned());
3146        let key3 = Rc::new("3".to_owned());
3147        let mut cache = LruCache::<Rc<String>, &'static str>::new(NonZeroUsize::new(2).unwrap());
3148        assert_eq!(
3149            cache.get_or_push_mut_ref(&key1, || "One"),
3150            (&mut "One", None)
3151        );
3152        let (v, r) = cache.get_or_push_mut_ref(&key2, || "Two");
3153        *v = "New two";
3154        assert_eq!(r, None);
3155        assert_eq!(
3156            cache.get_or_push_mut_ref(&key2, || "Two"),
3157            (&mut "New two", None)
3158        );
3159        assert_eq!(
3160            cache.get_or_push_mut_ref(&key3, || "Three"),
3161            (&mut "Three", Some((key1.clone(), "One")))
3162        );
3163        assert_eq!(Rc::strong_count(&key1), 1);
3164        assert_eq!(Rc::strong_count(&key2), 2);
3165        assert_eq!(Rc::strong_count(&key3), 2);
3166    }
3167
3168    #[test]
3169    fn test_try_get_or_insert_mut() {
3170        let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
3171
3172        cache.put(1, "a");
3173        cache.put(2, "b");
3174        cache.put(2, "c");
3175
3176        let f = || -> Result<&str, &str> { Err("failed") };
3177        let a = || -> Result<&str, &str> { Ok("a") };
3178        let b = || -> Result<&str, &str> { Ok("b") };
3179        if let Ok(v) = cache.try_get_or_insert_mut(2, a) {
3180            *v = "d";
3181        }
3182        assert_eq!(cache.try_get_or_insert_mut(2, a), Ok(&mut "d"));
3183        assert_eq!(cache.try_get_or_insert_mut(3, f), Err("failed"));
3184        assert_eq!(cache.try_get_or_insert_mut(4, b), Ok(&mut "b"));
3185        assert_eq!(cache.try_get_or_insert_mut(4, a), Ok(&mut "b"));
3186    }
3187
3188    #[test]
3189    fn test_try_get_or_push_mut() {
3190        let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
3191
3192        cache.put(1, "a");
3193        cache.put(2, "b");
3194        cache.put(2, "c");
3195
3196        let f = || -> Result<&str, &str> { Err("failed") };
3197        let a = || -> Result<&str, &str> { Ok("a") };
3198        let b = || -> Result<&str, &str> { Ok("b") };
3199        if let Ok((v, r)) = cache.try_get_or_push_mut(2, a) {
3200            *v = "d";
3201            assert_eq!(r, None);
3202        }
3203        assert_eq!(cache.try_get_or_push_mut(2, a), Ok((&mut "d", None)));
3204        assert_eq!(cache.try_get_or_push_mut(3, f), Err("failed"));
3205        assert_eq!(
3206            cache.try_get_or_push_mut(4, b),
3207            Ok((&mut "b", Some((1, "a"))))
3208        );
3209        assert_eq!(cache.try_get_or_push_mut(4, a), Ok((&mut "b", None)));
3210    }
3211
3212    #[test]
3213    fn test_try_get_or_insert_mut_with_key() {
3214        let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
3215
3216        cache.put("One", 1);
3217        cache.put("Two", 2);
3218        cache.put("Two", 3);
3219
3220        let f = |_: &&str| -> Result<usize, &str> { Err("failed") };
3221        let len = |k: &&str| -> Result<usize, &str> { Ok(k.len()) };
3222        let zero = |_: &&str| -> Result<usize, &str> { Ok(0) };
3223        if let Ok(v) = cache.try_get_or_insert_mut_with_key("Two", f) {
3224            *v = 6;
3225        }
3226        assert_eq!(cache.try_get_or_insert_mut_with_key("Two", len), Ok(&mut 6));
3227        assert_eq!(
3228            cache.try_get_or_insert_mut_with_key("Three", f),
3229            Err("failed")
3230        );
3231        assert_eq!(
3232            cache.try_get_or_insert_mut_with_key("Four", len),
3233            Ok(&mut 4)
3234        );
3235        assert_eq!(
3236            cache.try_get_or_insert_mut_with_key("Four", zero),
3237            Ok(&mut 4)
3238        );
3239    }
3240
3241    #[test]
3242    fn test_try_get_or_push_mut_with_key() {
3243        let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
3244
3245        cache.put("One", 1);
3246        cache.put("Two", 2);
3247        cache.put("Two", 3);
3248
3249        let f = |_: &&str| -> Result<usize, &str> { Err("failed") };
3250        let len = |k: &&str| -> Result<usize, &str> { Ok(k.len()) };
3251        let zero = |_: &&str| -> Result<usize, &str> { Ok(0) };
3252        if let Ok((v, r)) = cache.try_get_or_push_mut_with_key("Two", f) {
3253            *v = 6;
3254            assert_eq!(r, None);
3255        }
3256        assert_eq!(
3257            cache.try_get_or_push_mut_with_key("Two", len),
3258            Ok((&mut 6, None))
3259        );
3260        assert_eq!(
3261            cache.try_get_or_push_mut_with_key("Three", f),
3262            Err("failed")
3263        );
3264        assert_eq!(
3265            cache.try_get_or_push_mut_with_key("Four", len),
3266            Ok((&mut 4, Some(("One", 1))))
3267        );
3268        assert_eq!(
3269            cache.try_get_or_push_mut_with_key("Four", zero),
3270            Ok((&mut 4, None))
3271        );
3272    }
3273
3274    #[test]
3275    fn test_try_get_or_insert_mut_ref() {
3276        use alloc::borrow::ToOwned;
3277        use alloc::string::String;
3278
3279        let key1 = Rc::new("1".to_owned());
3280        let key2 = Rc::new("2".to_owned());
3281        let mut cache = LruCache::<Rc<String>, String>::new(NonZeroUsize::new(2).unwrap());
3282        let f = || -> Result<String, ()> { Err(()) };
3283        let a = || -> Result<String, ()> { Ok("One".to_owned()) };
3284        let b = || -> Result<String, ()> { Ok("Two".to_owned()) };
3285        assert_eq!(
3286            cache.try_get_or_insert_mut_ref(&key1, a),
3287            Ok(&mut "One".to_owned())
3288        );
3289        assert_eq!(cache.try_get_or_insert_mut_ref(&key2, f), Err(()));
3290        if let Ok(v) = cache.try_get_or_insert_mut_ref(&key2, b) {
3291            assert_eq!(v, &mut "Two");
3292            *v = "New two".to_owned();
3293        }
3294        assert_eq!(
3295            cache.try_get_or_insert_mut_ref(&key2, a),
3296            Ok(&mut "New two".to_owned())
3297        );
3298        assert_eq!(Rc::strong_count(&key1), 2);
3299        assert_eq!(Rc::strong_count(&key2), 2);
3300    }
3301
3302    #[test]
3303    fn test_try_get_or_push_mut_ref() {
3304        use alloc::borrow::ToOwned;
3305        use alloc::string::String;
3306
3307        let key1 = Rc::new("1".to_owned());
3308        let key2 = Rc::new("2".to_owned());
3309        let key3 = Rc::new("3".to_owned());
3310        let mut cache = LruCache::<Rc<String>, String>::new(NonZeroUsize::new(2).unwrap());
3311        let f = || -> Result<String, ()> { Err(()) };
3312        let a = || -> Result<String, ()> { Ok("One".to_owned()) };
3313        let b = || -> Result<String, ()> { Ok("Two".to_owned()) };
3314        let c = || -> Result<String, ()> { Ok("Three".to_owned()) };
3315        assert_eq!(
3316            cache.try_get_or_push_mut_ref(&key1, a),
3317            Ok((&mut "One".to_owned(), None))
3318        );
3319        assert_eq!(cache.try_get_or_push_mut_ref(&key2, f), Err(()));
3320        if let Ok((v, r)) = cache.try_get_or_push_mut_ref(&key2, b) {
3321            assert_eq!(v, &mut "Two");
3322            assert_eq!(r, None);
3323            *v = "New two".to_owned();
3324        }
3325        assert_eq!(
3326            cache.try_get_or_push_mut_ref(&key2, a),
3327            Ok((&mut "New two".to_owned(), None))
3328        );
3329        assert_eq!(
3330            cache.try_get_or_push_mut_ref(&key3, c),
3331            Ok((
3332                &mut "Three".to_owned(),
3333                Some((key1.clone(), "One".to_owned()))
3334            ))
3335        );
3336        assert_eq!(Rc::strong_count(&key1), 1);
3337        assert_eq!(Rc::strong_count(&key2), 2);
3338        assert_eq!(Rc::strong_count(&key3), 2);
3339    }
3340
3341    #[test]
3342    fn test_put_and_get_mut() {
3343        let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
3344
3345        cache.put("apple", "red");
3346        cache.put("banana", "yellow");
3347
3348        assert_eq!(cache.cap().get(), 2);
3349        assert_eq!(cache.len(), 2);
3350        assert_opt_eq_mut(cache.get_mut(&"apple"), "red");
3351        assert_opt_eq_mut(cache.get_mut(&"banana"), "yellow");
3352    }
3353
3354    #[test]
3355    fn test_get_mut_and_update() {
3356        let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
3357
3358        cache.put("apple", 1);
3359        cache.put("banana", 3);
3360
3361        {
3362            let v = cache.get_mut(&"apple").unwrap();
3363            *v = 4;
3364        }
3365
3366        assert_eq!(cache.cap().get(), 2);
3367        assert_eq!(cache.len(), 2);
3368        assert_opt_eq_mut(cache.get_mut(&"apple"), 4);
3369        assert_opt_eq_mut(cache.get_mut(&"banana"), 3);
3370    }
3371
3372    #[test]
3373    fn test_put_update() {
3374        let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
3375
3376        assert_eq!(cache.put("apple", "red"), None);
3377        assert_eq!(cache.put("apple", "green"), Some("red"));
3378
3379        assert_eq!(cache.len(), 1);
3380        assert_opt_eq(cache.get(&"apple"), "green");
3381    }
3382
3383    #[test]
3384    fn test_put_removes_oldest() {
3385        let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
3386
3387        assert_eq!(cache.put("apple", "red"), None);
3388        assert_eq!(cache.put("banana", "yellow"), None);
3389        assert_eq!(cache.put("pear", "green"), None);
3390
3391        assert!(cache.get(&"apple").is_none());
3392        assert_opt_eq(cache.get(&"banana"), "yellow");
3393        assert_opt_eq(cache.get(&"pear"), "green");
3394
3395        // Even though we inserted "apple" into the cache earlier it has since been removed from
3396        // the cache so there is no current value for `put` to return.
3397        assert_eq!(cache.put("apple", "green"), None);
3398        assert_eq!(cache.put("tomato", "red"), None);
3399
3400        assert!(cache.get(&"pear").is_none());
3401        assert_opt_eq(cache.get(&"apple"), "green");
3402        assert_opt_eq(cache.get(&"tomato"), "red");
3403    }
3404
3405    #[test]
3406    fn test_peek() {
3407        let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
3408
3409        cache.put("apple", "red");
3410        cache.put("banana", "yellow");
3411
3412        assert_opt_eq(cache.peek(&"banana"), "yellow");
3413        assert_opt_eq(cache.peek(&"apple"), "red");
3414
3415        cache.put("pear", "green");
3416
3417        assert!(cache.peek(&"apple").is_none());
3418        assert_opt_eq(cache.peek(&"banana"), "yellow");
3419        assert_opt_eq(cache.peek(&"pear"), "green");
3420    }
3421
3422    #[test]
3423    fn test_peek_mut() {
3424        let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
3425
3426        cache.put("apple", "red");
3427        cache.put("banana", "yellow");
3428
3429        assert_opt_eq_mut(cache.peek_mut(&"banana"), "yellow");
3430        assert_opt_eq_mut(cache.peek_mut(&"apple"), "red");
3431        assert!(cache.peek_mut(&"pear").is_none());
3432
3433        cache.put("pear", "green");
3434
3435        assert!(cache.peek_mut(&"apple").is_none());
3436        assert_opt_eq_mut(cache.peek_mut(&"banana"), "yellow");
3437        assert_opt_eq_mut(cache.peek_mut(&"pear"), "green");
3438
3439        {
3440            let v = cache.peek_mut(&"banana").unwrap();
3441            *v = "green";
3442        }
3443
3444        assert_opt_eq_mut(cache.peek_mut(&"banana"), "green");
3445    }
3446
3447    #[test]
3448    fn test_peek_lru() {
3449        let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
3450
3451        assert!(cache.peek_lru().is_none());
3452
3453        cache.put("apple", "red");
3454        cache.put("banana", "yellow");
3455        assert_opt_eq_tuple(cache.peek_lru(), ("apple", "red"));
3456
3457        cache.get(&"apple");
3458        assert_opt_eq_tuple(cache.peek_lru(), ("banana", "yellow"));
3459
3460        cache.clear();
3461        assert!(cache.peek_lru().is_none());
3462    }
3463
3464    #[test]
3465    fn test_peek_mru() {
3466        let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
3467
3468        assert!(cache.peek_mru().is_none());
3469
3470        cache.put("apple", "red");
3471        cache.put("banana", "yellow");
3472        assert_opt_eq_tuple(cache.peek_mru(), ("banana", "yellow"));
3473
3474        cache.get(&"apple");
3475        assert_opt_eq_tuple(cache.peek_mru(), ("apple", "red"));
3476
3477        cache.clear();
3478        assert!(cache.peek_mru().is_none());
3479    }
3480
3481    #[test]
3482    fn test_contains() {
3483        let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
3484
3485        cache.put("apple", "red");
3486        cache.put("banana", "yellow");
3487        cache.put("pear", "green");
3488
3489        assert!(!cache.contains(&"apple"));
3490        assert!(cache.contains(&"banana"));
3491        assert!(cache.contains(&"pear"));
3492    }
3493
3494    #[test]
3495    fn test_pop() {
3496        let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
3497
3498        cache.put("apple", "red");
3499        cache.put("banana", "yellow");
3500
3501        assert_eq!(cache.len(), 2);
3502        assert_opt_eq(cache.get(&"apple"), "red");
3503        assert_opt_eq(cache.get(&"banana"), "yellow");
3504
3505        let popped = cache.pop(&"apple");
3506        assert!(popped.is_some());
3507        assert_eq!(popped.unwrap(), "red");
3508        assert_eq!(cache.len(), 1);
3509        assert!(cache.get(&"apple").is_none());
3510        assert_opt_eq(cache.get(&"banana"), "yellow");
3511    }
3512
3513    #[test]
3514    fn test_pop_entry() {
3515        let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
3516        cache.put("apple", "red");
3517        cache.put("banana", "yellow");
3518
3519        assert_eq!(cache.len(), 2);
3520        assert_opt_eq(cache.get(&"apple"), "red");
3521        assert_opt_eq(cache.get(&"banana"), "yellow");
3522
3523        let popped = cache.pop_entry(&"apple");
3524        assert!(popped.is_some());
3525        assert_eq!(popped.unwrap(), ("apple", "red"));
3526        assert_eq!(cache.len(), 1);
3527        assert!(cache.get(&"apple").is_none());
3528        assert_opt_eq(cache.get(&"banana"), "yellow");
3529    }
3530
3531    #[test]
3532    fn test_pop_lru() {
3533        let mut cache = LruCache::new(NonZeroUsize::new(200).unwrap());
3534
3535        for i in 0..75 {
3536            cache.put(i, "A");
3537        }
3538        for i in 0..75 {
3539            cache.put(i + 100, "B");
3540        }
3541        for i in 0..75 {
3542            cache.put(i + 200, "C");
3543        }
3544        assert_eq!(cache.len(), 200);
3545
3546        for i in 0..75 {
3547            assert_opt_eq(cache.get(&(74 - i + 100)), "B");
3548        }
3549        assert_opt_eq(cache.get(&25), "A");
3550
3551        for i in 26..75 {
3552            assert_eq!(cache.pop_lru(), Some((i, "A")));
3553        }
3554        for i in 0..75 {
3555            assert_eq!(cache.pop_lru(), Some((i + 200, "C")));
3556        }
3557        for i in 0..75 {
3558            assert_eq!(cache.pop_lru(), Some((74 - i + 100, "B")));
3559        }
3560        assert_eq!(cache.pop_lru(), Some((25, "A")));
3561        for _ in 0..50 {
3562            assert_eq!(cache.pop_lru(), None);
3563        }
3564    }
3565
3566    #[test]
3567    fn test_pop_mru() {
3568        let mut cache = LruCache::new(NonZeroUsize::new(200).unwrap());
3569
3570        for i in 0..75 {
3571            cache.put(i, "A");
3572        }
3573        for i in 0..75 {
3574            cache.put(i + 100, "B");
3575        }
3576        for i in 0..75 {
3577            cache.put(i + 200, "C");
3578        }
3579        assert_eq!(cache.len(), 200);
3580
3581        for i in 0..75 {
3582            assert_opt_eq(cache.get(&(74 - i + 100)), "B");
3583        }
3584        assert_opt_eq(cache.get(&25), "A");
3585
3586        assert_eq!(cache.pop_mru(), Some((25, "A")));
3587        for i in 0..75 {
3588            assert_eq!(cache.pop_mru(), Some((i + 100, "B")));
3589        }
3590        for i in 0..75 {
3591            assert_eq!(cache.pop_mru(), Some((74 - i + 200, "C")));
3592        }
3593        for i in (26..75).into_iter().rev() {
3594            assert_eq!(cache.pop_mru(), Some((i, "A")));
3595        }
3596        for _ in 0..50 {
3597            assert_eq!(cache.pop_mru(), None);
3598        }
3599    }
3600
3601    #[test]
3602    fn test_clear() {
3603        let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
3604
3605        cache.put("apple", "red");
3606        cache.put("banana", "yellow");
3607
3608        assert_eq!(cache.len(), 2);
3609        assert_opt_eq(cache.get(&"apple"), "red");
3610        assert_opt_eq(cache.get(&"banana"), "yellow");
3611
3612        cache.clear();
3613        assert_eq!(cache.len(), 0);
3614    }
3615
3616    #[test]
3617    fn test_resize_larger() {
3618        let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
3619
3620        cache.put(1, "a");
3621        cache.put(2, "b");
3622        cache.resize(NonZeroUsize::new(4).unwrap());
3623        cache.put(3, "c");
3624        cache.put(4, "d");
3625
3626        assert_eq!(cache.len(), 4);
3627        assert_eq!(cache.get(&1), Some(&"a"));
3628        assert_eq!(cache.get(&2), Some(&"b"));
3629        assert_eq!(cache.get(&3), Some(&"c"));
3630        assert_eq!(cache.get(&4), Some(&"d"));
3631    }
3632
3633    #[test]
3634    fn test_resize_smaller() {
3635        let mut cache = LruCache::new(NonZeroUsize::new(4).unwrap());
3636
3637        cache.put(1, "a");
3638        cache.put(2, "b");
3639        cache.put(3, "c");
3640        cache.put(4, "d");
3641
3642        cache.resize(NonZeroUsize::new(2).unwrap());
3643
3644        assert_eq!(cache.len(), 2);
3645        assert!(cache.get(&1).is_none());
3646        assert!(cache.get(&2).is_none());
3647        assert_eq!(cache.get(&3), Some(&"c"));
3648        assert_eq!(cache.get(&4), Some(&"d"));
3649    }
3650
3651    #[test]
3652    fn test_send() {
3653        use std::thread;
3654
3655        let mut cache = LruCache::new(NonZeroUsize::new(4).unwrap());
3656        cache.put(1, "a");
3657
3658        let handle = thread::spawn(move || {
3659            assert_eq!(cache.get(&1), Some(&"a"));
3660        });
3661
3662        assert!(handle.join().is_ok());
3663    }
3664
3665    #[test]
3666    fn test_multiple_threads() {
3667        let mut pool = Pool::new(1);
3668        let mut cache = LruCache::new(NonZeroUsize::new(4).unwrap());
3669        cache.put(1, "a");
3670
3671        let cache_ref = &cache;
3672        pool.scoped(|scoped| {
3673            scoped.execute(move || {
3674                assert_eq!(cache_ref.peek(&1), Some(&"a"));
3675            });
3676        });
3677
3678        assert_eq!((cache_ref).peek(&1), Some(&"a"));
3679    }
3680
3681    #[test]
3682    fn test_iter_forwards() {
3683        let mut cache = LruCache::new(NonZeroUsize::new(3).unwrap());
3684        cache.put("a", 1);
3685        cache.put("b", 2);
3686        cache.put("c", 3);
3687
3688        {
3689            // iter const
3690            let mut iter = cache.iter();
3691            assert_eq!(iter.len(), 3);
3692            assert_opt_eq_tuple(iter.next(), ("c", 3));
3693
3694            assert_eq!(iter.len(), 2);
3695            assert_opt_eq_tuple(iter.next(), ("b", 2));
3696
3697            assert_eq!(iter.len(), 1);
3698            assert_opt_eq_tuple(iter.next(), ("a", 1));
3699
3700            assert_eq!(iter.len(), 0);
3701            assert_eq!(iter.next(), None);
3702        }
3703        {
3704            // iter mut
3705            let mut iter = cache.iter_mut();
3706            assert_eq!(iter.len(), 3);
3707            assert_opt_eq_mut_tuple(iter.next(), ("c", 3));
3708
3709            assert_eq!(iter.len(), 2);
3710            assert_opt_eq_mut_tuple(iter.next(), ("b", 2));
3711
3712            assert_eq!(iter.len(), 1);
3713            assert_opt_eq_mut_tuple(iter.next(), ("a", 1));
3714
3715            assert_eq!(iter.len(), 0);
3716            assert_eq!(iter.next(), None);
3717        }
3718    }
3719
3720    #[test]
3721    fn test_iter_backwards() {
3722        let mut cache = LruCache::new(NonZeroUsize::new(3).unwrap());
3723        cache.put("a", 1);
3724        cache.put("b", 2);
3725        cache.put("c", 3);
3726
3727        {
3728            // iter const
3729            let mut iter = cache.iter();
3730            assert_eq!(iter.len(), 3);
3731            assert_opt_eq_tuple(iter.next_back(), ("a", 1));
3732
3733            assert_eq!(iter.len(), 2);
3734            assert_opt_eq_tuple(iter.next_back(), ("b", 2));
3735
3736            assert_eq!(iter.len(), 1);
3737            assert_opt_eq_tuple(iter.next_back(), ("c", 3));
3738
3739            assert_eq!(iter.len(), 0);
3740            assert_eq!(iter.next_back(), None);
3741        }
3742
3743        {
3744            // iter mut
3745            let mut iter = cache.iter_mut();
3746            assert_eq!(iter.len(), 3);
3747            assert_opt_eq_mut_tuple(iter.next_back(), ("a", 1));
3748
3749            assert_eq!(iter.len(), 2);
3750            assert_opt_eq_mut_tuple(iter.next_back(), ("b", 2));
3751
3752            assert_eq!(iter.len(), 1);
3753            assert_opt_eq_mut_tuple(iter.next_back(), ("c", 3));
3754
3755            assert_eq!(iter.len(), 0);
3756            assert_eq!(iter.next_back(), None);
3757        }
3758    }
3759
3760    #[test]
3761    fn test_iter_forwards_and_backwards() {
3762        let mut cache = LruCache::new(NonZeroUsize::new(3).unwrap());
3763        cache.put("a", 1);
3764        cache.put("b", 2);
3765        cache.put("c", 3);
3766
3767        {
3768            // iter const
3769            let mut iter = cache.iter();
3770            assert_eq!(iter.len(), 3);
3771            assert_opt_eq_tuple(iter.next(), ("c", 3));
3772
3773            assert_eq!(iter.len(), 2);
3774            assert_opt_eq_tuple(iter.next_back(), ("a", 1));
3775
3776            assert_eq!(iter.len(), 1);
3777            assert_opt_eq_tuple(iter.next(), ("b", 2));
3778
3779            assert_eq!(iter.len(), 0);
3780            assert_eq!(iter.next_back(), None);
3781        }
3782        {
3783            // iter mut
3784            let mut iter = cache.iter_mut();
3785            assert_eq!(iter.len(), 3);
3786            assert_opt_eq_mut_tuple(iter.next(), ("c", 3));
3787
3788            assert_eq!(iter.len(), 2);
3789            assert_opt_eq_mut_tuple(iter.next_back(), ("a", 1));
3790
3791            assert_eq!(iter.len(), 1);
3792            assert_opt_eq_mut_tuple(iter.next(), ("b", 2));
3793
3794            assert_eq!(iter.len(), 0);
3795            assert_eq!(iter.next_back(), None);
3796        }
3797    }
3798
3799    #[test]
3800    fn test_iter_multiple_threads() {
3801        let mut pool = Pool::new(1);
3802        let mut cache = LruCache::new(NonZeroUsize::new(3).unwrap());
3803        cache.put("a", 1);
3804        cache.put("b", 2);
3805        cache.put("c", 3);
3806
3807        let mut iter = cache.iter();
3808        assert_eq!(iter.len(), 3);
3809        assert_opt_eq_tuple(iter.next(), ("c", 3));
3810
3811        {
3812            let iter_ref = &mut iter;
3813            pool.scoped(|scoped| {
3814                scoped.execute(move || {
3815                    assert_eq!(iter_ref.len(), 2);
3816                    assert_opt_eq_tuple(iter_ref.next(), ("b", 2));
3817                });
3818            });
3819        }
3820
3821        assert_eq!(iter.len(), 1);
3822        assert_opt_eq_tuple(iter.next(), ("a", 1));
3823
3824        assert_eq!(iter.len(), 0);
3825        assert_eq!(iter.next(), None);
3826    }
3827
3828    #[test]
3829    fn test_iter_send_sync_not_send() {
3830        use std::sync::{Mutex, MutexGuard};
3831        use std::thread;
3832
3833        fn assert_send<T: Send>() {}
3834        assert_send::<super::Iter<'_, MutexGuard<'_, ()>, MutexGuard<'_, ()>>>();
3835
3836        let lock = Mutex::new(42);
3837        let mut cache = LruCache::new(NonZeroUsize::new(1).unwrap());
3838        cache.put(1, lock.lock().unwrap());
3839        let mut iter = cache.iter();
3840        thread::scope(|scope| {
3841            scope
3842                .spawn(move || assert_eq!(**iter.next().unwrap().1, 42))
3843                .join()
3844                .unwrap();
3845        });
3846    }
3847
3848    #[test]
3849    fn test_iter_clone() {
3850        let mut cache = LruCache::new(NonZeroUsize::new(3).unwrap());
3851        cache.put("a", 1);
3852        cache.put("b", 2);
3853
3854        let mut iter = cache.iter();
3855        let mut iter_clone = iter.clone();
3856
3857        assert_eq!(iter.len(), 2);
3858        assert_opt_eq_tuple(iter.next(), ("b", 2));
3859        assert_eq!(iter_clone.len(), 2);
3860        assert_opt_eq_tuple(iter_clone.next(), ("b", 2));
3861
3862        assert_eq!(iter.len(), 1);
3863        assert_opt_eq_tuple(iter.next(), ("a", 1));
3864        assert_eq!(iter_clone.len(), 1);
3865        assert_opt_eq_tuple(iter_clone.next(), ("a", 1));
3866
3867        assert_eq!(iter.len(), 0);
3868        assert_eq!(iter.next(), None);
3869        assert_eq!(iter_clone.len(), 0);
3870        assert_eq!(iter_clone.next(), None);
3871    }
3872
3873    #[test]
3874    fn test_into_iter() {
3875        let mut cache = LruCache::new(NonZeroUsize::new(3).unwrap());
3876        cache.put("a", 1);
3877        cache.put("b", 2);
3878        cache.put("c", 3);
3879
3880        let mut iter = cache.into_iter();
3881        assert_eq!(iter.len(), 3);
3882        assert_eq!(iter.next(), Some(("a", 1)));
3883
3884        assert_eq!(iter.len(), 2);
3885        assert_eq!(iter.next(), Some(("b", 2)));
3886
3887        assert_eq!(iter.len(), 1);
3888        assert_eq!(iter.next(), Some(("c", 3)));
3889
3890        assert_eq!(iter.len(), 0);
3891        assert_eq!(iter.next(), None);
3892    }
3893
3894    #[test]
3895    fn test_that_pop_actually_detaches_node() {
3896        let mut cache = LruCache::new(NonZeroUsize::new(5).unwrap());
3897
3898        cache.put("a", 1);
3899        cache.put("b", 2);
3900        cache.put("c", 3);
3901        cache.put("d", 4);
3902        cache.put("e", 5);
3903
3904        assert_eq!(cache.pop(&"c"), Some(3));
3905
3906        cache.put("f", 6);
3907
3908        let mut iter = cache.iter();
3909        assert_opt_eq_tuple(iter.next(), ("f", 6));
3910        assert_opt_eq_tuple(iter.next(), ("e", 5));
3911        assert_opt_eq_tuple(iter.next(), ("d", 4));
3912        assert_opt_eq_tuple(iter.next(), ("b", 2));
3913        assert_opt_eq_tuple(iter.next(), ("a", 1));
3914        assert!(iter.next().is_none());
3915    }
3916
3917    #[test]
3918    fn test_retain() {
3919        let mut cache = LruCache::new(NonZeroUsize::new(5).unwrap());
3920
3921        cache.put(1, 10);
3922        cache.put(2, 20);
3923        cache.put(3, 30);
3924        cache.put(4, 40);
3925        cache.put(5, 50);
3926
3927        // Keep even keys and double the values that are kept.
3928        cache.retain(|k, v| {
3929            if k % 2 == 0 {
3930                *v *= 2;
3931                true
3932            } else {
3933                false
3934            }
3935        });
3936
3937        assert_eq!(cache.len(), 2);
3938        assert_eq!(cache.peek(&2), Some(&40));
3939        assert_eq!(cache.peek(&4), Some(&80));
3940        assert_eq!(cache.peek(&1), None);
3941        assert_eq!(cache.peek(&3), None);
3942        assert_eq!(cache.peek(&5), None);
3943
3944        // The retained entries keep their most-recently-used to least-recently-used order.
3945        let mut iter = cache.iter();
3946        assert_opt_eq_tuple(iter.next(), (4, 80));
3947        assert_opt_eq_tuple(iter.next(), (2, 40));
3948        assert!(iter.next().is_none());
3949
3950        // The list is still consistent, so newly inserted entries land at the front.
3951        cache.put(6, 60);
3952        let mut iter = cache.iter();
3953        assert_opt_eq_tuple(iter.next(), (6, 60));
3954        assert_opt_eq_tuple(iter.next(), (4, 80));
3955        assert_opt_eq_tuple(iter.next(), (2, 40));
3956        assert!(iter.next().is_none());
3957    }
3958
3959    #[test]
3960    fn test_retain_all_and_none() {
3961        let mut cache = LruCache::new(NonZeroUsize::new(3).unwrap());
3962        cache.put(1, "a");
3963        cache.put(2, "b");
3964
3965        cache.retain(|_, _| true);
3966        assert_eq!(cache.len(), 2);
3967
3968        cache.retain(|_, _| false);
3969        assert_eq!(cache.len(), 0);
3970        assert!(cache.is_empty());
3971    }
3972
3973    #[test]
3974    fn test_no_memory_leaks_with_retain() {
3975        static DROP_COUNT: AtomicUsize = AtomicUsize::new(0);
3976
3977        struct DropCounter;
3978
3979        impl Drop for DropCounter {
3980            fn drop(&mut self) {
3981                DROP_COUNT.fetch_add(1, Ordering::SeqCst);
3982            }
3983        }
3984
3985        let n = 100;
3986        for _ in 0..n {
3987            let mut cache = LruCache::unbounded();
3988            for i in 0..n {
3989                cache.put(i, DropCounter {});
3990            }
3991            // Drop half of the entries via `retain` and let the rest drop with the cache.
3992            cache.retain(|k, _| k % 2 == 0);
3993        }
3994        assert_eq!(DROP_COUNT.load(Ordering::SeqCst), n * n);
3995    }
3996
3997    #[test]
3998    fn test_get_with_borrow() {
3999        use alloc::string::String;
4000
4001        let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
4002
4003        let key = String::from("apple");
4004        cache.put(key, "red");
4005
4006        assert_opt_eq(cache.get("apple"), "red");
4007    }
4008
4009    #[test]
4010    fn test_get_mut_with_borrow() {
4011        use alloc::string::String;
4012
4013        let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
4014
4015        let key = String::from("apple");
4016        cache.put(key, "red");
4017
4018        assert_opt_eq_mut(cache.get_mut("apple"), "red");
4019    }
4020
4021    #[test]
4022    fn test_no_memory_leaks() {
4023        static DROP_COUNT: AtomicUsize = AtomicUsize::new(0);
4024
4025        struct DropCounter;
4026
4027        impl Drop for DropCounter {
4028            fn drop(&mut self) {
4029                DROP_COUNT.fetch_add(1, Ordering::SeqCst);
4030            }
4031        }
4032
4033        let n = 100;
4034        for _ in 0..n {
4035            let mut cache = LruCache::new(NonZeroUsize::new(1).unwrap());
4036            for i in 0..n {
4037                cache.put(i, DropCounter {});
4038            }
4039        }
4040        assert_eq!(DROP_COUNT.load(Ordering::SeqCst), n * n);
4041    }
4042
4043    #[test]
4044    fn test_no_memory_leaks_with_clear() {
4045        static DROP_COUNT: AtomicUsize = AtomicUsize::new(0);
4046
4047        struct DropCounter;
4048
4049        impl Drop for DropCounter {
4050            fn drop(&mut self) {
4051                DROP_COUNT.fetch_add(1, Ordering::SeqCst);
4052            }
4053        }
4054
4055        let n = 100;
4056        for _ in 0..n {
4057            let mut cache = LruCache::new(NonZeroUsize::new(1).unwrap());
4058            for i in 0..n {
4059                cache.put(i, DropCounter {});
4060            }
4061            cache.clear();
4062        }
4063        assert_eq!(DROP_COUNT.load(Ordering::SeqCst), n * n);
4064    }
4065
4066    #[test]
4067    fn test_no_memory_leaks_with_resize() {
4068        static DROP_COUNT: AtomicUsize = AtomicUsize::new(0);
4069
4070        struct DropCounter;
4071
4072        impl Drop for DropCounter {
4073            fn drop(&mut self) {
4074                DROP_COUNT.fetch_add(1, Ordering::SeqCst);
4075            }
4076        }
4077
4078        let n = 100;
4079        for _ in 0..n {
4080            let mut cache = LruCache::new(NonZeroUsize::new(1).unwrap());
4081            for i in 0..n {
4082                cache.put(i, DropCounter {});
4083            }
4084            cache.clear();
4085        }
4086        assert_eq!(DROP_COUNT.load(Ordering::SeqCst), n * n);
4087    }
4088
4089    #[test]
4090    fn test_no_memory_leaks_with_pop() {
4091        static DROP_COUNT: AtomicUsize = AtomicUsize::new(0);
4092
4093        #[derive(Hash, PartialEq, Eq)]
4094        struct KeyDropCounter(usize);
4095
4096        impl Drop for KeyDropCounter {
4097            fn drop(&mut self) {
4098                DROP_COUNT.fetch_add(1, Ordering::SeqCst);
4099            }
4100        }
4101
4102        let n = 100;
4103        for _ in 0..n {
4104            let mut cache = LruCache::new(NonZeroUsize::new(1).unwrap());
4105
4106            for i in 0..100 {
4107                cache.put(KeyDropCounter(i), i);
4108                cache.pop(&KeyDropCounter(i));
4109            }
4110        }
4111
4112        assert_eq!(DROP_COUNT.load(Ordering::SeqCst), n * n * 2);
4113    }
4114
4115    #[test]
4116    fn test_find_and_promote() {
4117        let mut cache = LruCache::new(NonZeroUsize::new(3).unwrap());
4118        cache.put(1, "a");
4119        cache.put(2, "b");
4120        cache.put(3, "c");
4121
4122        let found = cache.find_and_promote(|(_, value)| *value == "b");
4123        assert_eq!(found, Some((&2, &"b")));
4124        assert_eq!(cache.pop_lru(), Some((1, "a")));
4125        assert_eq!(cache.pop_lru(), Some((3, "c")));
4126        assert_eq!(cache.pop_lru(), Some((2, "b")));
4127        assert_eq!(cache.pop_lru(), None);
4128    }
4129
4130    #[test]
4131    fn test_find_and_promote_no_match() {
4132        let mut cache = LruCache::new(NonZeroUsize::new(3).unwrap());
4133        cache.put(1, "a");
4134        cache.put(2, "b");
4135        cache.put(3, "c");
4136
4137        let found = cache.find_and_promote(|(_, value)| *value == "d");
4138        assert_eq!(found, None);
4139        assert_eq!(cache.pop_lru(), Some((1, "a")));
4140        assert_eq!(cache.pop_lru(), Some((2, "b")));
4141        assert_eq!(cache.pop_lru(), Some((3, "c")));
4142        assert_eq!(cache.pop_lru(), None);
4143    }
4144
4145    #[test]
4146    fn test_find_and_promote_multiple_matches_picks_first_in_mru_order() {
4147        let mut cache = LruCache::new(NonZeroUsize::new(3).unwrap());
4148        cache.put(1, "b");
4149        cache.put(2, "b");
4150        cache.put(3, "x");
4151
4152        let found = cache.find_and_promote(|(_, value)| *value == "b");
4153        assert_eq!(found, Some((&2, &"b")));
4154        assert_eq!(cache.pop_lru(), Some((1, "b")));
4155        assert_eq!(cache.pop_lru(), Some((3, "x")));
4156        assert_eq!(cache.pop_lru(), Some((2, "b")));
4157        assert_eq!(cache.pop_lru(), None);
4158    }
4159
4160    #[test]
4161    fn test_promote_and_demote() {
4162        let mut cache = LruCache::new(NonZeroUsize::new(5).unwrap());
4163        for i in 0..5 {
4164            cache.push(i, i);
4165        }
4166        cache.promote(&1);
4167        cache.promote(&0);
4168        cache.demote(&3);
4169        cache.demote(&4);
4170        assert_eq!(cache.pop_lru(), Some((4, 4)));
4171        assert_eq!(cache.pop_lru(), Some((3, 3)));
4172        assert_eq!(cache.pop_lru(), Some((2, 2)));
4173        assert_eq!(cache.pop_lru(), Some((1, 1)));
4174        assert_eq!(cache.pop_lru(), Some((0, 0)));
4175        assert_eq!(cache.pop_lru(), None);
4176    }
4177
4178    #[test]
4179    fn test_get_key_value() {
4180        use alloc::string::String;
4181
4182        let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
4183
4184        let key = String::from("apple");
4185        cache.put(key, "red");
4186
4187        assert_eq!(
4188            cache.get_key_value("apple"),
4189            Some((&String::from("apple"), &"red"))
4190        );
4191        assert_eq!(cache.get_key_value("banana"), None);
4192    }
4193
4194    #[test]
4195    fn test_get_key_value_mut() {
4196        use alloc::string::String;
4197
4198        let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
4199
4200        let key = String::from("apple");
4201        cache.put(key, "red");
4202
4203        let (k, v) = cache.get_key_value_mut("apple").unwrap();
4204        assert_eq!(k, &String::from("apple"));
4205        assert_eq!(v, &mut "red");
4206        *v = "green";
4207
4208        assert_eq!(
4209            cache.get_key_value("apple"),
4210            Some((&String::from("apple"), &"green"))
4211        );
4212        assert_eq!(cache.get_key_value("banana"), None);
4213    }
4214
4215    #[test]
4216    fn test_clone() {
4217        let mut cache = LruCache::new(NonZeroUsize::new(3).unwrap());
4218        cache.put("a", 1);
4219        cache.put("b", 2);
4220        cache.put("c", 3);
4221
4222        let mut cloned = cache.clone();
4223
4224        assert_eq!(cache.pop_lru(), Some(("a", 1)));
4225        assert_eq!(cloned.pop_lru(), Some(("a", 1)));
4226
4227        assert_eq!(cache.pop_lru(), Some(("b", 2)));
4228        assert_eq!(cloned.pop_lru(), Some(("b", 2)));
4229
4230        assert_eq!(cache.pop_lru(), Some(("c", 3)));
4231        assert_eq!(cloned.pop_lru(), Some(("c", 3)));
4232
4233        assert_eq!(cache.pop_lru(), None);
4234        assert_eq!(cloned.pop_lru(), None);
4235    }
4236
4237    #[test]
4238    fn test_clone_unbounded() {
4239        let mut cache = LruCache::unbounded();
4240        cache.put("a", 1);
4241        cache.put("b", 2);
4242        cache.put("c", 3);
4243
4244        let mut cloned = cache.clone();
4245
4246        assert_eq!(cache.pop_lru(), Some(("a", 1)));
4247        assert_eq!(cloned.pop_lru(), Some(("a", 1)));
4248
4249        assert_eq!(cache.pop_lru(), Some(("b", 2)));
4250        assert_eq!(cloned.pop_lru(), Some(("b", 2)));
4251
4252        assert_eq!(cache.pop_lru(), Some(("c", 3)));
4253        assert_eq!(cloned.pop_lru(), Some(("c", 3)));
4254
4255        assert_eq!(cache.pop_lru(), None);
4256        assert_eq!(cloned.pop_lru(), None);
4257    }
4258
4259    #[test]
4260    fn iter_mut_stacked_borrows_violation() {
4261        let mut cache: LruCache<i32, i32> = LruCache::new(NonZeroUsize::new(3).unwrap());
4262        cache.put(1, 10);
4263        cache.put(2, 20);
4264        cache.put(3, 30);
4265
4266        for (_k, v) in cache.iter_mut() {
4267            *v *= 2;
4268        }
4269
4270        assert_eq!(cache.get(&1), Some(&20));
4271        assert_eq!(cache.get(&2), Some(&40));
4272        assert_eq!(cache.get(&3), Some(&60));
4273    }
4274
4275    #[test]
4276    fn test_pop_panicking_key_drop_keeps_list_consistent() {
4277        use std::panic::{AssertUnwindSafe, catch_unwind};
4278        use std::sync::atomic::{AtomicBool, Ordering};
4279
4280        static ARMED: AtomicBool = AtomicBool::new(false);
4281
4282        #[derive(PartialEq, Eq, Hash)]
4283        struct PanicKey(u32);
4284        impl Drop for PanicKey {
4285            fn drop(&mut self) {
4286                if ARMED.swap(false, Ordering::SeqCst) {
4287                    panic!("PanicKey::drop");
4288                }
4289            }
4290        }
4291
4292        let mut cache = LruCache::new(NonZeroUsize::new(4).unwrap());
4293        cache.put(PanicKey(1), "a");
4294        cache.put(PanicKey(2), "b");
4295        cache.put(PanicKey(3), "c");
4296
4297        ARMED.store(true, Ordering::SeqCst);
4298        let _ = catch_unwind(AssertUnwindSafe(|| {
4299            cache.pop(&PanicKey(2));
4300        }));
4301
4302        cache.put(PanicKey(4), "d");
4303        cache.put(PanicKey(5), "e");
4304        let _ = cache.get(&PanicKey(3));
4305        for (_k, _v) in cache.iter() {}
4306    }
4307}