timed-map 1.7.0

Lightweight map implementation that supports expiring entries and fully compatible with both std and no_std environments.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
use super::*;

use crate::iter::{GenericMapIntoIter, GenericMapIter, GenericMapIterMut, IntoIter, Iter, IterMut};

macro_rules! cfg_std_feature {
    ($($item:item)*) => {
        $(
            #[cfg(feature = "std")]
            $item
        )*
    };
}

macro_rules! cfg_not_std_feature {
    ($($item:item)*) => {
        $(
            #[cfg(not(feature = "std"))]
            $item
        )*
    };
}

cfg_not_std_feature! {
    /// Generic trait for `no_std` keys that is gated by the `std` feature
    /// and handled at compile time.
    pub trait GenericKey: Clone + Eq + Ord {}
    impl<T: Clone + Eq + Ord> GenericKey for T {}
}

cfg_std_feature! {
    /// Generic trait for `std` keys that is gated by the `std` feature
    /// and handled at compile time.
    pub trait GenericKey: Clone + Eq + Ord + Hash {}
    impl<T: Clone + Eq + Ord + Hash> GenericKey for T {}
}

/// Wraps different map implementations and provides a single interface to access them.
///
/// TODO: Consider removing this type, instead, define a trait and update the internals
/// of [`TimedMap`] to work with a generic value that implements this trait. This would
/// allow users to implement the trait for their own custom map types, which means any
/// map implementation can be supported from this library without needing to touch the
/// library internals.
#[allow(clippy::enum_variant_names)]
#[derive(Clone, Debug)]
enum GenericMap<K, V> {
    BTreeMap(BTreeMap<K, V>),
    #[cfg(feature = "std")]
    HashMap(HashMap<K, V>),
    #[cfg(all(feature = "std", feature = "rustc-hash"))]
    FxHashMap(FxHashMap<K, V>),
}

impl<K, V> Default for GenericMap<K, V> {
    fn default() -> Self {
        Self::BTreeMap(BTreeMap::default())
    }
}

impl<K, V> GenericMap<K, V>
where
    K: GenericKey,
{
    #[inline(always)]
    fn get(&self, k: &K) -> Option<&V> {
        match self {
            Self::BTreeMap(inner) => inner.get(k),
            #[cfg(feature = "std")]
            Self::HashMap(inner) => inner.get(k),
            #[cfg(all(feature = "std", feature = "rustc-hash"))]
            Self::FxHashMap(inner) => inner.get(k),
        }
    }

    #[inline(always)]
    fn get_mut(&mut self, k: &K) -> Option<&mut V> {
        match self {
            Self::BTreeMap(inner) => inner.get_mut(k),
            #[cfg(feature = "std")]
            Self::HashMap(inner) => inner.get_mut(k),
            #[cfg(all(feature = "std", feature = "rustc-hash"))]
            Self::FxHashMap(inner) => inner.get_mut(k),
        }
    }

    #[inline(always)]
    fn len(&self) -> usize {
        match self {
            Self::BTreeMap(inner) => inner.len(),
            #[cfg(feature = "std")]
            Self::HashMap(inner) => inner.len(),
            #[cfg(all(feature = "std", feature = "rustc-hash"))]
            Self::FxHashMap(inner) => inner.len(),
        }
    }

    #[inline(always)]
    fn keys(&self) -> Vec<K> {
        match self {
            Self::BTreeMap(inner) => inner.keys().cloned().collect(),
            #[cfg(feature = "std")]
            Self::HashMap(inner) => inner.keys().cloned().collect(),
            #[cfg(all(feature = "std", feature = "rustc-hash"))]
            Self::FxHashMap(inner) => inner.keys().cloned().collect(),
        }
    }

    #[inline(always)]
    fn is_empty(&self) -> bool {
        match self {
            Self::BTreeMap(inner) => inner.is_empty(),
            #[cfg(feature = "std")]
            Self::HashMap(inner) => inner.is_empty(),
            #[cfg(all(feature = "std", feature = "rustc-hash"))]
            Self::FxHashMap(inner) => inner.is_empty(),
        }
    }

    #[inline(always)]
    fn insert(&mut self, k: K, v: V) -> Option<V> {
        match self {
            Self::BTreeMap(inner) => inner.insert(k, v),
            #[cfg(feature = "std")]
            Self::HashMap(inner) => inner.insert(k, v),
            #[cfg(all(feature = "std", feature = "rustc-hash"))]
            Self::FxHashMap(inner) => inner.insert(k, v),
        }
    }

    #[inline(always)]
    fn clear(&mut self) {
        match self {
            Self::BTreeMap(inner) => inner.clear(),
            #[cfg(feature = "std")]
            Self::HashMap(inner) => inner.clear(),
            #[cfg(all(feature = "std", feature = "rustc-hash"))]
            Self::FxHashMap(inner) => inner.clear(),
        }
    }

    #[inline(always)]
    fn remove(&mut self, k: &K) -> Option<V> {
        match self {
            Self::BTreeMap(inner) => inner.remove(k),
            #[cfg(feature = "std")]
            Self::HashMap(inner) => inner.remove(k),
            #[cfg(all(feature = "std", feature = "rustc-hash"))]
            Self::FxHashMap(inner) => inner.remove(k),
        }
    }

    fn iter(&self) -> GenericMapIter<'_, K, V> {
        match self {
            Self::BTreeMap(inner) => GenericMapIter::BTreeMap(inner.iter()),
            #[cfg(feature = "std")]
            Self::HashMap(inner) => GenericMapIter::HashMap(inner.iter()),
            #[cfg(all(feature = "std", feature = "rustc-hash"))]
            Self::FxHashMap(inner) => GenericMapIter::FxHashMap(inner.iter()),
        }
    }

    fn into_iter(self) -> GenericMapIntoIter<K, V> {
        match self {
            Self::BTreeMap(inner) => GenericMapIntoIter::BTreeMap(inner.into_iter()),
            #[cfg(feature = "std")]
            Self::HashMap(inner) => GenericMapIntoIter::HashMap(inner.into_iter()),
            #[cfg(all(feature = "std", feature = "rustc-hash"))]
            Self::FxHashMap(inner) => GenericMapIntoIter::FxHashMap(inner.into_iter()),
        }
    }

    fn iter_mut(&mut self) -> GenericMapIterMut<'_, K, V> {
        match self {
            Self::BTreeMap(inner) => GenericMapIterMut::BTreeMap(inner.iter_mut()),
            #[cfg(feature = "std")]
            Self::HashMap(inner) => GenericMapIterMut::HashMap(inner.iter_mut()),
            #[cfg(all(feature = "std", feature = "rustc-hash"))]
            Self::FxHashMap(inner) => GenericMapIterMut::FxHashMap(inner.iter_mut()),
        }
    }
}

