lockable 0.2.0

This library offers hash map, hash set and cache data structures where individual entries can be locked
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
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
use futures::stream::Stream;
use lru::LruCache;
use std::borrow::Borrow;
use std::fmt::Debug;
use std::hash::Hash;
use std::iter::Rev;
use std::sync::Arc;
use tokio::sync::Mutex;
use tokio::time::{Duration, Instant};

use crate::lockable_map_impl::{Entry, EntryValue, LockableMapConfig};
use crate::utils::primary_arc::PrimaryArc;

use super::guard::Guard;
use super::limit::{AsyncLimit, SyncLimit};
use super::lockable_map_impl::LockableMapImpl;
use super::lockable_trait::Lockable;
use super::map_like::{GetOrInsertNoneResult, MapLike};
use super::utils::time::{RealTime, TimeProvider};

// The MapLike implementation here allows LockableMapImpl to
// work with LruCache as an underlying map
impl<K, V> MapLike<K, Entry<V>> for LruCache<K, Entry<V>>
where
    K: Eq + PartialEq + Hash + Clone,
{
    type ItemIter<'a>
        = Rev<lru::Iter<'a, K, Entry<V>>>
    where
        K: 'a,
        V: 'a;

    fn new() -> Self {
        Self::unbounded()
    }

    fn len(&self) -> usize {
        self.iter().len()
    }

    fn get_or_insert_none(&mut self, key: &K) -> GetOrInsertNoneResult<Entry<V>> {
        // TODO Is there a way to only clone the key when the entry doesn't already exist?
        //      Might be possible with a RawEntry-like API. If we do that, we may
        //      even be able to remove the `Clone` bound from `K` everywhere in this library.
        // TODO This bool is a bad workaround. We should find a better way.
        let mut was_inserted = false;
        let entry = self.get_or_insert(key.clone(), || {
            was_inserted = true;
            PrimaryArc::new(Mutex::new(EntryValue { value: None }))
        });
        if was_inserted {
            GetOrInsertNoneResult::Inserted(entry)
        } else {
            GetOrInsertNoneResult::Existing(entry)
        }
    }

    fn get(&mut self, key: &K) -> Option<&Entry<V>> {
        LruCache::get(self, key)
    }

    fn remove(&mut self, key: &K) -> Option<Entry<V>> {
        self.pop(key)
    }

    fn iter(&self) -> Self::ItemIter<'_> {
        LruCache::iter(self).rev()
    }
}

pub struct LockableLruCacheConfig<Time>
where
    Time: TimeProvider + Clone,
{
    time_provider: Time,
}

impl<Time> Clone for LockableLruCacheConfig<Time>
where
    Time: TimeProvider + Clone,
{
    fn clone(&self) -> Self {
        Self {
            time_provider: self.time_provider.clone(),
        }
    }
}

impl<Time> LockableMapConfig for LockableLruCacheConfig<Time>
where
    Time: TimeProvider + Clone,
{
    type WrappedV<V> = CacheEntry<V>;
    type MapImpl<K, V>
        = LruCache<K, Entry<CacheEntry<V>>>
    where
        K: Eq + PartialEq + Hash + Clone;

    fn borrow_value<V>(v: &CacheEntry<V>) -> &V {
        &v.value
    }

    fn borrow_value_mut<V>(v: &mut CacheEntry<V>) -> &mut V {
        &mut v.value
    }

    fn wrap_value<V>(&self, value: V) -> CacheEntry<V> {
        CacheEntry {
            value,
            // last_unlocked is now since the entry was just freshly inserted
            last_unlocked: self.time_provider.now(),
        }
    }
    fn unwrap_value<V>(v: CacheEntry<V>) -> V {
        v.value
    }

    // on_unlock ensures that whenever we unlock an entry, its last_unlocked
    // timestamp gets updated
    fn on_unlock<V>(&self, v: Option<&mut CacheEntry<V>>) {
        if let Some(v) = v {
            v.last_unlocked = self.time_provider.now();
        }
    }
}

// The LRUCache actually stores <K, CacheEntry<V>> instead of <K, V> so that we can
// remember a last_unlocked timestamp for each entry
// Invariant:
// -  The `last_unlocked` timestamps of CacheEntry instances in the map will follow the
//    same order as the LRU order of the map, with an exception for currently locked
//    entries that may be temporarily out of order while the entry is locked.
#[derive(Debug)]
pub struct CacheEntry<V> {
    value: V,
    last_unlocked: Instant,
}

/// A threadsafe LRU cache where individual keys can be locked/unlocked, even if there is no entry for this key in the cache.
/// It initially considers all keys as "unlocked", but they can be locked and if a second thread tries to acquire a lock
/// for the same key, they will have to wait.
///
/// This class is only available if the `lru` crate feature is enabled.
///
/// ```
/// use lockable::{AsyncLimit, LockableLruCache};
///
/// let lockable_cache: LockableLruCache<i64, String> = LockableLruCache::new();
/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
/// let entry1 = lockable_cache.async_lock(4, AsyncLimit::no_limit()).await?;
/// let entry2 = lockable_cache.async_lock(5, AsyncLimit::no_limit()).await?;
///
/// // This next line would cause a deadlock or panic because `4` is already locked on this thread
/// // let entry3 = lockable_cache.async_lock(4, AsyncLimit::no_limit()).await?;
///
/// // After dropping the corresponding guard, we can lock it again
/// std::mem::drop(entry1);
/// let entry3 = lockable_cache.async_lock(4, AsyncLimit::no_limit()).await?;
/// # Ok::<(), lockable::Never>(())}).unwrap();
/// ```
///
/// The guards holding a lock for an entry can be used to insert that entry to the cache, remove
/// it from the cache, or to modify the value of an existing entry.
///
/// ```
/// use lockable::{AsyncLimit, LockableLruCache};
///
/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
/// async fn insert_entry(
///     lockable_cache: &LockableLruCache<i64, String>,
/// ) -> Result<(), lockable::Never> {
///     let mut entry_guard = lockable_cache.async_lock(4, AsyncLimit::no_limit()).await?;
///     entry_guard.insert(String::from("Hello World"));
///     Ok(())
/// }
///
/// async fn remove_entry(
///     lockable_cache: &LockableLruCache<i64, String>,
/// ) -> Result<(), lockable::Never> {
///     let mut entry_guard = lockable_cache.async_lock(4, AsyncLimit::no_limit()).await?;
///     entry_guard.remove();
///     Ok(())
/// }
///
/// let lockable_cache: LockableLruCache<i64, String> = LockableLruCache::new();
/// assert_eq!(
///     None,
///     lockable_cache
///         .async_lock(4, AsyncLimit::no_limit())
///         .await?
///         .value()
/// );
/// insert_entry(&lockable_cache).await;
/// assert_eq!(
///     Some(&String::from("Hello World")),
///     lockable_cache
///         .async_lock(4, AsyncLimit::no_limit())
///         .await?
///         .value()
/// );
/// remove_entry(&lockable_cache).await;
/// assert_eq!(
///     None,
///     lockable_cache
///         .async_lock(4, AsyncLimit::no_limit())
///         .await?
///         .value()
/// );
/// # Ok::<(), lockable::Never>(())}).unwrap();
/// ```
///
///
/// You can use an arbitrary type to index cache entries by, as long as that type implements [PartialEq] + [Eq] + [Hash] + [Clone].
///
/// ```
/// use lockable::{AsyncLimit, LockableLruCache};
///
/// #[derive(PartialEq, Eq, Hash, Clone)]
/// struct CustomLockKey(u32);
///
/// let lockable_cache: LockableLruCache<CustomLockKey, String> = LockableLruCache::new();
/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
/// let guard = lockable_cache
///     .async_lock(CustomLockKey(4), AsyncLimit::no_limit())
///     .await?;
/// # Ok::<(), lockable::Never>(())}).unwrap();
/// ```
///
/// Under the hood, a [LockableLruCache] is a [lru::LruCache] of [Mutex](tokio::sync::Mutex)es, with some logic making sure that
/// empty entries can also be locked and that there aren't any race conditions when adding or removing entries.
#[derive(Debug)]
pub struct LockableLruCache<K, V, Time = RealTime>
where
    K: Eq + PartialEq + Hash + Clone,
    Time: TimeProvider + Default + Clone,
{
    map_impl: LockableMapImpl<K, V, LockableLruCacheConfig<Time>>,
}

