1use std::{
14 borrow::Borrow, fmt::{self, Debug}, hash::{BuildHasher, Hash}, marker::PhantomData, mem, ops::{Index, IndexMut}, ptr::{self, NonNull}
15};
16
17use crate::{HashMap, DefaultHasher};
18use super::{KeyRef, KeyWrapper};
19
20#[cfg(feature = "ttl")]
21use crate::get_milltimestamp;
22#[cfg(feature = "ttl")]
23const DEFAULT_CHECK_STEP: u64 = 120;
24pub(crate) struct LruEntry<K, V> {
26 pub key: mem::MaybeUninit<K>,
28 pub val: mem::MaybeUninit<V>,
30 pub prev: *mut LruEntry<K, V>,
31 pub next: *mut LruEntry<K, V>,
32 #[cfg(feature = "ttl")]
35 pub expire: u64,
36}
37
38impl<K, V> LruEntry<K, V> {
39 pub fn new_empty() -> Self {
40 LruEntry {
41 key: mem::MaybeUninit::uninit(),
42 val: mem::MaybeUninit::uninit(),
43 prev: ptr::null_mut(),
44 next: ptr::null_mut(),
45 #[cfg(feature = "ttl")]
46 expire: u64::MAX,
47 }
48 }
49
50 pub fn new(k: K, v: V) -> Self {
51 LruEntry {
52 key: mem::MaybeUninit::new(k),
53 val: mem::MaybeUninit::new(v),
54 prev: ptr::null_mut(),
55 next: ptr::null_mut(),
56 #[cfg(feature = "ttl")]
57 expire: u64::MAX,
58 }
59 }
60
61 #[cfg(feature = "ttl")]
62 #[allow(dead_code)]
63 pub fn new_expire(k: K, v: V, expire: u64) -> Self {
64 LruEntry {
65 key: mem::MaybeUninit::new(k),
66 val: mem::MaybeUninit::new(v),
67 prev: ptr::null_mut(),
68 next: ptr::null_mut(),
69 expire,
70 }
71 }
72
73
74 #[cfg(feature = "ttl")]
75 #[inline(always)]
76 pub fn is_expire(&self) -> bool {
77 get_milltimestamp() >= self.expire
78 }
79
80
81 #[cfg(feature = "ttl")]
82 #[inline(always)]
83 pub fn is_little(&self, time: &u64) -> bool {
84 time >= &self.expire
85 }
86
87 #[cfg(feature = "ttl")]
88 #[inline(always)]
89 pub fn get_ttl(&self) -> u64 {
90 if self.expire == u64::MAX {
91 self.expire
92 } else {
93 self.expire.saturating_sub(get_milltimestamp()) / 1000
94 }
95 }
96}
97
98
99pub struct LruCache<K, V, S> {
121 map: HashMap<KeyRef<K>, NonNull<LruEntry<K, V>>, S>,
123 cap: usize,
125 head: *mut LruEntry<K, V>,
127 tail: *mut LruEntry<K, V>,
129 #[cfg(feature = "ttl")]
131 check_next: u64,
132 #[cfg(feature = "ttl")]
134 check_step: u64,
135 #[cfg(feature = "ttl")]
137 has_ttl: bool,
138}
139
140impl<K: Hash + Eq, V> Default for LruCache<K, V, DefaultHasher> {
141 fn default() -> Self {
142 LruCache::new(100 )
143 }
144}
145
146impl<K: Hash + Eq, V> LruCache<K, V, DefaultHasher> {
147 pub fn new(cap: usize) -> Self {
148 LruCache::with_hasher(cap, DefaultHasher::default())
149 }
150}
151
152impl<K, V, S> LruCache<K, V, S> {
153 pub fn with_hasher(cap: usize, hash_builder: S) -> LruCache<K, V, S> {
155 let cap = cap.max(1);
156 let map = HashMap::with_capacity_and_hasher(cap, hash_builder);
157 let head = Box::into_raw(Box::new(LruEntry::new_empty()));
158 let tail = Box::into_raw(Box::new(LruEntry::new_empty()));
159 unsafe {
160 (*head).next = tail;
161 (*tail).prev = head;
162 }
163 Self {
164 map,
165 cap,
166 head,
167 tail,
168 #[cfg(feature = "ttl")]
169 check_step: DEFAULT_CHECK_STEP,
170 #[cfg(feature = "ttl")]
171 check_next: get_milltimestamp()+DEFAULT_CHECK_STEP * 1000,
172 #[cfg(feature = "ttl")]
173 has_ttl: false,
174 }
175 }
176
177 #[cfg(feature="ttl")]
179 pub fn get_check_step(&self) -> u64 {
180 self.check_step
181 }
182
183 #[cfg(feature="ttl")]
189 pub fn set_check_step(&mut self, check_step: u64) {
190 self.check_step = check_step;
191 self.check_next = get_milltimestamp() + self.check_step * 1000;
192 }
193
194 pub fn capacity(&self) -> usize {
196 self.cap
197 }
198
199 pub fn clear(&mut self) {
215 self.map.drain().for_each(|(_, entry)| {
216 let _node = unsafe { *Box::from_raw(entry.as_ptr()) };
217 });
218 unsafe {
219 (*self.head).next = self.tail;
220 (*self.tail).prev = self.head;
221 }
222 }
223
224 pub fn len(&self) -> usize {
226 self.map.len()
227 }
228
229 pub fn is_full(&self) -> bool {
230 self.map.len() == self.cap
231 }
232
233 pub fn is_empty(&self) -> bool {
234 self.map.len() == 0
235 }
236
237 fn detach(&mut self, entry: *mut LruEntry<K, V>) {
239 unsafe {
240 (*(*entry).prev).next = (*entry).next;
241 (*(*entry).next).prev = (*entry).prev;
242 }
243 }
244
245 fn attach(&mut self, entry: *mut LruEntry<K, V>) {
247 unsafe {
248 (*entry).next = (*self.head).next;
249 (*(*entry).next).prev = entry;
250 (*entry).prev = self.head;
251 (*self.head).next = entry;
252 }
253 }
254
255 pub fn reserve(&mut self, additional: usize) -> &mut Self {
257 self.cap += additional;
258 self
259 }
260
261 pub fn iter(&self) -> Iter<'_, K, V> {
277 Iter { len: self.map.len(), ptr: self.head, end: self.tail, phantom: PhantomData }
278 }
279
280
281 pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
298 IterMut { len: self.map.len(), ptr: self.head, end: self.tail, phantom: PhantomData }
299 }
300
301 pub fn keys(&self) -> Keys<'_, K, V> {
316 Keys {
317 iter: self.iter()
318 }
319 }
320
321 pub fn values(&self) -> Values<'_, K, V> {
339 Values {
340 iter: self.iter()
341 }
342 }
343
344
345 pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
363 ValuesMut {
364 iter: self.iter_mut()
365 }
366 }
367
368 pub fn hasher(&self) -> &S {
369 self.map.hasher()
370 }
371}
372
373impl<K: Hash + Eq, V, S: BuildHasher> LruCache<K, V, S> {
374 pub fn full_increase(&mut self) {
375 if self.cap == self.len() {
376 self.cap += 1;
377 }
378 }
379
380 pub fn full_decrease(&mut self) -> Option<(K, V)> {
381 if self.cap == self.len() {
382 let ret = self.pop_unusual();
383 self.cap = self.cap.saturating_sub(1);
384 ret
385 } else {
386 None
387 }
388 }
389 pub fn drain(&mut self) -> Drain<'_, K, V, S> {
405 Drain { base: self }
406 }
407
408
409 pub fn pop_usual(&mut self) -> Option<(K, V)> {
422 if self.len() == 0 {
423 return None;
424 }
425 unsafe {
426 let node = (*self.head).next;
427 self.detach(node);
428 let key = KeyRef::new((*node).key.as_ptr());
429 let value = self.map.remove(&key).expect("must ok");
430 let node = *Box::from_raw(value.as_ptr());
431 let LruEntry { key, val, .. } = node;
432 Some((key.assume_init(), val.assume_init()))
433 }
434 }
435
436 pub fn pop_unusual(&mut self) -> Option<(K, V)> {
449 if self.len() == 0 {
450 return None;
451 }
452 unsafe {
453 let node = (*self.tail).prev;
454 self.detach(node);
455 let key = KeyRef::new((*node).key.as_ptr());
456 let value = self.map.remove(&key).expect("must ok");
457 let node = *Box::from_raw(value.as_ptr());
458 let LruEntry { key, val, .. } = node;
459 Some((key.assume_init(), val.assume_init()))
460 }
461 }
462
463
464 pub fn peek_usual(&mut self) -> Option<(&K, &V)> {
477 if self.len() == 0 {
478 return None;
479 }
480 unsafe {
481 let node = (*self.head).next;
482 Some((&*(*node).key.as_ptr(), &*(*node).val.as_ptr()))
483 }
484 }
485
486 pub fn peek_unusual(&mut self) -> Option<(&K, &V)> {
499 if self.len() == 0 {
500 return None;
501 }
502 unsafe {
503 let node = (*self.tail).prev;
504 Some((&*(*node).key.as_ptr(), &*(*node).val.as_ptr()))
505 }
506 }
507
508 pub fn contains_key<Q>(&mut self, k: &Q) -> bool
509 where
510 K: Borrow<Q>,
511 Q: Hash + Eq + ?Sized,
512 {
513 self.map.contains_key(KeyWrapper::from_ref(k))
514 }
515
516
517 pub fn raw_get<Q>(&self, k: &Q) -> Option<&V>
529 where
530 K: Borrow<Q>,
531 Q: Hash + Eq + ?Sized,
532 {
533 match self.map.get(KeyWrapper::from_ref(k)) {
534 Some(l) => {
535 let node = l.as_ptr();
536 unsafe { Some(&*(*node).val.as_ptr()) }
537 }
538 None => None,
539 }
540 }
541
542 pub fn get<Q>(&mut self, k: &Q) -> Option<&V>
554 where
555 K: Borrow<Q>,
556 Q: Hash + Eq + ?Sized,
557 {
558 self.get_key_value(k).map(|(_, v)| v)
559 }
560
561 pub fn get_key_value<Q>(&mut self, k: &Q) -> Option<(&K, &V)>
573 where
574 K: Borrow<Q>,
575 Q: Hash + Eq + ?Sized,
576 {
577 self.get_mut_key_value(k).map(|(k, v)| (k, &*v))
578 }
579
580 pub fn get_mut<Q>(&mut self, k: &Q) -> Option<&mut V>
593 where
594 K: Borrow<Q>,
595 Q: Hash + Eq + ?Sized,
596 {
597 self.get_mut_key_value(k).map(|(_, v)| v)
598 }
599
600
601 pub fn get_mut_key_value<Q>(&mut self, k: &Q) -> Option<(&K, &mut V)>
602 where
603 K: Borrow<Q>,
604 Q: Hash + Eq + ?Sized,
605 {
606 match self.get_node(k) {
607 Some(node) => {
608 unsafe { Some(( &*(*node).key.as_mut_ptr(), &mut *(*node).val.as_mut_ptr())) }
609 }
610 None => None,
611 }
612 }
613
614 pub(crate) fn get_node<Q>(&mut self, k: &Q) -> Option<*mut LruEntry<K, V>>
615 where
616 K: Borrow<Q>,
617 Q: Hash + Eq + ?Sized,
618 {
619 match self.map.get(KeyWrapper::from_ref(k)) {
620 Some(l) => {
621 let node = l.as_ptr();
622 self.detach(node);
623 #[cfg(feature = "ttl")]
624 unsafe {
625 if self.has_ttl && (*node).is_expire() {
626 self.map.remove(KeyWrapper::from_ref(k));
627 let _ = *Box::from_raw(node);
628 return None;
629 }
630 }
631
632 self.attach(node);
633 Some(node)
634 }
635 None => None,
636 }
637 }
638 #[inline(always)]
650 pub fn insert(&mut self, k: K, v: V) -> Option<V> {
651 self.capture_insert(k, v).map(|(_, v, _)| v)
652 }
653
654 #[cfg(feature="ttl")]
658 #[inline(always)]
659 pub fn insert_with_ttl(&mut self, k: K, v: V, ttl: u64) -> Option<V> {
660 self.capture_insert_with_ttl(k, v, ttl).map(|(_, v, _)| v)
661 }
662
663 #[inline(always)]
664 pub fn capture_insert(&mut self, k: K, v: V) -> Option<(K, V, bool)> {
665 self._capture_insert_with_ttl(k, v, u64::MAX)
666 }
667
668 #[cfg(feature = "ttl")]
669 #[inline(always)]
670 pub fn capture_insert_with_ttl(&mut self, k: K, v: V, ttl: u64) -> Option<(K, V, bool)> {
671 if ttl == 0 { return None };
672 self.has_ttl = true;
673 self._capture_insert_with_ttl(k, v, ttl)
674 }
675
676 #[allow(unused_variables)]
677 fn _capture_insert_with_ttl(&mut self, k: K, mut v: V, ttl: u64) -> Option<(K, V, bool)> {
678 #[cfg(feature="ttl")]
679 self.clear_expire();
680
681 let key = KeyRef::new(&k);
682 match self.map.get_mut(&key) {
683 Some(entry) => {
684 let entry_ptr = entry.as_ptr();
685 unsafe {
686 mem::swap(&mut *(*entry_ptr).val.as_mut_ptr(), &mut v);
687 }
688 #[cfg(feature="ttl")]
689 unsafe {
690 (*entry_ptr).expire = ttl.saturating_mul(1000).saturating_add(get_milltimestamp());
691 }
692 self.detach(entry_ptr);
693 self.attach(entry_ptr);
694
695 Some((k, v, true))
696 }
697 None => {
698 let (val, entry) = self.replace_or_create_node(k, v);
699 let entry_ptr = entry.as_ptr();
700 self.attach(entry_ptr);
701 #[cfg(feature="ttl")]
702 unsafe {
703 (*entry_ptr).expire = ttl.saturating_mul(1000).saturating_add(get_milltimestamp());
704 }
705 unsafe {
706 self.map
707 .insert(KeyRef::new((*entry_ptr).key.as_ptr()), entry);
708 }
709 val.map(|(k, v)| (k, v, false))
710 }
711 }
712 }
713
714 pub fn get_or_insert<F>(&mut self, k: K, f: F) -> &V
715 where
716 F: FnOnce() -> V, {
717 &*self.get_or_insert_mut(k, f)
718 }
719
720 pub fn get_or_insert_mut<'a, F>(&'a mut self, k: K, f: F) -> &mut V
721 where
722 F: FnOnce() -> V, {
723 if let Some(v) = self.get_node(&k) {
724 return unsafe {
725 &mut *(*v).val.as_mut_ptr()
726 };
727 } else {
728 let v = f();
729
730 let (_, node) = self.replace_or_create_node(k, v);
731 let node_ptr: *mut LruEntry<K, V> = node.as_ptr();
732
733 self.attach(node_ptr);
734
735 let keyref = unsafe { (*node_ptr).key.as_ptr() };
736 self.map.insert(KeyRef { k: keyref }, node);
737 unsafe { &mut *(*node_ptr).val.as_mut_ptr() }
738 }
739 }
740
741 #[cfg(feature="ttl")]
742 pub fn clear_expire(&mut self) {
743 if !self.has_ttl {
744 return;
745 }
746 let now = get_milltimestamp();
747 if now < self.check_next {
748 return;
749 }
750 self.check_next = now + self.check_step;
751 unsafe {
752 let mut ptr = self.tail;
753 while ptr != self.head {
754 if (*ptr).is_little(&now) {
755 let next = (*ptr).prev;
756 self.detach(ptr);
757 self.map.remove(&KeyRef::new(&*(*ptr).key.as_ptr()));
758 let _ = *Box::from_raw(ptr);
759 ptr = next;
760 } else {
761 ptr = (*ptr).prev;
762 }
763 }
764 }
765 }
766
767 #[cfg(feature="ttl")]
768 #[inline(always)]
769 pub fn del_ttl<Q>(&mut self, k: &Q)
770 where
771 K: Borrow<Q>,
772 Q: Hash + Eq + ?Sized, {
773 self.set_ttl(k, u64::MAX);
774 }
775
776 #[cfg(feature="ttl")]
777 pub fn set_ttl<Q>(&mut self, k: &Q, expire: u64) -> bool
778 where
779 K: Borrow<Q>,
780 Q: Hash + Eq + ?Sized, {
781 if let Some(v) = self.get_node(&k) {
782 self.has_ttl = true;
783 unsafe {
784 (*v).expire = get_milltimestamp().saturating_add(expire.saturating_mul(1000));
785 }
786 true
787 } else {
788 false
789 }
790 }
791
792 #[cfg(feature="ttl")]
793 pub fn get_ttl<Q>(&mut self, k: &Q) -> Option<u64>
794 where
795 K: Borrow<Q>,
796 Q: Hash + Eq + ?Sized, {
797 if let Some(v) = self.get_node(&k) {
798 unsafe {
799 Some((*v).get_ttl())
800 }
801 } else {
802 None
803 }
804 }
805
806 pub fn remove<Q>(&mut self, k: &Q) -> Option<(K, V)>
819 where
820 K: Borrow<Q>,
821 Q: Hash + Eq + ?Sized,
822 {
823 if let Some(node) = self.remove_node(k) {
824 unsafe {
825 Some((node.key.assume_init(), node.val.assume_init()))
826 }
827 } else {
828 None
829 }
830 }
831
832
833 #[cfg(feature="ttl")]
834 pub fn remove_with_ttl<Q>(&mut self, k: &Q) -> Option<(K, V, u64)>
835 where
836 K: Borrow<Q>,
837 Q: Hash + Eq + ?Sized,
838 {
839 if let Some(node) = self.remove_node(k) {
840 unsafe {
841 let ttl = node.get_ttl();
842 Some((node.key.assume_init(), node.val.assume_init(), ttl))
843 }
844 } else {
845 None
846 }
847 }
848
849 fn remove_node<Q>(&mut self, k: &Q) -> Option<LruEntry<K, V>>
850 where
851 K: Borrow<Q>,
852 Q: Hash + Eq + ?Sized,
853 {
854 match self.map.remove(KeyWrapper::from_ref(k)) {
855 Some(l) => unsafe {
856 self.detach(l.as_ptr());
857 let node = *Box::from_raw(l.as_ptr());
858 Some(node)
859 },
860 None => None,
861 }
862 }
863
864 fn replace_or_create_node(&mut self, k: K, v: V) -> (Option<(K, V)>, NonNull<LruEntry<K, V>>) {
865 if self.len() == self.cap {
866 let old_key = KeyRef {
867 k: unsafe { &(*(*(*self.tail).prev).key.as_ptr()) },
868 };
869 let old_node = self.map.remove(&old_key).unwrap();
870 let node_ptr: *mut LruEntry<K, V> = old_node.as_ptr();
871
872 let replaced = unsafe {
873 (
874 mem::replace(&mut (*node_ptr).key, mem::MaybeUninit::new(k)).assume_init(),
875 mem::replace(&mut (*node_ptr).val, mem::MaybeUninit::new(v)).assume_init(),
876 )
877 };
878
879 self.detach(node_ptr);
880
881 (Some(replaced), old_node)
882 } else {
883 (None, unsafe {
884 NonNull::new_unchecked(Box::into_raw(Box::new(LruEntry::new(k, v))))
885 })
886 }
887 }
888
889 pub fn retain<F>(&mut self, mut f: F)
904 where
905 F: FnMut(&K, &mut V) -> bool,
906 {
907 unsafe {
908 let mut node = (*self.head).next;
909 while node != self.tail {
910 if !f(&*(*node).key.as_ptr(), &mut *(*node).val.as_mut_ptr()) {
911 let next = (*node).next;
912 self.map.remove(&KeyRef { k: &*(*node).key.as_ptr() });
913 self.detach(node);
914 node = next;
915 } else {
916 node = (*node).next;
917 }
918 }
919 }
920 }
921}
922
923
924impl<K: Hash + Eq, V: Default, S: BuildHasher> LruCache<K, V, S> {
925 pub fn get_or_insert_default(&mut self, k: K) -> &V {
926 &*self.get_or_insert_mut(k, || V::default())
927 }
928
929 pub fn get_or_insert_default_mut(&mut self, k: K) -> &mut V {
930 self.get_or_insert_mut(k, || V::default())
931 }
932}
933
934impl<K: Clone + Hash + Eq, V: Clone, S: Clone + BuildHasher> Clone for LruCache<K, V, S> {
935 fn clone(&self) -> Self {
936 let mut new_lru = LruCache::with_hasher(self.cap, self.map.hasher().clone());
937
938 for (key, value) in self.iter().rev() {
939 new_lru.insert(key.clone(), value.clone());
940 }
941
942 new_lru
943 }
944}
945
946impl<K, V, S> Drop for LruCache<K, V, S> {
947 fn drop(&mut self) {
948 self.clear();
949
950 let _head = unsafe { *Box::from_raw(self.head) };
951 let _tail = unsafe { *Box::from_raw(self.tail) };
952 }
953}
954
955
956pub struct IntoIter<K: Hash + Eq, V, S: BuildHasher> {
958 base: LruCache<K, V, S>,
959}
960
961impl<K: Hash + Eq, V, S: BuildHasher> Drop for IntoIter<K, V, S> {
963 #[inline]
964 fn drop(&mut self) {
965 for (_, _) in self {}
966 }
967}
968
969impl<K: Hash + Eq, V, S: BuildHasher> Iterator for IntoIter<K, V, S> {
970 type Item = (K, V);
971
972 fn next(&mut self) -> Option<(K, V)> {
973 self.base.pop_usual()
974 }
975
976 fn size_hint(&self) -> (usize, Option<usize>) {
977 (self.base.len(), Some(self.base.len()))
978 }
979}
980
981impl<K: Hash + Eq, V, S: BuildHasher> IntoIterator for LruCache<K, V, S> {
982 type Item = (K, V);
983 type IntoIter = IntoIter<K, V, S>;
984
985 #[inline]
986 fn into_iter(self) -> IntoIter<K, V, S> {
987 IntoIter {
988 base: self
989 }
990 }
991}
992
993pub struct Iter<'a, K: 'a, V: 'a> {
994 len: usize,
995 ptr: *mut LruEntry<K, V>,
996 end: *mut LruEntry<K, V>,
997 phantom: PhantomData<&'a usize>,
998}
999
1000impl<'a, K, V> Iterator for Iter<'a, K, V> {
1001 type Item = (&'a K, &'a V);
1002
1003 fn next(&mut self) -> Option<Self::Item> {
1004 if self.len == 0 {
1005 return None;
1006 }
1007 unsafe {
1008 self.ptr = (*self.ptr).next;
1009 let node = self.ptr;
1010 self.len -= 1;
1011 Some((&*(*node).key.as_ptr(), &*(*node).val.as_ptr()))
1012 }
1013 }
1014
1015 fn size_hint(&self) -> (usize, Option<usize>) {
1016 (self.len, Some(self.len))
1017 }
1018}
1019
1020impl<'a, K, V> DoubleEndedIterator for Iter<'a, K, V> {
1021 fn next_back(&mut self) -> Option<Self::Item> {
1022 if self.len == 0 {
1023 return None;
1024 }
1025 unsafe {
1026 self.end = (*self.end).prev;
1027 let node = self.end;
1028 self.len -= 1;
1029 Some((&*(*node).key.as_ptr(), &*(*node).val.as_ptr()))
1030 }
1031 }
1032}
1033
1034
1035impl<K: Hash + Eq, V, S: BuildHasher> DoubleEndedIterator for IntoIter<K, V, S> {
1036 #[inline]
1037 fn next_back(&mut self) -> Option<(K, V)> {
1038 self.base.pop_unusual()
1039 }
1040}
1041
1042pub struct IterMut<'a, K: 'a, V: 'a> {
1043 len: usize,
1044 ptr: *mut LruEntry<K, V>,
1045 end: *mut LruEntry<K, V>,
1046 phantom: PhantomData<&'a usize>,
1047}
1048
1049impl<'a, K, V> Iterator for IterMut<'a, K, V> {
1050 type Item = (&'a K, &'a mut V);
1051
1052 fn next(&mut self) -> Option<Self::Item> {
1053 if self.len == 0 {
1054 return None;
1055 }
1056 unsafe {
1057 self.ptr = (*self.ptr).next;
1058 let node = self.ptr;
1059 self.len -= 1;
1060 Some((&*(*node).key.as_ptr(), &mut *(*node).val.as_mut_ptr()))
1061 }
1062 }
1063
1064
1065 fn size_hint(&self) -> (usize, Option<usize>) {
1066 (self.len, Some(self.len))
1067 }
1068}
1069
1070impl<'a, K, V> DoubleEndedIterator for IterMut<'a, K, V> {
1071 fn next_back(&mut self) -> Option<Self::Item> {
1072 if self.len == 0 {
1073 return None;
1074 }
1075 unsafe {
1076 self.end = (*self.end).prev;
1077 let node = self.end;
1078 self.len -= 1;
1079 Some((&*(*node).key.as_ptr(), &mut *(*node).val.as_mut_ptr()))
1080 }
1081 }
1082}
1083
1084pub struct Drain<'a, K: 'a + Hash + Eq, V: 'a, S: BuildHasher> {
1085 pub base: &'a mut LruCache<K, V, S>,
1086}
1087
1088impl<'a, K: Hash + Eq, V, S: BuildHasher> ExactSizeIterator for Drain<'a, K, V, S> {
1089 fn len(&self) -> usize {
1090 self.base.map.len()
1091 }
1092}
1093
1094impl<'a, K: Hash + Eq, V, S: BuildHasher> Iterator for Drain<'a, K, V, S> {
1095 type Item = (K, V);
1096
1097 fn next(&mut self) -> Option<Self::Item> {
1098 if self.base.len() == 0 {
1099 return None;
1100 }
1101 self.base.pop_unusual()
1102 }
1103}
1104
1105impl<'a, K: Hash + Eq, V, S: BuildHasher> Drop for Drain<'a, K, V, S> {
1106 fn drop(&mut self) {
1107 self.base.clear();
1108 }
1109}
1110
1111pub struct Keys<'a, K, V> {
1112 iter: Iter<'a, K, V>,
1113}
1114
1115impl<'a, K, V> Iterator for Keys<'a, K, V> {
1116 type Item = &'a K;
1117
1118 fn next(&mut self) -> Option<Self::Item> {
1119 self.iter.next().map(|(k, _)| k)
1120 }
1121
1122
1123 fn size_hint(&self) -> (usize, Option<usize>) {
1124 (self.iter.len, Some(self.iter.len))
1125 }
1126}
1127
1128pub struct Values<'a, K, V> {
1129 iter: Iter<'a, K, V>,
1130}
1131
1132impl<'a, K, V> Iterator for Values<'a, K, V> {
1133 type Item = &'a V;
1134
1135 fn next(&mut self) -> Option<Self::Item> {
1136 self.iter.next().map(|(_, v)| v)
1137 }
1138
1139 fn size_hint(&self) -> (usize, Option<usize>) {
1140 (self.iter.len, Some(self.iter.len))
1141 }
1142}
1143
1144
1145pub struct ValuesMut<'a, K, V> {
1146 iter: IterMut<'a, K, V>,
1147}
1148
1149impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
1150 type Item = &'a mut V;
1151
1152 fn next(&mut self) -> Option<Self::Item> {
1153 self.iter.next().map(|(_, v)| v)
1154 }
1155
1156 fn size_hint(&self) -> (usize, Option<usize>) {
1157 (self.iter.len, Some(self.iter.len))
1158 }
1159}
1160
1161
1162impl<K: Hash + Eq, V> FromIterator<(K, V)> for LruCache<K, V, DefaultHasher> {
1163 fn from_iter<T: IntoIterator<Item=(K, V)>>(iter: T) -> LruCache<K, V, DefaultHasher> {
1164 let mut lru = LruCache::new(2);
1165 lru.extend(iter);
1166 lru
1167 }
1168}
1169
1170impl<K: Hash + Eq, V> Extend<(K, V)> for LruCache<K, V, DefaultHasher> {
1171 fn extend<T: IntoIterator<Item=(K, V)>>(&mut self, iter: T) {
1172 let iter = iter.into_iter();
1173 for (k, v) in iter {
1174 self.reserve(1);
1175 self.insert(k, v);
1176 }
1177 }
1178}
1179
1180impl<K, V, S> PartialEq for LruCache<K, V, S>
1181 where
1182 K: Eq + Hash,
1183 V: PartialEq,
1184 S: BuildHasher
1185{
1186 fn eq(&self, other: &LruCache<K, V, S>) -> bool {
1187 if self.len() != other.len() {
1188 return false;
1189 }
1190
1191 self.iter()
1192 .all(|(key, value)| other.raw_get(key).map_or(false, |v| *value == *v))
1193 }
1194}
1195
1196impl<K, V, S> Eq for LruCache<K, V, S>
1197 where
1198 K: Eq + Hash,
1199 V: PartialEq,
1200 S: BuildHasher
1201{}
1202
1203impl<K, V, S> Debug for LruCache<K, V, S>
1204where
1205 K: Ord + Debug,
1206 V: Debug,
1207{
1208 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1209 f.debug_map().entries(self.iter()).finish()
1210 }
1211}
1212
1213
1214impl<'a, K, V, S> Index<&'a K> for LruCache<K, V, S>
1215where
1216 K: Hash+Eq,
1217 S: BuildHasher
1218{
1219 type Output = V;
1220
1221 #[inline]
1222 fn index(&self, index: &K) -> &V {
1223 self.raw_get(index).expect("no entry found for key")
1224 }
1225}
1226
1227
1228impl<'a, K, V, S> IndexMut<&'a K> for LruCache<K, V, S>
1229where
1230 K: Hash+Eq,
1231 S: BuildHasher
1232{
1233 #[inline]
1234 fn index_mut(&mut self, index: &K) -> &mut V {
1235 self.get_mut(index).expect("no entry found for key")
1236 }
1237}
1238
1239unsafe impl<K: Send, V: Send, S: Send> Send for LruCache<K, V, S> {}
1240unsafe impl<K: Sync, V: Sync, S: Sync> Sync for LruCache<K, V, S> {}
1241
1242
1243#[cfg(test)]
1244mod tests {
1245 use crate::DefaultHasher;
1246
1247 use super::LruCache;
1248
1249 #[test]
1250 fn test_insert() {
1251 let mut m = LruCache::new(2);
1252 assert_eq!(m.len(), 0);
1253 m.insert(1, 2);
1254 assert_eq!(m.len(), 1);
1255 m.insert(2, 4);
1256 assert_eq!(m.len(), 2);
1257 m.insert(3, 6);
1258 assert_eq!(m.len(), 2);
1259 assert_eq!(m.get(&1), None);
1260 assert_eq!(*m.get(&2).unwrap(), 4);
1261 assert_eq!(*m.get(&3).unwrap(), 6);
1262 }
1263
1264 #[test]
1265 fn test_replace() {
1266 let mut m = LruCache::new(2);
1267 assert_eq!(m.len(), 0);
1268 m.insert(2, 4);
1269 assert_eq!(m.len(), 1);
1270 m.insert(2, 6);
1271 assert_eq!(m.len(), 1);
1272 assert_eq!(*m.get(&2).unwrap(), 6);
1273 }
1274
1275 #[test]
1276 fn test_clone() {
1277 let mut m = LruCache::new(2);
1278 assert_eq!(m.len(), 0);
1279 m.insert(1, 2);
1280 assert_eq!(m.len(), 1);
1281 m.insert(2, 4);
1282 assert_eq!(m.len(), 2);
1283 let mut m2 = m.clone();
1284 m.clear();
1285 assert_eq!(*m2.get(&1).unwrap(), 2);
1286 assert_eq!(*m2.get(&2).unwrap(), 4);
1287 assert_eq!(m2.len(), 2);
1288 }
1289
1290 #[test]
1291 fn test_empty_remove() {
1292 let mut m: LruCache<isize, bool, DefaultHasher> = LruCache::new(2);
1293 assert_eq!(m.remove(&0), None);
1294 }
1295
1296 #[test]
1297 fn test_empty_iter() {
1298 let mut m: LruCache<isize, bool, DefaultHasher> = LruCache::new(2);
1299 assert_eq!(m.iter().next(), None);
1300 assert_eq!(m.iter_mut().next(), None);
1301 assert_eq!(m.len(), 0);
1302 assert!(m.is_empty());
1303 assert_eq!(m.into_iter().next(), None);
1304 }
1305
1306 #[test]
1307 fn test_lots_of_insertions() {
1308 let mut m = LruCache::new(1000);
1309
1310 for _ in 0..10 {
1313 assert!(m.is_empty());
1314
1315 for i in 1..101 {
1316 m.insert(i, i);
1317
1318 for j in 1..i + 1 {
1319 let r = m.get(&j);
1320 assert_eq!(r, Some(&j));
1321 }
1322
1323 for j in i + 1..101 {
1324 let r = m.get(&j);
1325 assert_eq!(r, None);
1326 }
1327 }
1328
1329 for i in 101..201 {
1330 assert!(!m.contains_key(&i));
1331 }
1332
1333 for i in 1..101 {
1335 assert!(m.remove(&i).is_some());
1336
1337 for j in 1..i + 1 {
1338 assert!(!m.contains_key(&j));
1339 }
1340
1341 for j in i + 1..101 {
1342 assert!(m.contains_key(&j));
1343 }
1344 }
1345
1346 for i in 1..101 {
1347 assert!(!m.contains_key(&i));
1348 }
1349
1350 for i in 1..101 {
1351 m.insert(i, i);
1352 }
1353
1354 for i in (1..101).rev() {
1356 assert!(m.remove(&i).is_some());
1357
1358 for j in i..101 {
1359 assert!(!m.contains_key(&j));
1360 }
1361
1362 for j in 1..i {
1363 assert!(m.contains_key(&j));
1364 }
1365 }
1366 }
1367 }
1368
1369 #[test]
1370 fn test_find_mut() {
1371 let mut m = LruCache::new(3);
1372 m.insert(1, 12);
1373 m.insert(2, 8);
1374 m.insert(5, 14);
1375 let new = 100;
1376 match m.get_mut(&5) {
1377 None => panic!(),
1378 Some(x) => *x = new,
1379 }
1380 assert_eq!(m.get(&5), Some(&new));
1381 }
1382
1383 #[test]
1384 fn test_remove() {
1385 let mut m = LruCache::new(3);
1386 m.insert(1, 2);
1387 assert_eq!(*m.get(&1).unwrap(), 2);
1388 m.insert(5, 3);
1389 assert_eq!(*m.get(&5).unwrap(), 3);
1390 m.insert(9, 4);
1391 assert_eq!(*m.get(&1).unwrap(), 2);
1392 assert_eq!(*m.get(&5).unwrap(), 3);
1393 assert_eq!(*m.get(&9).unwrap(), 4);
1394 assert_eq!(m.remove(&1).unwrap(), (1, 2));
1395 assert_eq!(m.remove(&5).unwrap(), (5, 3));
1396 assert_eq!(m.remove(&9).unwrap(), (9, 4));
1397 assert_eq!(m.len(), 0);
1398 }
1399
1400 #[test]
1401 fn test_is_empty() {
1402 let mut m = LruCache::new(2);
1403 m.insert(1, 2);
1404 assert!(!m.is_empty());
1405 assert!(m.remove(&1).is_some());
1406 assert!(m.is_empty());
1407 }
1408
1409 #[test]
1410 fn test_pop() {
1411 let mut m = LruCache::new(3);
1412 m.insert(3, 6);
1413 m.insert(2, 4);
1414 m.insert(1, 2);
1415 assert_eq!(m.len(), 3);
1416 assert_eq!(m.pop_usual(), Some((1, 2)));
1417 assert_eq!(m.len(), 2);
1418 assert_eq!(m.pop_unusual(), Some((3, 6)));
1419 assert_eq!(m.len(), 1);
1420 }
1421
1422 #[test]
1423 fn test_iterate() {
1424 let mut m = LruCache::new(32);
1425 for i in 0..32 {
1426 m.insert(i, i * 2);
1427 }
1428 assert_eq!(m.len(), 32);
1429
1430 let mut observed: u32 = 0;
1431
1432 for (k, v) in m.iter() {
1433 assert_eq!(*v, *k * 2);
1434 observed |= 1 << *k;
1435 }
1436 assert_eq!(observed, 0xFFFF_FFFF);
1437 }
1438
1439 #[test]
1440 fn test_keys() {
1441 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
1442 let map: LruCache<_, _, _> = vec.into_iter().collect();
1443 let keys: Vec<_> = map.keys().cloned().collect();
1444 assert_eq!(keys.len(), 3);
1445 assert!(keys.contains(&1));
1446 assert!(keys.contains(&2));
1447 assert!(keys.contains(&3));
1448 }
1449
1450 #[test]
1451 fn test_values() {
1452 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
1453 let map: LruCache<_, _, _> = vec.into_iter().collect();
1454 let values: Vec<_> = map.values().cloned().collect();
1455 assert_eq!(values.len(), 3);
1456 assert!(values.contains(&'a'));
1457 assert!(values.contains(&'b'));
1458 assert!(values.contains(&'c'));
1459 }
1460
1461 #[test]
1462 fn test_values_mut() {
1463 let vec = vec![(1, 1), (2, 2), (3, 3)];
1464 let mut map: LruCache<_, _, _> = vec.into_iter().collect();
1465 for value in map.values_mut() {
1466 *value = (*value) * 2
1467 }
1468 let values: Vec<_> = map.values().cloned().collect();
1469 assert_eq!(values.len(), 3);
1470 assert!(values.contains(&2));
1471 assert!(values.contains(&4));
1472 assert!(values.contains(&6));
1473 }
1474
1475 #[test]
1476 fn test_find() {
1477 let mut m = LruCache::new(2);
1478 assert!(m.get(&1).is_none());
1479 m.insert(1, 2);
1480 match m.get(&1) {
1481 None => panic!(),
1482 Some(v) => assert_eq!(*v, 2),
1483 }
1484 }
1485
1486 #[test]
1487 fn test_eq() {
1488 let mut m1 = LruCache::new(3);
1489 m1.insert(1, 2);
1490 m1.insert(2, 3);
1491 m1.insert(3, 4);
1492
1493 let mut m2 = LruCache::new(3);
1494 m2.insert(1, 2);
1495 m2.insert(2, 3);
1496
1497 assert!(m1 != m2);
1498
1499 m2.insert(3, 4);
1500
1501 assert_eq!(m1, m2);
1502 }
1503
1504 #[test]
1505 fn test_from_iter() {
1506 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
1507
1508 let map: LruCache<_, _, _> = xs.iter().cloned().collect();
1509
1510 for &(k, v) in &xs {
1511 assert_eq!(map.raw_get(&k), Some(&v));
1512 }
1513 }
1514
1515 #[test]
1516 fn test_size_hint() {
1517 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
1518
1519 let map: LruCache<_, _, _> = xs.iter().cloned().collect();
1520
1521 let mut iter = map.iter();
1522
1523 for _ in iter.by_ref().take(3) {}
1524
1525 assert_eq!(iter.size_hint(), (3, Some(3)));
1526 }
1527
1528 #[test]
1529 fn test_iter_len() {
1530 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
1531
1532 let map: LruCache<_, _, _> = xs.iter().cloned().collect();
1533
1534 let mut iter = map.iter();
1535
1536 for _ in iter.by_ref().take(3) {}
1537
1538 assert_eq!(iter.count(), 3);
1539 }
1540
1541 #[test]
1542 fn test_mut_size_hint() {
1543 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
1544
1545 let mut map: LruCache<_, _, _> = xs.iter().cloned().collect();
1546
1547 let mut iter = map.iter_mut();
1548
1549 for _ in iter.by_ref().take(3) {}
1550
1551 assert_eq!(iter.size_hint(), (3, Some(3)));
1552 }
1553
1554 #[test]
1555 fn test_iter_mut_len() {
1556 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
1557
1558 let mut map: LruCache<_, _, _> = xs.iter().cloned().collect();
1559
1560 let mut iter = map.iter_mut();
1561
1562 for _ in iter.by_ref().take(3) {}
1563
1564 assert_eq!(iter.count(), 3);
1565 }
1566
1567 #[test]
1568 fn test_index() {
1569 let mut map = LruCache::new(2);
1570
1571 map.insert(1, 2);
1572 map.insert(2, 1);
1573 map.insert(3, 4);
1574
1575 assert_eq!(map[&2], 1);
1576 }
1577
1578 #[test]
1579 #[should_panic]
1580 fn test_index_nonexistent() {
1581 let mut map = LruCache::new(2);
1582
1583 map.insert(1, 2);
1584 map.insert(2, 1);
1585 map.insert(3, 4);
1586
1587 map[&4];
1588 }
1589
1590 #[test]
1591 fn test_extend_iter() {
1592 let mut a = LruCache::new(2);
1593 a.insert(1, "one");
1594 let mut b = LruCache::new(2);
1595 b.insert(2, "two");
1596 b.insert(3, "three");
1597
1598 a.extend(b.into_iter());
1599
1600 assert_eq!(a.len(), 3);
1601 assert_eq!(a[&1], "one");
1602 assert_eq!(a[&2], "two");
1603 assert_eq!(a[&3], "three");
1604 }
1605
1606 #[test]
1607 fn test_drain() {
1608 let mut a = LruCache::new(3);
1609 a.insert(1, 1);
1610 a.insert(2, 2);
1611 a.insert(3, 3);
1612
1613 assert_eq!(a.len(), 3);
1614 {
1615 let mut drain = a.drain();
1616 assert_eq!(drain.next().unwrap(), (1, 1));
1617 assert_eq!(drain.next().unwrap(), (2, 2));
1618 }
1619 assert_eq!(a.len(), 0);
1620 }
1621
1622
1623 #[test]
1624 fn test_send() {
1625 use std::thread;
1626
1627 let mut cache = LruCache::new(4);
1628 cache.insert(1, "a");
1629
1630 let handle = thread::spawn(move || {
1631 assert_eq!(cache.get(&1), Some(&"a"));
1632 });
1633
1634 assert!(handle.join().is_ok());
1635 }
1636
1637 #[test]
1638 #[cfg(feature="ttl")]
1639 fn test_ttl_cache() {
1640 let mut lru = LruCache::new(3);
1641 lru.insert_with_ttl("help", "ok", 1);
1642 lru.insert_with_ttl("author", "tickbh", 2);
1643 assert_eq!(lru.len(), 2);
1644 std::thread::sleep(std::time::Duration::from_secs(1));
1645 assert_eq!(lru.get("help"), None);
1646 std::thread::sleep(std::time::Duration::from_secs(1));
1647 assert_eq!(lru.get("author"), None);
1648 assert_eq!(lru.len(), 0);
1649 }
1650
1651 #[test]
1652 #[cfg(feature="ttl")]
1653 fn test_ttl_check_cache() {
1654 let mut lru = LruCache::new(3);
1655 lru.set_check_step(1);
1656 lru.insert_with_ttl("help", "ok", 1);
1657 lru.insert("now", "algorithm");
1658 assert_eq!(lru.len(), 2);
1659 std::thread::sleep(std::time::Duration::from_secs(1));
1660 assert_eq!(lru.len(), 2);
1661 lru.insert_with_ttl("author", "tickbh", 3);
1662 assert_eq!(lru.len(), 2);
1663 assert_eq!(lru.get("help"), None);
1664 assert_eq!(lru.len(), 2);
1665 }
1666
1667 #[test]
1668 #[cfg(feature="ttl")]
1669 fn test_ttl_del() {
1670 let mut lru = LruCache::new(3);
1671 lru.insert_with_ttl("help", "ok", 1);
1672 lru.insert_with_ttl("author", "tickbh", 2);
1673 assert_eq!(lru.len(), 2);
1674 std::thread::sleep(std::time::Duration::from_secs(1));
1675 assert_eq!(lru.get("help"), None);
1676 lru.del_ttl(&"author");
1677 std::thread::sleep(std::time::Duration::from_secs(1));
1678 assert_eq!(lru.get("author"), Some(&"tickbh"));
1679 assert_eq!(lru.len(), 1);
1680 }
1681
1682 #[test]
1683 #[cfg(feature="ttl")]
1684 fn test_ttl_set() {
1685 let mut lru = LruCache::new(3);
1686 lru.insert_with_ttl("help", "ok", 1);
1687 lru.insert_with_ttl("author", "tickbh", 2);
1688 lru.set_ttl(&"help", 3);
1689 assert_eq!(lru.len(), 2);
1690 std::thread::sleep(std::time::Duration::from_secs(1));
1691 assert_eq!(lru.get("help"), Some(&"ok"));
1692 std::thread::sleep(std::time::Duration::from_secs(1));
1693 assert_eq!(lru.get("author"), None);
1694 std::thread::sleep(std::time::Duration::from_secs(1));
1695 assert_eq!(lru.get("help"), None);
1696 assert_eq!(lru.len(), 0);
1697 }
1698
1699
1700 #[test]
1701 #[cfg(feature="ttl")]
1702 fn test_ttl_get() {
1703 let mut lru = LruCache::new(3);
1704 lru.insert_with_ttl("help", "ok", 1);
1705 lru.insert_with_ttl("author", "tickbh", 2);
1706 lru.insert("now", "algorithm");
1707 assert!(lru.get_ttl(&"help").unwrap() <= 1);
1708 assert!(lru.get_ttl(&"author").unwrap() <= 2);
1709 assert_eq!(lru.get_ttl(&"now"), Some(u64::MAX));
1710 }
1711}