/// Specifies the inner map implementation for `TimedMap`.
#[cfg(feature = "std")]
#[allow(clippy::enum_variant_names)]
pub enum MapKind {
    BTreeMap,
    HashMap,
    #[cfg(feature = "rustc-hash")]
    FxHashMap,
}

/// Associates keys of type `K` with values of type `V`. Each entry may optionally expire after a
/// specified duration.
///
/// Mutable functions automatically clears expired entries when called.
///
/// If no expiration is set, the entry remains constant.
#[derive(Clone, Debug)]
pub struct TimedMap<K, V, #[cfg(feature = "std")] C = StdClock, #[cfg(not(feature = "std"))] C> {
    clock: C,

    map: GenericMap<K, ExpirableEntry<V>>,
    expiries: BTreeMap<u64, BTreeSet<K>>,

    expiration_tick: u16,
    expiration_tick_cap: u16,
}

#[cfg(feature = "serde")]
impl<K: serde::Serialize + Ord, V: serde::Serialize, C: Clock> serde::Serialize
    for TimedMap<K, V, C>
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let now = self.clock.elapsed_seconds_since_creation();
        match &self.map {
            GenericMap::BTreeMap(inner) => {
                let map = inner.iter().filter(|(_k, v)| !v.is_expired(now));
                serializer.collect_map(map)
            }
            #[cfg(feature = "std")]
            GenericMap::HashMap(inner) => {
                let map = inner.iter().filter(|(_k, v)| !v.is_expired(now));
                serializer.collect_map(map)
            }
            #[cfg(all(feature = "std", feature = "rustc-hash"))]
            GenericMap::FxHashMap(inner) => {
                let map = inner.iter().filter(|(_k, v)| !v.is_expired(now));
                serializer.collect_map(map)
            }
        }
    }
}

impl<'a, K, V, C> IntoIterator for &'a TimedMap<K, V, C>
where
    K: GenericKey,
    C: Clock,
{
    type Item = (&'a K, &'a V);
    type IntoIter = Iter<'a, K, V>;

    fn into_iter(self) -> Self::IntoIter {
        let now = self.clock.elapsed_seconds_since_creation();
        Iter {
            inner: self.map.iter(),
            now,
        }
    }
}

impl<'a, K, V, C> IntoIterator for &'a mut TimedMap<K, V, C>
where
    K: GenericKey,
    C: Clock,
{
    type Item = (&'a K, &'a mut V);
    type IntoIter = IterMut<'a, K, V>;

    fn into_iter(self) -> Self::IntoIter {
        let now = self.clock.elapsed_seconds_since_creation();
        IterMut {
            inner: self.map.iter_mut(),
            now,
        }
    }
}

impl<K, V, C> IntoIterator for TimedMap<K, V, C>
where
    K: GenericKey,
    C: Clock,
{
    type Item = (K, V);
    type IntoIter = IntoIter<K, V>;

    fn into_iter(self) -> Self::IntoIter {
        let now = self.clock.elapsed_seconds_since_creation();
        IntoIter {
            inner: self.map.into_iter(),
            now,
        }
    }
}

impl<K, V, C> Default for TimedMap<K, V, C>
where
    C: Default,
{
    fn default() -> Self {
        Self {
            clock: Default::default(),

            map: GenericMap::default(),
            expiries: BTreeMap::default(),

            expiration_tick: 0,
            expiration_tick_cap: 1,
        }
    }
}

#[cfg(feature = "std")]
impl<K, V> TimedMap<K, V, StdClock>
where
    K: GenericKey,
{
    /// Creates an empty map.
    pub fn new() -> Self {
        Self::default()
    }

    /// Creates an empty map based on the chosen map implementation specified by `MapKind`.
    pub fn new_with_map_kind(map_kind: MapKind) -> Self {
        let map = match map_kind {
            MapKind::BTreeMap => GenericMap::<K, ExpirableEntry<V>>::BTreeMap(BTreeMap::default()),
            MapKind::HashMap => GenericMap::HashMap(HashMap::default()),
            #[cfg(feature = "rustc-hash")]
            MapKind::FxHashMap => GenericMap::FxHashMap(FxHashMap::default()),
        };

        Self {
            map,

            clock: StdClock::default(),
            expiries: BTreeMap::default(),

            expiration_tick: 0,
            expiration_tick_cap: 1,
        }
    }
}