impl<K, V, Time> Lockable<K, V> for LockableLruCache<K, V, Time>
where
    K: Eq + PartialEq + Hash + Clone,
    Time: TimeProvider + Default + Clone,
{
    type Guard<'a>
        = Guard<
        K,
        V,
        LockableLruCacheConfig<Time>,
        &'a LockableMapImpl<K, V, LockableLruCacheConfig<Time>>,
    >
    where
        K: 'a,
        V: 'a,
        Time: 'a;

    type OwnedGuard = Guard<K, V, LockableLruCacheConfig<Time>, Arc<LockableLruCache<K, V, Time>>>;

    type SyncLimit<'a, OnEvictFn, E>
        = SyncLimit<
        K,
        V,
        LockableLruCacheConfig<Time>,
        &'a LockableMapImpl<K, V, LockableLruCacheConfig<Time>>,
        E,
        OnEvictFn,
    >
    where
        OnEvictFn: FnMut(Vec<Self::Guard<'a>>) -> Result<(), E>,
        K: 'a,
        V: 'a,
        Time: 'a;

    type SyncLimitOwned<OnEvictFn, E>
        = SyncLimit<
        K,
        V,
        LockableLruCacheConfig<Time>,
        Arc<LockableLruCache<K, V, Time>>,
        E,
        OnEvictFn,
    >
    where
        OnEvictFn: FnMut(Vec<Self::OwnedGuard>) -> Result<(), E>;

    type AsyncLimit<'a, OnEvictFn, E, F>
        = AsyncLimit<
        K,
        V,
        LockableLruCacheConfig<Time>,
        &'a LockableMapImpl<K, V, LockableLruCacheConfig<Time>>,
        E,
        F,
        OnEvictFn,
    >
    where
        F: Future<Output = Result<(), E>>,
        OnEvictFn: FnMut(Vec<Self::Guard<'a>>) -> F,
        K: 'a,
        V: 'a,
        Time: 'a;

    type AsyncLimitOwned<OnEvictFn, E, F>
        = AsyncLimit<
        K,
        V,
        LockableLruCacheConfig<Time>,
        Arc<LockableLruCache<K, V, Time>>,
        E,
        F,
        OnEvictFn,
    >
    where
        F: Future<Output = Result<(), E>>,
        OnEvictFn: FnMut(Vec<Self::OwnedGuard>) -> F;
}

impl<K, V, Time> LockableLruCache<K, V, Time>
where
    K: Eq + PartialEq + Hash + Clone,
    Time: TimeProvider + Default + Clone,
{
    /// Create a new hash map with no entries and no locked keys.
    ///
    /// Examples
    /// -----
    /// ```
    /// use lockable::{AsyncLimit, LockableLruCache};
    ///
    /// let lockable_map: LockableLruCache<i64, String> = LockableLruCache::new();
    /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
    /// let guard = lockable_map.async_lock(4, AsyncLimit::no_limit()).await?;
    /// # Ok::<(), lockable::Never>(())}).unwrap();
    /// ```
    #[inline]
    pub fn new() -> Self {
        let time_provider = Time::default();
        Self {
            map_impl: LockableMapImpl::new(LockableLruCacheConfig { time_provider }),
        }
    }

    /// Return the number of cache entries.
    ///
    /// Corner case: Currently locked keys are counted even if they don't have any data in the cache.
    ///
    /// Examples
    /// -----
    /// ```
    /// use lockable::{AsyncLimit, LockableLruCache};
    ///
    /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
    /// let lockable_map = LockableLruCache::<i64, String>::new();
    ///
    /// // Insert two entries
    /// lockable_map
    ///     .async_lock(4, AsyncLimit::no_limit())
    ///     .await?
    ///     .insert(String::from("Value 4"));
    /// lockable_map
    ///     .async_lock(5, AsyncLimit::no_limit())
    ///     .await?
    ///     .insert(String::from("Value 5"));
    /// // Keep a lock on a third entry but don't insert it
    /// let guard = lockable_map.async_lock(6, AsyncLimit::no_limit()).await?;
    ///
    /// // Now we have two entries and one additional locked guard
    /// assert_eq!(3, lockable_map.num_entries_or_locked());
    /// # Ok::<(), lockable::Never>(())}).unwrap();
    /// ```
    #[inline]
    pub fn num_entries_or_locked(&self) -> usize {
        self.map_impl.num_entries_or_locked()
    }

    /// Lock a key and return a guard with any potential cache entry for that key.
    /// Any changes to that entry will be persisted in the cache.
    /// Locking a key prevents any other threads from locking the same key, but the action of locking a key doesn't insert
    /// a cache entry by itself. Cache entries can be inserted and removed using [Guard::insert] and [Guard::remove] on the returned entry guard.
    ///
    /// If the lock with this key is currently locked by a different thread, then the current thread blocks until it becomes available.
    /// Upon returning, the thread is the only thread with the lock held. A RAII guard is returned to allow scoped unlock
    /// of the lock. When the guard goes out of scope, the lock will be unlocked.
    ///
    /// This function can only be used from non-async contexts and will panic if used from async contexts.
    ///
    /// The exact behavior on locking a lock in the thread which already holds the lock is left unspecified.
    /// However, this function will not return on the second call (it might panic or deadlock, for example).
    ///
    /// The `limit` parameter can be used to set a limit on the number of entries in the cache, see the documentation of [SyncLimit]
    /// for an explanation of how exactly it works.
    ///
    /// Panics
    /// -----
    /// - This function might panic when called if the lock is already held by the current thread.
    /// - This function will also panic when called from an `async` context.
    ///   See documentation of [tokio::sync::Mutex] for details.
    ///
    /// Examples
    /// -----
    /// ```
    /// use lockable::{LockableLruCache, SyncLimit};
    ///
    /// # (||{
    /// let lockable_cache = LockableLruCache::<i64, String>::new();
    /// let guard1 = lockable_cache.blocking_lock(4, SyncLimit::no_limit())?;
    /// let guard2 = lockable_cache.blocking_lock(5, SyncLimit::no_limit())?;
    ///
    /// // This next line would cause a deadlock or panic because `4` is already locked on this thread
    /// // let guard3 = lockable_cache.blocking_lock(4, SyncLimit::no_limit())?;
    ///
    /// // After dropping the corresponding guard, we can lock it again
    /// std::mem::drop(guard1);
    /// let guard3 = lockable_cache.blocking_lock(4, SyncLimit::no_limit())?;
    /// # Ok::<(), lockable::Never>(())})().unwrap();
    /// ```
    #[inline]
    pub fn blocking_lock<'a, E, OnEvictFn>(
        &'a self,
        key: K,
        limit: <Self as Lockable<K, V>>::SyncLimit<'a, OnEvictFn, E>,
    ) -> Result<<Self as Lockable<K, V>>::Guard<'a>, E>
    where
        OnEvictFn: FnMut(Vec<<Self as Lockable<K, V>>::Guard<'a>>) -> Result<(), E>,
    {
        LockableMapImpl::blocking_lock(&self.map_impl, key, limit)
    }

    /// Lock a lock by key and return a guard with any potential cache entry for that key.
    ///
    /// This is identical to [LockableLruCache::blocking_lock], please see documentation for that function for more information.
    /// But different to [LockableLruCache::blocking_lock], [LockableLruCache::blocking_lock_owned] works on an `Arc<LockableLruCache>`
    /// instead of a [LockableLruCache] and returns a [Lockable::OwnedGuard] that binds its lifetime to the [LockableLruCache] in that [Arc].
    /// Such a [Lockable::OwnedGuard] can be more easily moved around or cloned than the [Lockable::Guard] returned by [LockableLruCache::blocking_lock].
    ///
    /// Examples
    /// -----
    /// ```
    /// use lockable::{LockableLruCache, SyncLimit};
    /// use std::sync::Arc;
    ///
    /// # (||{
    /// let lockable_cache = Arc::new(LockableLruCache::<i64, String>::new());
    /// let guard1 = lockable_cache.blocking_lock_owned(4, SyncLimit::no_limit())?;
    /// let guard2 = lockable_cache.blocking_lock_owned(5, SyncLimit::no_limit())?;
    ///
    /// // This next line would cause a deadlock or panic because `4` is already locked on this thread
    /// // let guard3 = lockable_cache.blocking_lock_owned(4, SyncLimit::no_limit())?;
    ///
    /// // After dropping the corresponding guard, we can lock it again
    /// std::mem::drop(guard1);
    /// let guard3 = lockable_cache.blocking_lock_owned(4, SyncLimit::no_limit())?;
    /// # Ok::<(), lockable::Never>(())})().unwrap();
    /// ```
    #[inline]
    pub fn blocking_lock_owned<E, OnEvictFn>(
        self: &Arc<Self>,
        key: K,
        limit: <Self as Lockable<K, V>>::SyncLimitOwned<OnEvictFn, E>,
    ) -> Result<<Self as Lockable<K, V>>::OwnedGuard, E>
    where
        OnEvictFn: FnMut(Vec<<Self as Lockable<K, V>>::OwnedGuard>) -> Result<(), E>,
    {
        LockableMapImpl::blocking_lock(Arc::clone(self), key, limit)
    }

    /// Attempts to acquire the lock with the given key and if successful, returns a guard with any potential cache entry for that key.
    /// Any changes to that entry will be persisted in the cache.
    /// Locking a key prevents any other threads from locking the same key, but the action of locking a key doesn't insert
    /// a cache entry by itself. Cache entries can be inserted and removed using [Guard::insert] and [Guard::remove] on the returned entry guard.
    ///
    /// If the lock could not be acquired because it is already locked, then [Ok](Ok)([None]) is returned. Otherwise, a RAII guard is returned.
    /// The lock will be unlocked when the guard is dropped.
    ///
    /// This function does not block and can be used from both async and non-async contexts.
    ///
    /// The `limit` parameter can be used to set a limit on the number of entries in the cache, see the documentation of [SyncLimit]
    /// for an explanation of how exactly it works.
    ///
    /// Examples
    /// -----
    /// ```
    /// use lockable::{LockableLruCache, SyncLimit};
    ///
    /// # (||{
    /// let lockable_cache: LockableLruCache<i64, String> = LockableLruCache::new();
    /// let guard1 = lockable_cache.blocking_lock(4, SyncLimit::no_limit())?;
    /// let guard2 = lockable_cache.blocking_lock(5, SyncLimit::no_limit())?;
    ///
    /// // This next line cannot acquire the lock because `4` is already locked on this thread
    /// let guard3 = lockable_cache.try_lock(4, SyncLimit::no_limit())?;
    /// assert!(guard3.is_none());
    ///
    /// // After dropping the corresponding guard, we can lock it again
    /// std::mem::drop(guard1);
    /// let guard3 = lockable_cache.try_lock(4, SyncLimit::no_limit())?;
    /// assert!(guard3.is_some());
    /// # Ok::<(), lockable::Never>(())})().unwrap();
    /// ```
    #[inline]
    pub fn try_lock<'a, E, OnEvictFn>(
        &'a self,
        key: K,
        limit: <Self as Lockable<K, V>>::SyncLimit<'a, OnEvictFn, E>,
    ) -> Result<Option<<Self as Lockable<K, V>>::Guard<'a>>, E>
    where
        OnEvictFn: FnMut(Vec<<Self as Lockable<K, V>>::Guard<'a>>) -> Result<(), E>,
    {
        LockableMapImpl::try_lock(&self.map_impl, key, limit)
    }

    /// Attempts to acquire the lock with the given key and if successful, returns a guard with any potential cache entry for that key.
    ///
    /// This is identical to [LockableLruCache::blocking_lock], please see documentation for that function for more information.
    /// But different to [LockableLruCache::blocking_lock], [LockableLruCache::blocking_lock_owned] works on an `Arc<LockableLruCache>`
    /// instead of a [LockableLruCache] and returns a [Lockable::OwnedGuard] that binds its lifetime to the [LockableLruCache] in that [Arc].
    /// Such a [Lockable::OwnedGuard] can be more easily moved around or cloned than the [Lockable::Guard] returned by [LockableLruCache::blocking_lock].
    ///
    /// Examples
    /// -----
    /// ```
    /// use lockable::{LockableLruCache, SyncLimit};
    /// use std::sync::Arc;
    ///
    /// # (||{
    /// let lockable_cache = Arc::new(LockableLruCache::<i64, String>::new());
    /// let guard1 = lockable_cache.blocking_lock(4, SyncLimit::no_limit())?;
    /// let guard2 = lockable_cache.blocking_lock(5, SyncLimit::no_limit())?;
    ///
    /// // This next line cannot acquire the lock because `4` is already locked on this thread
    /// let guard3 = lockable_cache.try_lock_owned(4, SyncLimit::no_limit())?;
    /// assert!(guard3.is_none());
    ///
    /// // After dropping the corresponding guard, we can lock it again
    /// std::mem::drop(guard1);
    /// let guard3 = lockable_cache.try_lock_owned(4, SyncLimit::no_limit())?;
    /// assert!(guard3.is_some());
    /// # Ok::<(), lockable::Never>(())})().unwrap();
    /// ```
    #[inline]
    pub fn try_lock_owned<E, OnEvictFn>(
        self: &Arc<Self>,
        key: K,
        limit: <Self as Lockable<K, V>>::SyncLimitOwned<OnEvictFn, E>,
    ) -> Result<Option<<Self as Lockable<K, V>>::OwnedGuard>, E>
    where
        OnEvictFn: FnMut(Vec<<Self as Lockable<K, V>>::OwnedGuard>) -> Result<(), E>,
    {
        LockableMapImpl::try_lock(Arc::clone(self), key, limit)
    }

    /// Attempts to acquire the lock with the given key and if successful, returns a guard with any potential map entry for that key.
    ///
    /// This is identical to [LockableLruCache::try_lock], please see documentation for that function for more information.
    /// But different to [LockableLruCache::try_lock], [LockableLruCache::try_lock_async] takes an [AsyncLimit] instead of a [SyncLimit]
    /// and therefore allows an `async` callback to be specified for when the cache reaches its limit.
    ///
    /// This function does not block and can be used in async contexts.
    ///
    /// Examples
    /// -----
    /// ```
    /// use lockable::{AsyncLimit, LockableLruCache};
    /// use std::sync::Arc;
    ///
    /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
    /// let lockable_cache = LockableLruCache::<i64, String>::new();
    /// let guard1 = lockable_cache.async_lock(4, AsyncLimit::no_limit()).await?;
    /// let guard2 = lockable_cache.async_lock(5, AsyncLimit::no_limit()).await?;
    ///
    /// // This next line cannot acquire the lock because `4` is already locked on this thread
    /// let guard3 = lockable_cache
    ///     .try_lock_async(4, AsyncLimit::no_limit())
    ///     .await?;
    /// assert!(guard3.is_none());
    ///
    /// // After dropping the corresponding guard, we can lock it again
    /// std::mem::drop(guard1);
    /// let guard3 = lockable_cache
    ///     .try_lock_async(4, AsyncLimit::no_limit())
    ///     .await?;
    /// assert!(guard3.is_some());
    /// # Ok::<(), lockable::Never>(())}).unwrap();
    /// ```
    #[inline]
    pub async fn try_lock_async<'a, E, F, OnEvictFn>(
        &'a self,
        key: K,
        limit: <Self as Lockable<K, V>>::AsyncLimit<'a, OnEvictFn, E, F>,
    ) -> Result<Option<<Self as Lockable<K, V>>::Guard<'a>>, E>
    where
        F: Future<Output = Result<(), E>>,
        OnEvictFn: FnMut(Vec<<Self as Lockable<K, V>>::Guard<'a>>) -> F,
    {
        LockableMapImpl::try_lock_async(&self.map_impl, key, limit).await
    }

    /// Attempts to acquire the lock with the given key and if successful, returns a guard with any potential map entry for that key.
    ///
    /// This is identical to [LockableLruCache::try_lock_async], please see documentation for that function for more information.
    /// But different to [LockableLruCache::try_lock_async], [LockableLruCache::try_lock_owned_async] works on an `Arc<LockableLruCache>`
    /// instead of a [LockableLruCache] and returns a [Lockable::OwnedGuard] that binds its lifetime to the [LockableLruCache] in that [Arc].
    /// Such a [Lockable::OwnedGuard] can be more easily moved around or cloned than the [Lockable::Guard] returned by [LockableLruCache::try_lock_async].
    ///
    /// This is identical to [LockableLruCache::try_lock_owned], please see documentation for that function for more information.
    /// But different to [LockableLruCache::try_lock_owned], [LockableLruCache::try_lock_owned_async] takes an [AsyncLimit] instead of a [SyncLimit]
    /// and therefore allows an `async` callback to be specified for when the cache reaches its limit.
    ///
    /// Examples
    /// -----
    /// ```
    /// use lockable::{AsyncLimit, LockableLruCache};
    /// use std::sync::Arc;
    ///
    /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
    /// let lockable_cache = Arc::new(LockableLruCache::<i64, String>::new());
    /// let guard1 = lockable_cache.async_lock(4, AsyncLimit::no_limit()).await?;
    /// let guard2 = lockable_cache.async_lock(5, AsyncLimit::no_limit()).await?;
    ///
    /// // This next line cannot acquire the lock because `4` is already locked on this thread
    /// let guard3 = lockable_cache
    ///     .try_lock_owned_async(4, AsyncLimit::no_limit())
    ///     .await?;
    /// assert!(guard3.is_none());
    ///
    /// // After dropping the corresponding guard, we can lock it again
    /// std::mem::drop(guard1);
    /// let guard3 = lockable_cache
    ///     .try_lock_owned_async(4, AsyncLimit::no_limit())
    ///     .await?;
    /// assert!(guard3.is_some());
    /// # Ok::<(), lockable::Never>(())}).unwrap();
    /// ```
    #[inline]
    pub async fn try_lock_owned_async<E, F, OnEvictFn>(
        self: &Arc<Self>,
        key: K,
        limit: <Self as Lockable<K, V>>::AsyncLimitOwned<OnEvictFn, E, F>,
    ) -> Result<Option<<Self as Lockable<K, V>>::OwnedGuard>, E>
    where
        F: Future<Output = Result<(), E>>,
        OnEvictFn: FnMut(Vec<<Self as Lockable<K, V>>::OwnedGuard>) -> F,
    {
        LockableMapImpl::try_lock_async(Arc::clone(self), key, limit).await
    }

    /// Lock a key and return a guard with any potential map entry for that key.
    /// Any changes to that entry will be persisted in the map.
    /// Locking a key prevents any other tasks from locking the same key, but the action of locking a key doesn't insert
    /// a map entry by itself. Map entries can be inserted and removed using [Guard::insert] and [Guard::remove] on the returned entry guard.
    ///
    /// If the lock with this key is currently locked by a different task, then the current tasks `await`s until it becomes available.
    /// Upon returning, the task is the only task with the lock held. A RAII guard is returned to allow scoped unlock
    /// of the lock. When the guard goes out of scope, the lock will be unlocked.
    ///
    /// The `limit` parameter can be used to set a limit on the number of entries in the cache, see the documentation of [AsyncLimit]
    /// for an explanation of how exactly it works.
    ///
    /// Examples
    /// -----
    /// ```
    /// use lockable::{AsyncLimit, LockableLruCache};
    ///
    /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
    /// let lockable_map = LockableLruCache::<i64, String>::new();
    /// let guard1 = lockable_map.async_lock(4, AsyncLimit::no_limit()).await?;
    /// let guard2 = lockable_map.async_lock(5, AsyncLimit::no_limit()).await?;
    ///
    /// // This next line would cause a deadlock or panic because `4` is already locked on this thread
    /// // let guard3 = lockable_map.async_lock(4).await?;
    ///
    /// // After dropping the corresponding guard, we can lock it again
    /// std::mem::drop(guard1);
    /// let guard3 = lockable_map.async_lock(4, AsyncLimit::no_limit()).await?;
    /// # Ok::<(), lockable::Never>(())}).unwrap();
    /// ```
    #[inline]
    pub async fn async_lock<'a, E, F, OnEvictFn>(
        &'a self,
        key: K,
        limit: <Self as Lockable<K, V>>::AsyncLimit<'a, OnEvictFn, E, F>,
    ) -> Result<<Self as Lockable<K, V>>::Guard<'a>, E>
    where
        F: Future<Output = Result<(), E>>,
        OnEvictFn: FnMut(Vec<<Self as Lockable<K, V>>::Guard<'a>>) -> F,
    {
        LockableMapImpl::async_lock(&self.map_impl, key, limit).await
    }

    /// Lock a key and return a guard with any potential map entry for that key.
    /// Any changes to that entry will be persisted in the map.
    /// Locking a key prevents any other tasks from locking the same key, but the action of locking a key doesn't insert
    /// a map entry by itself. Map entries can be inserted and removed using [Guard::insert] and [Guard::remove] on the returned entry guard.
    ///
    /// This is identical to [LockableLruCache::async_lock], please see documentation for that function for more information.
    /// But different to [LockableLruCache::async_lock], [LockableLruCache::async_lock_owned] works on an `Arc<LockableLruCache>`
    /// instead of a [LockableLruCache] and returns a [Lockable::OwnedGuard] that binds its lifetime to the [LockableLruCache] in that [Arc].
    /// Such a [Lockable::OwnedGuard] can be more easily moved around or cloned than the [Lockable::Guard] returned by [LockableLruCache::async_lock].
    ///
    /// Examples
    /// -----
    /// ```
    /// use lockable::{AsyncLimit, LockableLruCache};
    /// use std::sync::Arc;
    ///
    /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
    /// let lockable_map = Arc::new(LockableLruCache::<i64, String>::new());
    /// let guard1 = lockable_map
    ///     .async_lock_owned(4, AsyncLimit::no_limit())
    ///     .await?;
    /// let guard2 = lockable_map
    ///     .async_lock_owned(5, AsyncLimit::no_limit())
    ///     .await?;
    ///
    /// // This next line would cause a deadlock or panic because `4` is already locked on this thread
    /// // let guard3 = lockable_map.async_lock_owned(4).await?;
    ///
    /// // After dropping the corresponding guard, we can lock it again
    /// std::mem::drop(guard1);
    /// let guard3 = lockable_map
    ///     .async_lock_owned(4, AsyncLimit::no_limit())
    ///     .await?;
    /// # Ok::<(), lockable::Never>(())}).unwrap();
    /// ```
    #[inline]
    pub async fn async_lock_owned<E, F, OnEvictFn>(
        self: &Arc<Self>,
        key: K,
        limit: <Self as Lockable<K, V>>::AsyncLimitOwned<OnEvictFn, E, F>,
    ) -> Result<<Self as Lockable<K, V>>::OwnedGuard, E>
    where
        F: Future<Output = Result<(), E>>,
        OnEvictFn: FnMut(Vec<<Self as Lockable<K, V>>::OwnedGuard>) -> F,
    {
        LockableMapImpl::async_lock(Arc::clone(self), key, limit).await
    }

    /// Consumes the cache and returns an iterator over all of its entries.
    ///
    /// Examples
    /// -----
    /// ```
    /// use lockable::{AsyncLimit, LockableLruCache};
    ///
    /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
    /// let lockable_map = LockableLruCache::<i64, String>::new();
    ///
    /// // Insert two entries
    /// lockable_map
    ///     .async_lock(4, AsyncLimit::no_limit())
    ///     .await?
    ///     .insert(String::from("Value 4"));
    /// lockable_map
    ///     .async_lock(5, AsyncLimit::no_limit())
    ///     .await?
    ///     .insert(String::from("Value 5"));
    ///
    /// let entries: Vec<(i64, String)> = lockable_map.into_entries_unordered().collect();
    ///
    /// // `entries` now contains both entries, but in an arbitrary order
    /// assert_eq!(2, entries.len());
    /// assert!(entries.contains(&(4, String::from("Value 4"))));
    /// assert!(entries.contains(&(5, String::from("Value 5"))));
    /// # Ok::<(), lockable::Never>(())}).unwrap();
    /// ```
    #[inline]
    pub fn into_entries_unordered(self) -> impl Iterator<Item = (K, V)> {
        self.map_impl
            .into_entries_unordered()
            .map(|(k, v)| (k, v.value))
    }

    /// Returns all of the keys that currently have an entry in the map.
    /// Caveat: Currently locked keys are listed even if they don't carry a value.
    ///
    /// This function has a high performance cost because it needs to lock the whole
    /// map to get a consistent snapshot and clone all the keys.
    ///
    /// Examples
    /// -----
    /// ```
    /// use lockable::{AsyncLimit, LockableLruCache};
    ///
    /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
    /// let lockable_map = LockableLruCache::<i64, String>::new();
    ///
    /// // Insert two entries
    /// lockable_map
    ///     .async_lock(4, AsyncLimit::no_limit())
    ///     .await?
    ///     .insert(String::from("Value 4"));
    /// lockable_map
    ///     .async_lock(5, AsyncLimit::no_limit())
    ///     .await?
    ///     .insert(String::from("Value 5"));
    /// // Keep a lock on a third entry but don't insert it
    /// let guard = lockable_map.async_lock(6, AsyncLimit::no_limit()).await?;
    ///
    /// let keys: Vec<i64> = lockable_map.keys_with_entries_or_locked();
    ///
    /// // `keys` now contains all three keys
    /// assert_eq!(3, keys.len());
    /// assert!(keys.contains(&4));
    /// assert!(keys.contains(&5));
    /// assert!(keys.contains(&6));
    /// # Ok::<(), lockable::Never>(())}).unwrap();
    /// ```
    #[inline]
    pub fn keys_with_entries_or_locked(&self) -> Vec<K> {
        self.map_impl.keys_with_entries_or_locked()
    }

    /// Lock all entries of the cache once. The result of this is a [Stream] that will
    /// produce the corresponding lock guards. If items are locked, the [Stream] will
    /// produce them as they become unlocked and can be locked by the stream.
    ///
    /// The returned stream is `async` and therefore may return items much later than
    /// when this function was called, but it only returns an entry if it existed
    /// or was locked at the time this function was called, and still exists when
    /// the stream is returning the entry.
    /// For any entry currently locked by another thread or task while this function
    /// is called, the following rules apply:
    /// - If that thread/task creates the entry => the stream will return it
    /// - If that thread/task removes the entry => the stream will not return it
    /// - If the entry was not pre-existing and that thread/task does not create it => the stream will not return it.
    ///
    /// Examples
    /// -----
    /// ```
    /// use futures::stream::StreamExt;
    /// use lockable::{AsyncLimit, LockableLruCache};
    ///
    /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
    /// let lockable_map = LockableLruCache::<i64, String>::new();
    ///
    /// // Insert two entries
    /// lockable_map
    ///     .async_lock(4, AsyncLimit::no_limit())
    ///     .await?
    ///     .insert(String::from("Value 4"));
    /// lockable_map
    ///     .async_lock(5, AsyncLimit::no_limit())
    ///     .await?
    ///     .insert(String::from("Value 5"));
    ///
    /// // Lock all entries and add them to an `entries` vector
    /// let mut entries: Vec<(i64, String)> = Vec::new();
    /// let mut stream = lockable_map.lock_all_entries().await;
    /// while let Some(guard) = stream.next().await {
    ///     entries.push((*guard.key(), guard.value().unwrap().clone()));
    /// }
    ///
    /// // `entries` now contains both entries, but in an arbitrary order
    /// assert_eq!(2, entries.len());
    /// assert!(entries.contains(&(4, String::from("Value 4"))));
    /// assert!(entries.contains(&(5, String::from("Value 5"))));
    /// # Ok::<(), lockable::Never>(())}).unwrap();
    /// ```
    pub async fn lock_all_entries(
        &self,
    ) -> impl Stream<Item = <Self as Lockable<K, V>>::Guard<'_>> {
        LockableMapImpl::lock_all_entries(&self.map_impl).await
    }

    /// Lock all entries of the cache once. The result of this is a [Stream] that will
    /// produce the corresponding lock guards. If items are locked, the [Stream] will
    /// produce them as they become unlocked and can be locked by the stream.
    ///
    /// This is identical to [LockableLruCache::lock_all_entries], but it works on
    /// an `Arc<LockableLruCache>` instead of a [LockableLruCache] and returns a
    /// [Lockable::OwnedGuard] that binds its lifetime to the [LockableLruCache] in that
    /// [Arc]. Such a [Lockable::OwnedGuard] can be more easily moved around or cloned.
    ///
    /// Examples
    /// -----
    /// ```
    /// use futures::stream::StreamExt;
    /// use lockable::{AsyncLimit, LockableLruCache};
    /// use std::sync::Arc;
    ///
    /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
    /// let lockable_map = Arc::new(LockableLruCache::<i64, String>::new());
    ///
    /// // Insert two entries
    /// lockable_map
    ///     .async_lock(4, AsyncLimit::no_limit())
    ///     .await?
    ///     .insert(String::from("Value 4"));
    /// lockable_map
    ///     .async_lock(5, AsyncLimit::no_limit())
    ///     .await?
    ///     .insert(String::from("Value 5"));
    ///
    /// // Lock all entries and add them to an `entries` vector
    /// let mut entries: Vec<(i64, String)> = Vec::new();
    /// let mut stream = lockable_map.lock_all_entries_owned().await;
    /// while let Some(guard) = stream.next().await {
    ///     entries.push((*guard.key(), guard.value().unwrap().clone()));
    /// }
    ///
    /// // `entries` now contains both entries, but in an arbitrary order
    /// assert_eq!(2, entries.len());
    /// assert!(entries.contains(&(4, String::from("Value 4"))));
    /// assert!(entries.contains(&(5, String::from("Value 5"))));
    /// # Ok::<(), lockable::Never>(())}).unwrap();
    /// ```
    pub async fn lock_all_entries_owned(
        self: &Arc<Self>,
    ) -> impl Stream<Item = <Self as Lockable<K, V>>::OwnedGuard> + use<K, V, Time> {
        LockableMapImpl::lock_all_entries(Arc::clone(self)).await
    }

    /// Lock all entries that are currently unlocked and that were unlocked for at least
    /// the given `duration`. This follows the LRU nature of the cache.
    ///
    /// Examples
    /// -----
    /// ```
    /// use lockable::{AsyncLimit, LockableLruCache};
    /// use tokio::time::{self, Duration};
    ///
    /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
    /// let lockable_map = LockableLruCache::<i64, String>::new();
    /// lockable_map
    ///     .async_lock(1, AsyncLimit::no_limit())
    ///     .await?
    ///     .insert(String::from("Value 1"));
    /// lockable_map
    ///     .async_lock(2, AsyncLimit::no_limit())
    ///     .await?
    ///     .insert(String::from("Value 2"));
    ///
    /// time::sleep(Duration::from_secs(1)).await;
    ///
    /// // Lock and unlock entry 1
    /// lockable_map.async_lock(1, AsyncLimit::no_limit()).await?;
    ///
    /// // Only entry 2 was unlocked more than half a second ago
    ///
    /// let unlocked_for_at_least_half_a_sec: Vec<(i64, String)> = lockable_map
    ///     .lock_entries_unlocked_for_at_least(Duration::from_millis(500))
    ///     .map(|guard| (*guard.key(), guard.value().cloned().unwrap()))
    ///     .collect();
    /// assert_eq!(
    ///     vec![(2, String::from("Value 2"))],
    ///     unlocked_for_at_least_half_a_sec
    /// );
    /// # Ok::<(), lockable::Never>(())}).unwrap();
    /// ```
    pub fn lock_entries_unlocked_for_at_least(
        &self,
        duration: Duration,
    ) -> impl Iterator<Item = <Self as Lockable<K, V>>::Guard<'_>> {
        Self::_lock_entries_unlocked_for_at_least(
            &self.map_impl,
            self.map_impl.config().time_provider.now(),
            duration,
        )
    }

    /// Lock all entries that are currently unlocked and that were unlocked for at least
    /// the given `duration`. This follows the LRU nature of the cache.
    ///
    /// This is identical to [LockableLruCache::lock_entries_unlocked_for_at_least], but it works on
    /// an `Arc<LockableLruCache>` instead of a [LockableLruCache] and returns a
    /// [Lockable::OwnedGuard] that binds its lifetime to the [LockableLruCache] in that
    /// [Arc]. Such a [Lockable::OwnedGuard] can be more easily moved around or cloned.
    ///
    /// Examples
    /// -----
    /// ```
    /// use lockable::{AsyncLimit, LockableLruCache};
    /// use std::sync::Arc;
    /// use tokio::time::{self, Duration};
    ///
    /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
    /// let lockable_map = Arc::new(LockableLruCache::<i64, String>::new());
    /// lockable_map
    ///     .async_lock(1, AsyncLimit::no_limit())
    ///     .await?
    ///     .insert(String::from("Value 1"));
    /// lockable_map
    ///     .async_lock(2, AsyncLimit::no_limit())
    ///     .await?
    ///     .insert(String::from("Value 2"));
    ///
    /// time::sleep(Duration::from_secs(1)).await;
    ///
    /// // Lock and unlock entry 1
    /// lockable_map.async_lock(1, AsyncLimit::no_limit()).await?;
    ///
    /// // Only entry 2 was unlocked more than half a second ago
    ///
    /// let unlocked_for_at_least_half_a_sec: Vec<(i64, String)> = lockable_map
    ///     .lock_entries_unlocked_for_at_least_owned(Duration::from_millis(500))
    ///     .map(|guard| (*guard.key(), guard.value().cloned().unwrap()))
    ///     .collect();
    /// assert_eq!(
    ///     vec![(2, String::from("Value 2"))],
    ///     unlocked_for_at_least_half_a_sec
    /// );
    /// # Ok::<(), lockable::Never>(())}).unwrap();
    /// ```
    pub fn lock_entries_unlocked_for_at_least_owned(
        self: &Arc<Self>,
        duration: Duration,
    ) -> impl Iterator<Item = <Self as Lockable<K, V>>::OwnedGuard> + use<K, V, Time> {
        Self::_lock_entries_unlocked_for_at_least(
            Arc::clone(self),
            self.map_impl.config().time_provider.now(),
            duration,
        )
    }

    fn _lock_entries_unlocked_for_at_least<
        S: Borrow<LockableMapImpl<K, V, LockableLruCacheConfig<Time>>> + Clone,
    >(
        this: S,
        now: Instant,
        duration: Duration,
    ) -> impl Iterator<Item = Guard<K, V, LockableLruCacheConfig<Time>, S>> {
        let cutoff = now - duration;
        LockableMapImpl::lock_all_unlocked(this, &move |entry| {
            let entry = entry.value_raw().expect("There must be a value, otherwise it cannot exist in the map as an 'unlocked' entry");
            entry.last_unlocked <= cutoff
        }).into_iter()
    }

    #[cfg(test)]
    fn time_provider(&self) -> &Time {
        &self.map_impl.config().time_provider
    }
}

