1#![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
88struct 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 #![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#[repr(transparent)]
114struct KeyWrapper<K: ?Sized>(K);
115
116impl<K: ?Sized> KeyWrapper<K> {
117 fn from_ref(key: &K) -> &Self {
118 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 #![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
152struct 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
186pub struct LruCache<K, V, S = DefaultHasher> {
188 map: HashMap<KeyRef<K>, NonNull<LruEntry<K, V>>, S>,
189 cap: NonZeroUsize,
190
191 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 pub fn new(cap: NonZeroUsize) -> LruCache<K, V> {
232 LruCache::construct(cap, HashMap::with_capacity(cap.get()))
233 }
234
235 pub fn sparse(cap: NonZeroUsize) -> LruCache<K, V> {
246 LruCache::construct(cap, HashMap::default())
247 }
248
249 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 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 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 fn construct(
300 cap: NonZeroUsize,
301 map: HashMap<KeyRef<K>, NonNull<LruEntry<K, V>>, S>,
302 ) -> LruCache<K, V, S> {
303 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 fn is_unbounded(&self) -> bool {
322 self.cap() == NonZeroUsize::MAX
323 }
324
325 pub fn put(&mut self, k: K, v: V) -> Option<V> {
343 self.capturing_put(k, v, false).map(|(_, v)| v)
344 }
345
346 pub fn push(&mut self, k: K, v: V) -> Option<(K, V)> {
371 self.capturing_put(k, v, true)
372 }
373
374 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 let node_ptr: *mut LruEntry<K, V> = node_ref.as_ptr();
385
386 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 #[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 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 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 (
435 None,
436 NonNull::new(Box::into_raw(Box::new(LruEntry::new(k, v)))).unwrap(),
437 )
438 }
439 }
440
441 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 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 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 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 #[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 #[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 #[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 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 #[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 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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 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 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 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 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 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 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 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 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 pub fn pop_lru(&mut self) -> Option<(K, V)> {
1897 let node = self.remove_last()?;
1898 let node = *node;
1900 let LruEntry { key, val, .. } = node;
1901 unsafe { Some((key.assume_init(), val.assume_init())) }
1902 }
1903
1904 pub fn pop_mru(&mut self) -> Option<(K, V)> {
1925 let node = self.remove_first()?;
1926 let node = *node;
1928 let LruEntry { key, val, .. } = node;
1929 unsafe { Some((key.assume_init(), val.assume_init())) }
1930 }
1931
1932 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 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 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 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 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 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 pub fn len(&self) -> usize {
2143 self.map.len()
2144 }
2145
2146 pub fn is_empty(&self) -> bool {
2160 self.map.len() == 0
2161 }
2162
2163 pub fn cap(&self) -> NonZeroUsize {
2174 self.cap
2175 }
2176
2177 pub fn resize(&mut self, cap: NonZeroUsize) {
2200 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 pub fn clear(&mut self) {
2233 while self.pop_lru().is_some() {}
2234 }
2235
2236 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 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 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 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 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
2392unsafe 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
2407pub 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
2493unsafe 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
2498pub 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
2556unsafe 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
2561pub 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
2604fn _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 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 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 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 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 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 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 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 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 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 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 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}