impl<K, V, C> TimedMap<K, V, C>
where
    C: Clock,
    K: GenericKey,
{
    /// Creates an empty `TimedMap`.
    ///
    /// Uses the provided `clock` to handle expiration times.
    #[cfg(not(feature = "std"))]
    pub fn new(clock: C) -> Self {
        Self {
            clock,
            map: GenericMap::default(),
            expiries: BTreeMap::default(),
            expiration_tick: 0,
            expiration_tick_cap: 1,
        }
    }

    /// Configures `expiration_tick_cap`, which sets how often `TimedMap::drop_expired_entries`
    /// is automatically called. The default value is 1.
    ///
    /// On each insert (excluding `unchecked` ones), an internal counter `expiration_tick` is incremented.
    /// When `expiration_tick` meets or exceeds `expiration_tick_cap`, `TimedMap::drop_expired_entries` is
    /// triggered to remove expired entries.
    ///
    /// Use this to control cleanup frequency and optimize performance. For example, if your workload
    /// involves about 100 inserts within couple seconds, setting `expiration_tick_cap` to 100 can improve
    /// the performance significantly.
    #[inline(always)]
    pub fn expiration_tick_cap(mut self, expiration_tick_cap: u16) -> Self {
        self.expiration_tick_cap = expiration_tick_cap;
        self
    }

    /// Returns the associated value if present and not expired.
    ///
    /// To retrieve the value without checking expiration, use `TimedMap::get_unchecked`.
    pub fn get(&self, k: &K) -> Option<&V> {
        self.map
            .get(k)
            .filter(|v| !v.is_expired(self.clock.elapsed_seconds_since_creation()))
            .map(|v| v.value())
    }

    /// Returns a mutable reference to the value corresponding to the key.
    ///
    /// To retrieve the value without checking expiration, use `TimedMap::get_mut_unchecked`.
    pub fn get_mut(&mut self, k: &K) -> Option<&mut V> {
        self.map
            .get_mut(k)
            .filter(|v| !v.is_expired(self.clock.elapsed_seconds_since_creation()))
            .map(|v| v.value_mut())
    }

    /// Returns the associated value if present, regardless of whether it is expired.
    ///
    /// If you only want non-expired entries, use `TimedMap::get` instead.
    #[inline(always)]
    pub fn get_unchecked(&self, k: &K) -> Option<&V> {
        self.map.get(k).map(|v| v.value())
    }

    /// Returns a mutable reference to the associated value if present, regardless of
    /// whether it is expired.
    ///
    /// If you only want non-expired entries, use `TimedMap::get_mut` instead.
    #[inline(always)]
    pub fn get_mut_unchecked(&mut self, k: &K) -> Option<&mut V> {
        self.map.get_mut(k).map(|v| v.value_mut())
    }

    /// Returns the associated value's `Duration` if present and not expired.
    ///
    /// Returns `None` if the entry does not exist or is constant.
    pub fn get_remaining_duration(&self, k: &K) -> Option<Duration> {
        match self.map.get(k) {
            Some(v) => {
                let now = self.clock.elapsed_seconds_since_creation();
                if v.is_expired(now) {
                    return None;
                }

                v.remaining_duration(now)
            }
            None => None,
        }
    }

    /// Returns the number of unexpired elements in the map.
    ///
    /// See `TimedMap::len_expired` and `TimedMap::len_unchecked` for other usages.
    #[inline(always)]
    pub fn len(&self) -> usize {
        self.map.len() - self.len_expired()
    }

    /// Returns the number of expired elements in the map.
    ///
    /// See `TimedMap::len` and `TimedMap::len_unchecked` for other usages.
    #[inline(always)]
    pub fn len_expired(&self) -> usize {
        let now = self.clock.elapsed_seconds_since_creation();
        self.expiries
            .range(..=now)
            .map(|(_exp, keys)| keys.len())
            .sum()
    }

    /// Returns the total number of elements (including expired ones) in the map.
    ///
    /// See `TimedMap::len` and `TimedMap::len_expired` for other usages.
    #[inline(always)]
    pub fn len_unchecked(&self) -> usize {
        self.map.len()
    }

    /// Returns keys for non-expired entries.
    ///
    /// To include expired entries as well, use [`TimedMap::keys_unchecked`].
    #[inline(always)]
    pub fn keys(&self) -> Vec<K> {
        let now = self.clock.elapsed_seconds_since_creation();
        self.map
            .iter()
            .filter(|(_k, v)| !v.is_expired(now))
            .map(|(k, _v)| k.clone())
            .collect()
    }

    /// Returns keys for expired entries.
    #[inline(always)]
    pub fn keys_expired(&self) -> Vec<K> {
        let now = self.clock.elapsed_seconds_since_creation();
        self.map
            .iter()
            .filter(|(_k, v)| v.is_expired(now))
            .map(|(k, _v)| k.clone())
            .collect()
    }

    /// Returns keys for all entries, including expired ones.
    ///
    /// To exclude expired entries, use [`TimedMap::keys`] instead.
    #[inline(always)]
    pub fn keys_unchecked(&self) -> Vec<K> {
        self.map.keys()
    }

    /// Returns true if the map contains no non-expired elements.
    ///
    /// To include expired entries as well, use [`TimedMap::is_empty_unchecked`].
    #[inline(always)]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Returns true if the map contains no elements, regardless of expiration status.
    ///
    /// To exclude expired entries, use [`TimedMap::is_empty`] instead.
    #[inline(always)]
    pub fn is_empty_unchecked(&self) -> bool {
        self.map.is_empty()
    }

    /// Inserts a key-value pair with an expiration duration. If duration is `None`,
    /// entry will be stored in a non-expirable way.
    ///
    /// If a value already exists for the given key, it will be updated and then
    /// the old one will be returned.
    #[inline(always)]
    fn insert(&mut self, k: K, v: V, expires_at: Option<u64>) -> Option<V> {
        let entry = ExpirableEntry::new(v, expires_at);
        match self.map.insert(k.clone(), entry) {
            Some(old) => {
                // Remove the old expiry record
                if let EntryStatus::ExpiresAtSeconds(e) = old.status() {
                    self.drop_key_from_expiry(e, &k)
                }

                Some(old.owned_value())
            }
            None => None,
        }
    }

    /// Inserts a key-value pair with an expiration duration, and then drops the
    /// expired entries.
    ///
    /// If a value already exists for the given key, it will be updated and then
    /// the old one will be returned.
    ///
    /// If you don't want to the check expired entries, consider using `TimedMap::insert_expirable_unchecked`
    /// instead.
    pub fn insert_expirable(&mut self, k: K, v: V, duration: Duration) -> Option<V> {
        self.expiration_tick += 1;

        let now = self.clock.elapsed_seconds_since_creation();
        if self.expiration_tick >= self.expiration_tick_cap {
            self.drop_expired_entries_inner(now);
            self.expiration_tick = 0;
        }

        let expires_at = now + duration.as_secs();

        let res = self.insert(k.clone(), v, Some(expires_at));

        self.expiries.entry(expires_at).or_default().insert(k);

        res
    }

    /// Inserts a key-value pair with an expiration duration, without checking the expired
    /// entries.
    ///
    /// If a value already exists for the given key, it will be updated and then
    /// the old one will be returned.
    ///
    /// If you want to check the expired entries, consider using `TimedMap::insert_expirable`
    /// instead.
    pub fn insert_expirable_unchecked(&mut self, k: K, v: V, duration: Duration) -> Option<V> {
        let now = self.clock.elapsed_seconds_since_creation();
        let expires_at = now + duration.as_secs();

        let res = self.insert(k.clone(), v, Some(expires_at));

        self.expiries.entry(expires_at).or_default().insert(k);

        res
    }

    /// Inserts a key-value pair with that doesn't expire, and then drops the
    /// expired entries.
    ///
    /// If a value already exists for the given key, it will be updated and then
    /// the old one will be returned.
    ///
    /// If you don't want to check the expired entries, consider using `TimedMap::insert_constant_unchecked`
    /// instead.
    pub fn insert_constant(&mut self, k: K, v: V) -> Option<V> {
        self.expiration_tick += 1;

        let now = self.clock.elapsed_seconds_since_creation();
        if self.expiration_tick >= self.expiration_tick_cap {
            self.drop_expired_entries_inner(now);
            self.expiration_tick = 0;
        }

        self.insert(k, v, None)
    }

    /// Inserts a key-value pair with that doesn't expire without checking the expired
    /// entries.
    ///
    /// If a value already exists for the given key, it will be updated and then
    /// the old one will be returned.
    ///
    /// If you want to check the expired entries, consider using `TimedMap::insert_constant`
    /// instead.
    pub fn insert_constant_unchecked(&mut self, k: K, v: V) -> Option<V> {
        self.expiration_tick += 1;
        self.insert(k, v, None)
    }

    /// Removes a key-value pair from the map and returns the associated value if present
    /// and not expired.
    ///
    /// If you want to retrieve the entry after removal even if it is expired, consider using
    /// `TimedMap::remove_unchecked`.
    #[inline(always)]
    pub fn remove(&mut self, k: &K) -> Option<V> {
        self.map
            .remove(k)
            .filter(|v| {
                if let EntryStatus::ExpiresAtSeconds(expires_at_seconds) = v.status() {
                    self.drop_key_from_expiry(expires_at_seconds, k);
                }

                !v.is_expired(self.clock.elapsed_seconds_since_creation())
            })
            .map(|v| v.owned_value())
    }

    /// Removes a key-value pair from the map and returns the associated value if present,
    /// regardless of expiration status.
    ///
    /// If you only want the entry when it is not expired, consider using `TimedMap::remove`.
    #[inline(always)]
    pub fn remove_unchecked(&mut self, k: &K) -> Option<V> {
        self.map
            .remove(k)
            .filter(|v| {
                if let EntryStatus::ExpiresAtSeconds(expires_at_seconds) = v.status() {
                    self.drop_key_from_expiry(expires_at_seconds, k);
                }

                true
            })
            .map(|v| v.owned_value())
    }

    /// Clears the map, removing all elements.
    #[inline(always)]
    pub fn clear(&mut self) {
        self.map.clear();
        self.expiries.clear();
    }

    /// Returns an iterator over non-expired key-value pairs.
    pub fn iter(&self) -> Iter<'_, K, V> {
        self.into_iter()
    }

    /// Returns an iterator over all key-value pairs, including expired ones.
    pub fn iter_unchecked(&self) -> impl Iterator<Item = (&K, &V)> {
        self.map.iter().map(|(k, v)| (k, v.value()))
    }

    /// Returns a mutable iterator over non-expired key-value pairs.
    pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
        self.into_iter()
    }

    /// Returns a mutable iterator over all key-value pairs, including expired ones.
    pub fn iter_mut_unchecked(&mut self) -> impl Iterator<Item = (&K, &mut V)> {
        self.map.iter_mut().map(|(k, v)| (k, v.value_mut()))
    }

    /// Updates the expiration status of an entry and returns the old expirable status.
    ///
    /// If the entry does not exist, returns Err.
    /// If the entry's old status is `EntryStatus::Constant`, returns None.
    pub fn update_expiration_status(
        &mut self,
        key: K,
        duration: Duration,
    ) -> Result<Option<EntryStatus>, &'static str> {
        match self.map.get_mut(&key) {
            Some(entry) => {
                let old_status = *entry.status();
                let now = self.clock.elapsed_seconds_since_creation();
                let expires_at = now + duration.as_secs();

                entry.update_status(EntryStatus::ExpiresAtSeconds(expires_at));

                if let EntryStatus::ExpiresAtSeconds(t) = &old_status {
                    self.drop_key_from_expiry(t, &key);
                }
                self.expiries
                    .entry(expires_at)
                    .or_default()
                    .insert(key.clone());

                match old_status {
                    EntryStatus::Constant => Ok(None),
                    EntryStatus::ExpiresAtSeconds(_) => Ok(Some(old_status)),
                }
            }
            None => Err("entry not found"),
        }
    }

    /// Clears expired entries from the map and returns them.
    ///
    /// Call this function when using `*_unchecked` inserts, as these do not
    /// automatically clear expired entries.
    #[inline(always)]
    pub fn drop_expired_entries(&mut self) -> Vec<(K, V)> {
        let now = self.clock.elapsed_seconds_since_creation();
        self.drop_expired_entries_inner(now)
    }

    fn drop_expired_entries_inner(&mut self, now: u64) -> Vec<(K, V)> {
        let mut expired_entries = Vec::new();
        // Iterates through `expiries` in order and drops expired ones.
        while let Some((exp, keys)) = self.expiries.pop_first() {
            // It's safe to do early-break here as keys are sorted by expiration.
            if exp > now {
                self.expiries.insert(exp, keys);
                break;
            }

            for key in keys {
                if let Some(value) = self.map.remove(&key) {
                    expired_entries.push((key, value.owned_value()));
                }
            }
        }

        expired_entries
    }

    fn drop_key_from_expiry(&mut self, expiry_key: &u64, map_key: &K) {
        if let Some(list) = self.expiries.get_mut(expiry_key) {
            list.remove(map_key);

            if list.is_empty() {
                self.expiries.remove(expiry_key);
            }
        }
    }

    /// Returns `true` if the map contains a non-expired value for the given key.
    ///
    /// To include expired entries as well, use [`TimedMap::contains_key_unchecked`].
    #[inline(always)]
    pub fn contains_key(&self, k: &K) -> bool {
        self.get(k).is_some()
    }

    /// Returns `true` if the map contains a value for the given key regardless of expiration status.
    ///
    /// To exclude expired entries, use [`TimedMap::contains_key`] instead.
    #[inline(always)]
    pub fn contains_key_unchecked(&self, k: &K) -> bool {
        self.get_unchecked(k).is_some()
    }
}