impl<K, V, Time> Default for LockableLruCache<K, V, Time>
where
    K: Eq + PartialEq + Hash + Clone,
    Time: TimeProvider + Default + Clone,
{
    fn default() -> Self {
        Self::new()
    }
}

// We implement Borrow<LockableMapImpl> for Arc<LockableLruCache<K, V>> because that's the way, our LockableMapImpl can "see through" an instance
// of LockableLruCache to get to its "self" parameter in calls like LockableMapImpl::blocking_lock_owned.
// Since LockableMapImpl is a type private to this crate, this Borrow doesn't escape crate boundaries.
impl<K, V, Time> Borrow<LockableMapImpl<K, V, LockableLruCacheConfig<Time>>>
    for Arc<LockableLruCache<K, V, Time>>
where
    K: Eq + PartialEq + Hash + Clone,
    Time: TimeProvider + Default + Clone,
{
    fn borrow(&self) -> &LockableMapImpl<K, V, LockableLruCacheConfig<Time>> {
        &self.map_impl
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::instantiate_lockable_tests;
    use crate::utils::time::MockTime;

    instantiate_lockable_tests!(LockableLruCache);

    macro_rules! instantiate_lock_entries_unlocked_for_at_least_tests {
        ($create_map:expr, $lock_entries_unlocked_for_at_least:ident) => {
            #[test]
            fn zero_entries() {
                let map = $create_map;
                let old_enough: Vec<(i64, String)> = map
                    .$lock_entries_unlocked_for_at_least(Duration::from_millis(500))
                    .map(|guard| (*guard.key(), guard.value().cloned().unwrap()))
                    .collect();
                assert_eq!(Vec::<(i64, String)>::new(), old_enough);
            }

            #[tokio::test]
            async fn one_entry_not_old_enough() {
                let map = $create_map;
                map.async_lock(1, AsyncLimit::no_limit())
                    .await
                    .unwrap()
                    .insert(String::from("Value 1"));

                let old_enough: Vec<(i64, String)> = map
                    .$lock_entries_unlocked_for_at_least(Duration::from_millis(500))
                    .map(|guard| (*guard.key(), guard.value().cloned().unwrap()))
                    .collect();
                assert_eq!(Vec::<(i64, String)>::new(), old_enough);
            }

            #[tokio::test]
            async fn one_entry_old_enough() {
                let map = $create_map;
                map.async_lock(1, AsyncLimit::no_limit())
                    .await
                    .unwrap()
                    .insert(String::from("Value 1"));

                map.time_provider().advance_time(Duration::from_secs(1));

                let old_enough: Vec<(i64, String)> = map
                    .$lock_entries_unlocked_for_at_least(Duration::from_millis(500))
                    .map(|guard| (*guard.key(), guard.value().cloned().unwrap()))
                    .collect();
                crate::tests::assert_vec_eq_unordered(
                    vec![(1, String::from("Value 1"))],
                    old_enough,
                );
            }

            #[tokio::test]
            async fn one_entry_locked() {
                let map = $create_map;
                map.async_lock(1, AsyncLimit::no_limit())
                    .await
                    .unwrap()
                    .insert(String::from("Value 1"));

                map.time_provider().advance_time(Duration::from_secs(1));

                let _guard = map.async_lock(1, AsyncLimit::no_limit()).await.unwrap();

                let old_enough: Vec<(i64, String)> = map
                    .$lock_entries_unlocked_for_at_least(Duration::from_millis(500))
                    .map(|guard| (*guard.key(), guard.value().cloned().unwrap()))
                    .collect();
                crate::tests::assert_vec_eq_unordered(vec![], old_enough);
            }

            #[tokio::test]
            async fn two_entries_zero_old_enough_zero_locked() {
                let map = $create_map;
                map.async_lock(1, AsyncLimit::no_limit())
                    .await
                    .unwrap()
                    .insert(String::from("Value 1"));
                map.async_lock(2, AsyncLimit::no_limit())
                    .await
                    .unwrap()
                    .insert(String::from("Value 2"));

                let old_enough: Vec<(i64, String)> = map
                    .$lock_entries_unlocked_for_at_least(Duration::from_millis(500))
                    .map(|guard| (*guard.key(), guard.value().cloned().unwrap()))
                    .collect();
                assert_eq!(Vec::<(i64, String)>::new(), old_enough);
            }

            #[tokio::test]
            async fn two_entries_one_old_enough() {
                let map = $create_map;
                map.async_lock(1, AsyncLimit::no_limit())
                    .await
                    .unwrap()
                    .insert(String::from("Value 1"));
                map.time_provider().advance_time(Duration::from_secs(1));
                map.async_lock(2, AsyncLimit::no_limit())
                    .await
                    .unwrap()
                    .insert(String::from("Value 2"));

                let old_enough: Vec<(i64, String)> = map
                    .$lock_entries_unlocked_for_at_least(Duration::from_millis(500))
                    .map(|guard| (*guard.key(), guard.value().cloned().unwrap()))
                    .collect();
                crate::tests::assert_vec_eq_unordered(
                    vec![(1, String::from("Value 1"))],
                    old_enough,
                );
            }

            #[tokio::test]
            async fn two_entries_one_old_enough_and_locked() {
                let map = $create_map;
                map.async_lock(1, AsyncLimit::no_limit())
                    .await
                    .unwrap()
                    .insert(String::from("Value 1"));
                map.time_provider().advance_time(Duration::from_secs(1));
                map.async_lock(2, AsyncLimit::no_limit())
                    .await
                    .unwrap()
                    .insert(String::from("Value 2"));

                let _guard = map.async_lock(1, AsyncLimit::no_limit()).await.unwrap();

                let old_enough: Vec<(i64, String)> = map
                    .$lock_entries_unlocked_for_at_least(Duration::from_millis(500))
                    .map(|guard| (*guard.key(), guard.value().cloned().unwrap()))
                    .collect();
                crate::tests::assert_vec_eq_unordered(vec![], old_enough);
            }

            #[tokio::test]
            async fn two_entries_both_old_enough() {
                let map = $create_map;
                map.async_lock(1, AsyncLimit::no_limit())
                    .await
                    .unwrap()
                    .insert(String::from("Value 1"));
                map.async_lock(2, AsyncLimit::no_limit())
                    .await
                    .unwrap()
                    .insert(String::from("Value 2"));
                map.time_provider().advance_time(Duration::from_secs(1));

                let old_enough: Vec<(i64, String)> = map
                    .$lock_entries_unlocked_for_at_least(Duration::from_millis(500))
                    .map(|guard| (*guard.key(), guard.value().cloned().unwrap()))
                    .collect();
                crate::tests::assert_vec_eq_unordered(
                    vec![(1, String::from("Value 1")), (2, String::from("Value 2"))],
                    old_enough,
                );
            }

            #[tokio::test]
            async fn two_entries_both_old_enough_one_locked_1() {
                let map = $create_map;
                map.async_lock(1, AsyncLimit::no_limit())
                    .await
                    .unwrap()
                    .insert(String::from("Value 1"));
                map.async_lock(2, AsyncLimit::no_limit())
                    .await
                    .unwrap()
                    .insert(String::from("Value 2"));
                map.time_provider().advance_time(Duration::from_secs(1));

                let _guard = map.async_lock(1, AsyncLimit::no_limit()).await.unwrap();

                let old_enough: Vec<(i64, String)> = map
                    .$lock_entries_unlocked_for_at_least(Duration::from_millis(500))
                    .map(|guard| (*guard.key(), guard.value().cloned().unwrap()))
                    .collect();
                crate::tests::assert_vec_eq_unordered(
                    vec![(2, String::from("Value 2"))],
                    old_enough,
                );
            }

            #[tokio::test]
            async fn two_entries_both_old_enough_one_locked_2() {
                let map = $create_map;
                map.async_lock(1, AsyncLimit::no_limit())
                    .await
                    .unwrap()
                    .insert(String::from("Value 1"));
                map.async_lock(2, AsyncLimit::no_limit())
                    .await
                    .unwrap()
                    .insert(String::from("Value 2"));
                map.time_provider().advance_time(Duration::from_secs(1));

                let _guard = map.async_lock(2, AsyncLimit::no_limit()).await.unwrap();

                let old_enough: Vec<(i64, String)> = map
                    .$lock_entries_unlocked_for_at_least(Duration::from_millis(500))
                    .map(|guard| (*guard.key(), guard.value().cloned().unwrap()))
                    .collect();
                crate::tests::assert_vec_eq_unordered(
                    vec![(1, String::from("Value 1"))],
                    old_enough,
                );
            }

            #[tokio::test]
            async fn two_entries_both_old_enough_both_locked() {
                let map = $create_map;
                map.async_lock(1, AsyncLimit::no_limit())
                    .await
                    .unwrap()
                    .insert(String::from("Value 1"));
                map.async_lock(2, AsyncLimit::no_limit())
                    .await
                    .unwrap()
                    .insert(String::from("Value 2"));
                map.time_provider().advance_time(Duration::from_secs(1));

                let _guard1 = map.async_lock(1, AsyncLimit::no_limit()).await.unwrap();
                let _guard2 = map.async_lock(2, AsyncLimit::no_limit()).await.unwrap();

                let old_enough: Vec<(i64, String)> = map
                    .$lock_entries_unlocked_for_at_least(Duration::from_millis(500))
                    .map(|guard| (*guard.key(), guard.value().cloned().unwrap()))
                    .collect();
                crate::tests::assert_vec_eq_unordered(vec![], old_enough);
            }

            #[tokio::test]
            async fn three_entries_zero_old_enough() {
                let map = $create_map;
                map.async_lock(1, AsyncLimit::no_limit())
                    .await
                    .unwrap()
                    .insert(String::from("Value 1"));
                map.async_lock(2, AsyncLimit::no_limit())
                    .await
                    .unwrap()
                    .insert(String::from("Value 2"));
                map.async_lock(3, AsyncLimit::no_limit())
                    .await
                    .unwrap()
                    .insert(String::from("Value 3"));

                let old_enough: Vec<(i64, String)> = map
                    .$lock_entries_unlocked_for_at_least(Duration::from_millis(500))
                    .map(|guard| (*guard.key(), guard.value().cloned().unwrap()))
                    .collect();
                assert_eq!(Vec::<(i64, String)>::new(), old_enough);
            }

            #[tokio::test]
            async fn three_entries_one_old_enough() {
                let map = $create_map;
                map.async_lock(1, AsyncLimit::no_limit())
                    .await
                    .unwrap()
                    .insert(String::from("Value 1"));
                map.time_provider().advance_time(Duration::from_secs(1));
                map.async_lock(2, AsyncLimit::no_limit())
                    .await
                    .unwrap()
                    .insert(String::from("Value 2"));
                map.async_lock(3, AsyncLimit::no_limit())
                    .await
                    .unwrap()
                    .insert(String::from("Value 3"));

                let old_enough: Vec<(i64, String)> = map
                    .$lock_entries_unlocked_for_at_least(Duration::from_millis(500))
                    .map(|guard| (*guard.key(), guard.value().cloned().unwrap()))
                    .collect();
                crate::tests::assert_vec_eq_unordered(
                    vec![(1, String::from("Value 1"))],
                    old_enough,
                );
            }

            #[tokio::test]
            async fn three_entries_two_old_enough() {
                let map = $create_map;
                map.async_lock(1, AsyncLimit::no_limit())
                    .await
                    .unwrap()
                    .insert(String::from("Value 1"));
                map.async_lock(2, AsyncLimit::no_limit())
                    .await
                    .unwrap()
                    .insert(String::from("Value 2"));
                map.time_provider().advance_time(Duration::from_secs(1));
                map.async_lock(3, AsyncLimit::no_limit())
                    .await
                    .unwrap()
                    .insert(String::from("Value 3"));

                let old_enough: Vec<(i64, String)> = map
                    .$lock_entries_unlocked_for_at_least(Duration::from_millis(500))
                    .map(|guard| (*guard.key(), guard.value().cloned().unwrap()))
                    .collect();
                crate::tests::assert_vec_eq_unordered(
                    vec![(1, String::from("Value 1")), (2, String::from("Value 2"))],
                    old_enough,
                );
            }

            #[tokio::test]
            async fn three_entries_three_old_enough() {
                let map = $create_map;
                map.async_lock(1, AsyncLimit::no_limit())
                    .await
                    .unwrap()
                    .insert(String::from("Value 1"));
                map.async_lock(2, AsyncLimit::no_limit())
                    .await
                    .unwrap()
                    .insert(String::from("Value 2"));
                map.async_lock(3, AsyncLimit::no_limit())
                    .await
                    .unwrap()
                    .insert(String::from("Value 3"));
                map.time_provider().advance_time(Duration::from_secs(1));

                let old_enough: Vec<(i64, String)> = map
                    .$lock_entries_unlocked_for_at_least(Duration::from_millis(500))
                    .map(|guard| (*guard.key(), guard.value().cloned().unwrap()))
                    .collect();
                crate::tests::assert_vec_eq_unordered(
                    vec![
                        (1, String::from("Value 1")),
                        (2, String::from("Value 2")),
                        (3, String::from("Value 3")),
                    ],
                    old_enough,
                );
            }

            #[tokio::test]
            async fn locking_an_entry_makes_it_not_old_enough_anymore_1() {
                let map = $create_map;
                map.async_lock(1, AsyncLimit::no_limit())
                    .await
                    .unwrap()
                    .insert(String::from("Value 1"));
                map.async_lock(2, AsyncLimit::no_limit())
                    .await
                    .unwrap()
                    .insert(String::from("Value 2"));
                map.async_lock(3, AsyncLimit::no_limit())
                    .await
                    .unwrap()
                    .insert(String::from("Value 3"));
                map.time_provider().advance_time(Duration::from_secs(1));

                let guard = map.async_lock(1, AsyncLimit::no_limit()).await.unwrap();
                std::mem::drop(guard);

                map.time_provider().advance_time(Duration::from_millis(100));

                let old_enough: Vec<(i64, String)> = map
                    .$lock_entries_unlocked_for_at_least(Duration::from_millis(500))
                    .map(|guard| (*guard.key(), guard.value().cloned().unwrap()))
                    .collect();
                crate::tests::assert_vec_eq_unordered(
                    vec![(2, String::from("Value 2")), (3, String::from("Value 3"))],
                    old_enough,
                );
            }

            #[tokio::test]
            async fn locking_an_entry_makes_it_not_old_enough_anymore_2() {
                let map = $create_map;
                map.async_lock(1, AsyncLimit::no_limit())
                    .await
                    .unwrap()
                    .insert(String::from("Value 1"));
                map.async_lock(2, AsyncLimit::no_limit())
                    .await
                    .unwrap()
                    .insert(String::from("Value 2"));
                map.async_lock(3, AsyncLimit::no_limit())
                    .await
                    .unwrap()
                    .insert(String::from("Value 3"));
                map.time_provider().advance_time(Duration::from_secs(1));

                let guard = map.async_lock(2, AsyncLimit::no_limit()).await.unwrap();
                std::mem::drop(guard);

                map.time_provider().advance_time(Duration::from_millis(100));

                let old_enough: Vec<(i64, String)> = map
                    .$lock_entries_unlocked_for_at_least(Duration::from_millis(500))
                    .map(|guard| (*guard.key(), guard.value().cloned().unwrap()))
                    .collect();
                crate::tests::assert_vec_eq_unordered(
                    vec![(1, String::from("Value 1")), (3, String::from("Value 3"))],
                    old_enough,
                );
            }

            #[tokio::test]
            async fn locking_an_entry_makes_it_not_old_enough_anymore_3() {
                let map = $create_map;
                map.async_lock(1, AsyncLimit::no_limit())
                    .await
                    .unwrap()
                    .insert(String::from("Value 1"));
                map.async_lock(2, AsyncLimit::no_limit())
                    .await
                    .unwrap()
                    .insert(String::from("Value 2"));
                map.async_lock(3, AsyncLimit::no_limit())
                    .await
                    .unwrap()
                    .insert(String::from("Value 3"));
                map.time_provider().advance_time(Duration::from_secs(1));

                let guard = map.async_lock(3, AsyncLimit::no_limit()).await.unwrap();
                std::mem::drop(guard);

                map.time_provider().advance_time(Duration::from_millis(100));

                let old_enough: Vec<(i64, String)> = map
                    .$lock_entries_unlocked_for_at_least(Duration::from_millis(500))
                    .map(|guard| (*guard.key(), guard.value().cloned().unwrap()))
                    .collect();
                crate::tests::assert_vec_eq_unordered(
                    vec![(1, String::from("Value 1")), (2, String::from("Value 2"))],
                    old_enough,
                );
            }

            #[tokio::test]
            async fn can_lock_other_elements_while_iterator_is_running() {
                let map = $create_map;
                map.async_lock(1, AsyncLimit::no_limit())
                    .await
                    .unwrap()
                    .insert(String::from("Value 1"));
                map.time_provider().advance_time(Duration::from_secs(1));
                map.async_lock(2, AsyncLimit::no_limit())
                    .await
                    .unwrap()
                    .insert(String::from("Value 2"));

                map.time_provider().advance_time(Duration::from_millis(100));

                let old_enough_iterator =
                    map.$lock_entries_unlocked_for_at_least(Duration::from_millis(500));

                // Locking another entry should work and not interfere with the iterator
                let guard = map.async_lock(2, AsyncLimit::no_limit()).await.unwrap();
                std::mem::drop(guard);

                let old_enough: Vec<(i64, String)> = old_enough_iterator
                    .map(|guard| (*guard.key(), guard.value().cloned().unwrap()))
                    .collect();
                crate::tests::assert_vec_eq_unordered(
                    vec![(1, String::from("Value 1"))],
                    old_enough,
                );
            }
        };
    }

    mod lock_entries_unlocked_for_at_least {
        use super::*;

        instantiate_lock_entries_unlocked_for_at_least_tests!(
            LockableLruCache::<i64, String, MockTime>::new(),
            lock_entries_unlocked_for_at_least
        );
    }

    mod lock_entries_unlocked_for_at_least_owned {
        use super::*;

        instantiate_lock_entries_unlocked_for_at_least_tests!(
            Arc::new(LockableLruCache::<i64, String, MockTime>::new()),
            lock_entries_unlocked_for_at_least_owned
        );
    }

    #[test]
    fn test_default() {
        let lockable_map: LockableLruCache<i64, String> = Default::default();
        assert_eq!(0, lockable_map.num_entries_or_locked());
    }
}