#[cfg(test)]
#[cfg(not(feature = "std"))]
mod tests {
    use super::*;

    #[derive(Clone, Copy)]
    struct MockClock {
        current_time: u64,
    }

    impl Clock for MockClock {
        fn elapsed_seconds_since_creation(&self) -> u64 {
            self.current_time
        }
    }

    #[test]
    fn nostd_insert_and_get_constant_entry() {
        let clock = MockClock { current_time: 1000 };
        let mut map = TimedMap::new(clock);

        map.insert_constant(1, "constant value");

        assert_eq!(map.get(&1), Some(&"constant value"));
        assert_eq!(map.get_remaining_duration(&1), None);
    }

    #[test]
    fn nostd_insert_and_get_expirable_entry() {
        let clock = MockClock { current_time: 1000 };
        let mut map = TimedMap::new(clock);
        let duration = Duration::from_secs(60);

        map.insert_expirable(1, "expirable value", duration);

        assert_eq!(map.get(&1), Some(&"expirable value"));
        assert_eq!(map.get_remaining_duration(&1), Some(duration));
    }

    #[test]
    fn nostd_expired_entry() {
        let clock = MockClock { current_time: 1000 };
        let mut map = TimedMap::new(clock);
        let duration = Duration::from_secs(60);

        // Insert entry that expires in 60 seconds
        map.insert_expirable(1, "expirable value", duration);

        // Simulate time passage beyond expiration
        let clock = MockClock { current_time: 1070 };
        map.clock = clock;

        // The entry should be considered expired
        assert_eq!(map.get(&1), None);
        assert_eq!(map.get_remaining_duration(&1), None);
    }

    #[test]
    fn nostd_remove_entry() {
        let clock = MockClock { current_time: 1000 };
        let mut map = TimedMap::new(clock);

        map.insert_constant(1, "constant value");

        assert_eq!(map.remove(&1), Some("constant value"));
        assert_eq!(map.get(&1), None);
    }

    #[test]
    fn nostd_clear_removes_expiry_bookkeeping() {
        let clock = MockClock { current_time: 1000 };
        let mut map = TimedMap::new(clock);

        map.insert_expirable(1, "expirable value", Duration::from_secs(60));

        assert!(!map.expiries.is_empty());

        map.clear();

        assert!(map.expiries.is_empty());
        assert_eq!(map.len(), 0);
        assert_eq!(map.len_expired(), 0);
        assert_eq!(map.len_unchecked(), 0);
    }

    #[test]
    fn nostd_drop_expired_entries() {
        let clock = MockClock { current_time: 1000 };
        let mut map = TimedMap::new(clock);

        // Insert one constant and 2 expirable entries
        map.insert_expirable(1, "expirable value1", Duration::from_secs(50));
        map.insert_expirable(2, "expirable value2", Duration::from_secs(70));
        map.insert_constant(3, "constant value");

        // Simulate time passage beyond the expiration of the first entry
        let clock = MockClock { current_time: 1055 };
        map.clock = clock;

        // Entry 1 should be removed and entry 2 and 3 should still exist
        assert_eq!(map.get(&1), None);
        assert_eq!(map.get(&2), Some(&"expirable value2"));
        assert_eq!(map.get(&3), Some(&"constant value"));

        // Simulate time passage again to expire second expirable entry
        let clock = MockClock { current_time: 1071 };
        map.clock = clock;

        assert_eq!(map.get(&1), None);
        assert_eq!(map.get(&2), None);
        assert_eq!(map.get(&3), Some(&"constant value"));
    }

    #[test]
    fn nostd_update_existing_entry() {
        let clock = MockClock { current_time: 1000 };
        let mut map = TimedMap::new(clock);

        map.insert_constant(1, "initial value");
        assert_eq!(map.get(&1), Some(&"initial value"));

        // Update the value of the existing key and make it expirable
        map.insert_expirable(1, "updated value", Duration::from_secs(15));
        assert_eq!(map.get(&1), Some(&"updated value"));

        // Simulate time passage and expire the updated entry
        let clock = MockClock { current_time: 1016 };
        map.clock = clock;

        assert_eq!(map.get(&1), None);
    }

    #[test]
    fn nostd_update_expirable_entry_status() {
        let clock = MockClock { current_time: 1000 };
        let mut map = TimedMap::new(clock);

        map.insert_constant(1, "initial value");
        assert_eq!(map.get(&1), Some(&"initial value"));

        // Update the value of the existing key and make it expirable
        let old_status = map
            .update_expiration_status(1, Duration::from_secs(16))
            .expect("entry update shouldn't fail");
        assert!(old_status.is_none());
        assert_eq!(map.get(&1), Some(&"initial value"));

        // Simulate time passage and expire the updated entry
        let clock = MockClock { current_time: 1017 };
        map.clock = clock;
        assert_eq!(map.get(&1), None);
    }

    #[test]
    fn nostd_update_expirable_entry_status_with_previou_time() {
        let clock = MockClock { current_time: 1000 };
        let mut map = TimedMap::new(clock);

        // Insert map entry followed by immediately updating expiration time
        map.insert_expirable(1, "expirable value", Duration::from_secs(15));
        let old_status = map
            .update_expiration_status(1, Duration::from_secs(15))
            .expect("entry update shouldn't fail");
        assert!(matches!(
            old_status,
            Some(EntryStatus::ExpiresAtSeconds(1015))
        ));

        // We should still have our entry.
        assert_eq!(map.get(&1), Some(&"expirable value"));
        assert!(map.expiries.contains_key(&1015));
    }

    #[test]
    fn nostd_contains_key() {
        let clock = MockClock { current_time: 1000 };
        let mut map = TimedMap::new(clock);

        // Insert map entry and check if exists
        map.insert_expirable(1, "expirable value", Duration::from_secs(5));
        assert!(map.contains_key(&1));
    }

    #[test]
    fn nostd_keys_and_is_empty_ignore_expired_entries() {
        let mut clock = MockClock { current_time: 1000 };
        let mut map = TimedMap::new(clock);

        map.insert_expirable(1, "expired value", Duration::from_secs(1));
        map.insert_constant(2, "constant value");

        clock.current_time = 1002;
        map.clock = clock;

        assert_eq!(map.keys().as_slice(), &[2]);
        assert_eq!(map.keys_expired().as_slice(), &[1]);
        assert_eq!(map.keys_unchecked().as_slice(), &[1, 2]);
        assert!(!map.is_empty());
        assert!(!map.is_empty_unchecked());

        map.remove(&2);

        assert!(map.is_empty());
        assert_eq!(map.keys_expired().as_slice(), &[1]);
        assert!(!map.is_empty_unchecked());
    }

    #[test]
    fn nostd_iter_empty() {
        let clock = MockClock { current_time: 1000 };
        let map: TimedMap<u64, &str, MockClock> = TimedMap::new(clock);
        assert_eq!(map.iter().count(), 0);
        assert_eq!(map.into_iter().count(), 0);
    }

    #[test]
    fn nostd_iter_all_expired() {
        let mut clock = MockClock { current_time: 1000 };
        let mut map = TimedMap::new(clock);

        // Expires at 1001
        map.insert_expirable(1, "val1", Duration::from_secs(1));
        // Expires at 1002
        map.insert_expirable(2, "val2", Duration::from_secs(2));

        clock.current_time = 1003;
        map.clock = clock;

        assert_eq!(map.iter().count(), 0);
        assert_eq!(map.into_iter().count(), 0);
    }

    #[test]
    fn nostd_iter_mixed() {
        let mut clock = MockClock { current_time: 1000 };
        let mut map = TimedMap::new(clock);

        // Expires at 1001
        map.insert_expirable(1, "val1", Duration::from_secs(1));
        // Never expires
        map.insert_constant(2, "val2");
        // Expires at 1005
        map.insert_expirable(3, "val3", Duration::from_secs(5));

        clock.current_time = 1002;
        map.clock = clock;

        let mut collected: Vec<(&u64, &&str)> = map.iter().collect();
        collected.sort_by_key(|(k, _)| *k);

        assert_eq!(collected.len(), 2);
        assert_eq!(collected[0], (&2, &"val2"));
        assert_eq!(collected[1], (&3, &"val3"));
    }

    #[test]
    fn nostd_iter_mut_mixed() {
        let mut clock = MockClock { current_time: 1000 };
        let mut map = TimedMap::new(clock);

        // Expires at 1001
        map.insert_expirable(1, "val1", Duration::from_secs(1));
        // Never expires
        map.insert_constant(2, "val2");
        // Expires at 1005
        map.insert_expirable(3, "val3", Duration::from_secs(5));

        clock.current_time = 1002;
        map.clock = clock;

        for (k, v) in map.iter_mut() {
            if *k == 2 {
                *v = "modified_val2";
            }
        }

        assert_eq!(map.get(&1), None);
        assert_eq!(map.get(&2), Some(&"modified_val2"));
        assert_eq!(map.get(&3), Some(&"val3"));
    }
}

#[cfg(feature = "std")]
#[cfg(test)]
mod std_tests {
    use core::ops::Add;

    use super::*;

    #[test]
    fn std_expirable_and_constant_entries() {
        let mut map = TimedMap::new();

        map.insert_constant(1, "constant value");
        map.insert_expirable(2, "expirable value", Duration::from_secs(2));

        assert_eq!(map.get(&1), Some(&"constant value"));
        assert_eq!(map.get(&2), Some(&"expirable value"));

        assert_eq!(map.get_remaining_duration(&1), None);
        assert!(map.get_remaining_duration(&2).is_some());
    }

    #[test]
    fn std_expired_entry_removal() {
        let mut map = TimedMap::new();
        let duration = Duration::from_secs(2);

        map.insert_expirable(1, "expirable value", duration);

        // Wait for expiration
        std::thread::sleep(Duration::from_secs(3));

        // Entry should now be expired
        assert_eq!(map.get(&1), None);
        assert_eq!(map.get_remaining_duration(&1), None);
    }

    #[test]
    fn std_remove_entry() {
        let mut map = TimedMap::new();

        map.insert_constant(1, "constant value");
        map.insert_expirable(2, "expirable value", Duration::from_secs(2));

        assert_eq!(map.remove(&1), Some("constant value"));
        assert_eq!(map.remove(&2), Some("expirable value"));

        assert_eq!(map.get(&1), None);
        assert_eq!(map.get(&2), None);
    }

    #[test]
    fn std_clear_removes_expiry_bookkeeping() {
        let mut map = TimedMap::new();

        map.insert_expirable(1, "expirable value", Duration::from_secs(60));

        assert!(!map.expiries.is_empty());

        map.clear();

        assert!(map.expiries.is_empty());
        assert_eq!(map.len(), 0);
        assert_eq!(map.len_expired(), 0);
        assert_eq!(map.len_unchecked(), 0);
    }

    #[test]
    fn std_drop_expired_entries() {
        let mut map = TimedMap::new();

        map.insert_expirable(1, "expirable value1", Duration::from_secs(2));
        map.insert_expirable(2, "expirable value2", Duration::from_secs(4));

        // Wait for expiration
        std::thread::sleep(Duration::from_secs(3));

        // Entry 1 should be removed and entry 2 should still exist
        assert_eq!(map.get(&1), None);
        assert_eq!(map.get(&2), Some(&"expirable value2"));
    }

    #[test]
    fn std_update_existing_entry() {
        let mut map = TimedMap::new();

        map.insert_constant(1, "initial value");
        assert_eq!(map.get(&1), Some(&"initial value"));

        // Update the value of the existing key and make it expirable
        map.insert_expirable(1, "updated value", Duration::from_secs(1));
        assert_eq!(map.get(&1), Some(&"updated value"));

        std::thread::sleep(Duration::from_secs(2));

        // Should be expired now
        assert_eq!(map.get(&1), None);
    }

    #[test]
    fn std_insert_constant_and_expirable_combined() {
        let mut map = TimedMap::new();

        // Insert a constant entry and an expirable entry
        map.insert_constant(1, "constant value");
        map.insert_expirable(2, "expirable value", Duration::from_secs(2));

        // Check both entries exist
        assert_eq!(map.get(&1), Some(&"constant value"));
        assert_eq!(map.get(&2), Some(&"expirable value"));

        // Simulate passage of time beyond expiration
        std::thread::sleep(Duration::from_secs(3));

        // Constant entry should still exist, expirable should be expired
        assert_eq!(map.get(&1), Some(&"constant value"));
        assert_eq!(map.get(&2), None);
    }

    #[test]
    fn std_expirable_entry_still_valid_before_expiration() {
        let mut map = TimedMap::new();

        // Insert an expirable entry with a duration of 3 seconds
        map.insert_expirable(1, "expirable value", Duration::from_secs(3));

        // Simulate a short sleep of 2 seconds (still valid)
        std::thread::sleep(Duration::from_secs(2));

        // The entry should still be valid
        assert_eq!(map.get(&1), Some(&"expirable value"));
        assert!(map.get_remaining_duration(&1).unwrap().as_secs() == 1);
    }

    #[test]
    fn std_length_functions() {
        let mut map = TimedMap::new();

        map.insert_expirable(1, "expirable value", Duration::from_secs(1));
        map.insert_expirable(2, "expirable value", Duration::from_secs(1));
        map.insert_expirable(3, "expirable value", Duration::from_secs(3));
        map.insert_expirable(4, "expirable value", Duration::from_secs(3));
        map.insert_expirable(5, "expirable value", Duration::from_secs(3));
        map.insert_expirable(6, "expirable value", Duration::from_secs(3));

        std::thread::sleep(Duration::from_secs(2).add(Duration::from_millis(1)));

        assert_eq!(map.len(), 4);
        assert_eq!(map.len_expired(), 2);
        assert_eq!(map.len_unchecked(), 6);
    }

    #[test]
    fn std_update_expirable_entry() {
        let mut map = TimedMap::new();

        map.insert_expirable(1, "expirable value", Duration::from_secs(1));
        map.insert_expirable(1, "expirable value", Duration::from_secs(5));

        std::thread::sleep(Duration::from_secs(2));

        assert!(!map.expiries.contains_key(&1));
        assert!(map.expiries.contains_key(&5));
        assert_eq!(map.get(&1), Some(&"expirable value"));
    }

    #[test]
    fn std_update_expirable_entry_status() {
        let mut map = TimedMap::new();

        map.insert_expirable(1, "expirable value", Duration::from_secs(1));
        let old_status = map
            .update_expiration_status(1, Duration::from_secs(5))
            .expect("entry update shouldn't fail");
        assert!(matches!(old_status, Some(EntryStatus::ExpiresAtSeconds(_))));

        std::thread::sleep(Duration::from_secs(3));
        assert!(!map.expiries.contains_key(&1));
        assert!(map.expiries.contains_key(&5));
        assert_eq!(map.get(&1), Some(&"expirable value"));
    }

    #[test]
    fn std_update_constant_entry_status_returns_none() {
        let mut map = TimedMap::new();

        map.insert_constant(1, "initial value");

        let old_status = map
            .update_expiration_status(1, Duration::from_secs(5))
            .expect("entry update shouldn't fail");

        assert!(old_status.is_none());
        assert_eq!(map.get(&1), Some(&"initial value"));
    }

    #[test]
    fn std_update_expirable_entry_status_with_previou_time() {
        let mut map = TimedMap::new();

        // Insert map entry followed by immediately updating expiration time
        map.insert_expirable(1, "expirable value", Duration::from_secs(5));
        map.update_expiration_status(1, Duration::from_secs(5))
            .expect("entry update shouldn't fail");

        // We should still have our entry.
        assert_eq!(map.get(&1), Some(&"expirable value"));
        assert!(map.expiries.contains_key(&5));
    }

    #[test]
    fn std_contains_key() {
        let mut map = TimedMap::new();

        // Insert map entry and check if exists
        map.insert_expirable(1, "expirable value", Duration::from_secs(1));
        assert!(map.contains_key(&1));
    }

    #[test]
    fn std_does_not_contain_key_anymore() {
        let mut map = TimedMap::new();

        // Insert map entry and check if still exists after expiry
        map.insert_expirable(1, "expirable value", Duration::from_secs(1));
        std::thread::sleep(Duration::from_secs(2));
        assert!(!map.contains_key(&1));
    }

    #[test]
    fn std_contains_key_unchecked() {
        let mut map = TimedMap::new();

        map.insert_expirable(1, "expirable value", Duration::from_secs(1));
        std::thread::sleep(Duration::from_secs(2));
        assert!(map.contains_key_unchecked(&1));
    }

    #[test]
    fn std_keys_and_is_empty_ignore_expired_entries() {
        let mut map = TimedMap::new();

        map.insert_expirable(1, "expired value", Duration::from_secs(1));
        map.insert_constant(2, "constant value");

        std::thread::sleep(Duration::from_secs(2));

        assert_eq!(map.keys().as_slice(), &[2]);
        assert_eq!(map.keys_expired().as_slice(), &[1]);
        assert_eq!(map.keys_unchecked().as_slice(), &[1, 2]);
        assert!(!map.is_empty());
        assert!(!map.is_empty_unchecked());

        map.remove(&2);

        assert!(map.is_empty());
        assert_eq!(map.keys_expired().as_slice(), &[1]);
        assert!(!map.is_empty_unchecked());
    }

    #[test]
    fn std_iter_empty() {
        let map: TimedMap<u64, &str> = TimedMap::new();
        assert_eq!(map.iter().count(), 0);
        assert_eq!(map.into_iter().count(), 0);
    }

    #[test]
    fn std_iter_all_expired() {
        let mut map = TimedMap::new();

        map.insert_expirable(1, "val1", Duration::from_secs(1));
        map.insert_expirable(2, "val2", Duration::from_secs(1));

        std::thread::sleep(Duration::from_secs(2));

        assert_eq!(map.iter().count(), 0);
        assert_eq!(map.into_iter().count(), 0);
    }

    #[test]
    fn std_iter_mixed() {
        let mut map = TimedMap::new();

        map.insert_expirable(1, "val1", Duration::from_secs(1));
        map.insert_constant(2, "val2");
        map.insert_expirable(3, "val3", Duration::from_secs(5));

        // Only 1 should expire after this sleep
        std::thread::sleep(Duration::from_secs(2));

        let mut collected: Vec<(&u64, &&str)> = map.iter().collect();
        collected.sort_by_key(|(k, _)| *k);

        assert_eq!(collected.len(), 2);
        assert_eq!(collected[0], (&2, &"val2"));
        assert_eq!(collected[1], (&3, &"val3"));
    }

    #[test]
    fn std_iter_mut_mixed() {
        let mut map = TimedMap::new();

        map.insert_expirable(1, "val1", Duration::from_secs(1));
        map.insert_constant(2, "val2");
        map.insert_expirable(3, "val3", Duration::from_secs(5));

        // Only 1 should expire after this sleep
        std::thread::sleep(Duration::from_secs(2));

        for (k, v) in map.iter_mut() {
            if *k == 2 {
                *v = "modified_val2";
            }
        }

        assert_eq!(map.get(&1), None);
        assert_eq!(map.get(&2), Some(&"modified_val2"));
        assert_eq!(map.get(&3), Some(&"val3"));
    }
}