quick_cache 0.6.21

Lightweight and high performance concurrent cache
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
//! Lightweight, high performance concurrent cache. It allows very fast access to the cached items
//! with little overhead compared to a plain concurrent hash table. No allocations are ever performed
//! unless the cache internal state table needs growing (which will eventually stabilize).
//!
//! # Eviction policy
//!
//! The current eviction policy is a modified version of the Clock-PRO algorithm, very similar to the
//! later published S3-FIFO algorithm. It's "scan resistent" and provides high hit rates,
//! significantly better than a LRU eviction policy and comparable to other state-of-the art algorithms
//! like W-TinyLFU.
//!
//! # Thread safety and Concurrency
//!
//! Both `sync` (thread-safe) and `unsync` (non thread-safe) implementations are provided. The latter
//! offers slightly better performance when thread safety is not required.
//!
//! # Equivalent keys
//!
//! The cache uses the [`Equivalent`](https://docs.rs/equivalent/1.0.1/equivalent/trait.Equivalent.html) trait
//! for gets/removals. It can help work around the `Borrow` limitations.
//! For example, if the cache key is a tuple `(K, Q)`, you wouldn't be able to access such keys without
//! building a `&(K, Q)` and thus potentially cloning `K` and/or `Q`.
//!
//! # User defined weight
//!
//! By implementing the [Weighter] trait the user can define different weights for each cache entry.
//!
//! # Atomic operations
//!
//! By using the `get_or_insert` or `get_value_or_guard` family of functions (both sync and async variants
//! are available, they can be mix and matched) the user can coordinate the insertion of entries, so only
//! one value is "computed" and inserted after a cache miss.
//!
//! The `entry` family of functions provide a closure-based API for atomically
//! inspecting and acting on existing entries (keep, remove, or replace) while also coordinating
//! insertion on cache misses.
//!
//! # Lifecycle hooks
//!
//! A user can optionally provide a custom [Lifecycle] implementation to hook into the lifecycle of cache entries.
//!
//! Example use cases:
//! * item pinning, so even if the item occupies weight but isn't allowed to be evicted
//! * send evicted items to a channel, achieving the equivalent to an eviction listener feature.
//! * zero out item weights so they are left in the cache instead of evicted.
//!
//! # Approximate memory usage
//!
//! The memory overhead per entry is `21` bytes.
//!
//! The memory usage of the cache data structures can be estimated as:
//! `(size_of::<K>() + size_of::<V>() + 21) * (length * 1.5).next_power_of_two()`
//!
//! Actual memory usage may vary depending on the cache options and the key and value types, which can have external
//! allocations (e.g. `String`, `Vec`, etc.). The above formula only accounts for the cache's data structures.
//!
//! The `1.5` value in the formula above results from `1 + G`, where `G` is the configured ghost allocation specified
//! in [`OptionsBuilder::ghost_allocation`], which is `0.5` by default.
//!
//! # Hasher
//!
//! By default the crate uses [ahash](https://crates.io/crates/ahash), which is enabled (by default) via
//! a crate feature with the same name. If the `ahash` feature is disabled the crate defaults to the std lib
//! implementation instead (currently Siphash13). Note that a custom hasher can also be provided if desirable.
//!
//! # Synchronization primitives
//!
//! By default the crate uses [parking_lot](https://crates.io/crates/parking_lot), which is enabled (by default) via
//! a crate feature with the same name. If `parking_lot` is disabled and `sharded-lock` is enabled, the crate uses
//! [`crossbeam_utils::sync::ShardedLock`](https://docs.rs/crossbeam-utils/latest/crossbeam_utils/sync/struct.ShardedLock.html)
//! from [crossbeam-utils](https://crates.io/crates/crossbeam-utils) instead. If both are disabled the crate defaults
//! to the std lib implementation. The `parking_lot` and `sharded-lock` features are mutually exclusive.
//!
//! # Cargo Features
//!
//! | Feature | Default | Description |
//! |---------|---------|-------------|
//! | `ahash` | ✓ | Use [ahash](https://crates.io/crates/ahash) as the default hasher. When disabled, falls back to std lib's `RandomState` (currently SipHash-1-3). |
//! | `parking_lot` | ✓ | Use [parking_lot](https://crates.io/crates/parking_lot) for synchronization primitives. Mutually exclusive with `sharded-lock`. |
//! | `sharded-lock` | | Use [`crossbeam_utils::sync::ShardedLock`](https://docs.rs/crossbeam-utils/latest/crossbeam_utils/sync/struct.ShardedLock.html) for synchronization primitives. Mutually exclusive with `parking_lot`. |
//! | `shuttle` | | Enable [shuttle](https://crates.io/crates/shuttle) testing support for concurrency testing. |
//! | `stats` | | Enable cache statistics tracking via the `hits()` and `misses()` methods. |
#![allow(clippy::type_complexity)]
#![cfg_attr(docsrs, feature(doc_cfg))]

#[cfg(all(feature = "parking_lot", feature = "sharded-lock"))]
compile_error!("features `parking_lot` and `sharded-lock` are mutually exclusive");

#[cfg(not(fuzzing))]
mod linked_slab;
#[cfg(fuzzing)]
pub mod linked_slab;
mod options;
#[cfg(not(feature = "shuttle"))]
mod rw_lock;
mod shard;
mod shim;
/// Concurrent cache variants that can be used from multiple threads.
pub mod sync;
mod sync_placeholder;
/// Non-concurrent cache variants.
pub mod unsync;
pub use equivalent::Equivalent;

#[cfg(all(test, feature = "shuttle"))]
mod shuttle_tests;

pub use options::{Options, OptionsBuilder};

#[cfg(feature = "ahash")]
pub type DefaultHashBuilder = ahash::RandomState;
#[cfg(not(feature = "ahash"))]
pub type DefaultHashBuilder = std::collections::hash_map::RandomState;

/// Defines the weight of a cache entry.
///
/// # Example
///
/// ```
/// use quick_cache::{sync::Cache, Weighter};
///
/// #[derive(Clone)]
/// struct StringWeighter;
///
/// impl Weighter<u64, String> for StringWeighter {
///     fn weight(&self, _key: &u64, val: &String) -> u64 {
///         // Be cautious about zero weights!
///         val.len() as u64
///     }
/// }
///
/// let cache = Cache::with_weighter(100, 100_000, StringWeighter);
/// cache.insert(1, "1".to_string());
/// ```
pub trait Weighter<Key, Val> {
    /// Returns the weight of the cache item.
    ///
    /// For performance reasons, this function should be trivially cheap as
    /// it's called during the cache eviction routine.
    /// If weight is expensive to calculate, consider caching it alongside the value.
    ///
    /// Zero (0) weight items are allowed and will be ignored when looking for eviction
    /// candidates. Such items can only be manually removed or overwritten.
    ///
    /// Note that it's undefined behavior for a cache item to change its weight.
    /// The only exception to this is when Lifecycle::before_evict is called.
    ///
    /// It's also undefined behavior in release mode if the summing of weights overflows,
    /// although this is unlikely to be a problem in practice.
    fn weight(&self, key: &Key, val: &Val) -> u64;
}

/// Each cache entry weights exactly `1` unit of weight.
#[derive(Debug, Clone, Default)]
pub struct UnitWeighter;

impl<Key, Val> Weighter<Key, Val> for UnitWeighter {
    #[inline]
    fn weight(&self, _key: &Key, _val: &Val) -> u64 {
        1
    }
}

/// Hooks into the lifetime of the cache items.
///
/// The functions should be small and very fast, otherwise the cache performance might be negatively affected.
pub trait Lifecycle<Key, Val> {
    type RequestState;

    /// Returns whether the item is pinned. Items that are pinned can't be evicted.
    /// Note that a pinned item can still be replaced with get_mut, insert, replace and similar APIs.
    ///
    /// Compared to zero (0) weight items, pinned items still consume (non-zero) weight even if they can't
    /// be evicted. Furthermore, zero (0) weight items are separated from the other entries, which allows
    /// having a large number of them without impacting performance, but moving them in/out or the evictable
    /// section has a small cost. Pinning on the other hand doesn't separate entries, so during eviction
    /// the cache may visit pinned entries but will ignore them.
    #[allow(unused_variables)]
    #[inline]
    fn is_pinned(&self, key: &Key, val: &Val) -> bool {
        false
    }

    /// Called before the insert request starts, e.g.: insert, replace.
    fn begin_request(&self) -> Self::RequestState;

    /// Called when a cache item is about to be evicted.
    /// Note that value replacement (e.g. insertions for the same key) won't call this method.
    ///
    /// This is the only time the item can change its weight. If the item weight becomes zero (0) it
    /// will be left in the cache, otherwise it'll still be removed. Zero (0) weight items aren't evictable
    /// and are kept separated from the other items so it's possible to have a large number of them without
    /// negatively affecting eviction performance.
    #[allow(unused_variables)]
    #[inline]
    fn before_evict(&self, state: &mut Self::RequestState, key: &Key, val: &mut Val) {}

    /// Called when an item is evicted.
    fn on_evict(&self, state: &mut Self::RequestState, key: Key, val: Val);

    /// Called after a request finishes, e.g.: insert, replace.
    ///
    /// Notes:
    /// This will _not_ be called when using `_with_lifecycle` apis, which will return the RequestState instead.
    /// This will _not_ be called if the request errored (e.g. a replace didn't find a value to replace).
    /// If needed, Drop for RequestState can be used to detect these cases.
    #[allow(unused_variables)]
    #[inline]
    fn end_request(&self, state: Self::RequestState) {}
}

/// The memory used by the cache
///
/// This struct exposes some implementation details, may change in the future
#[non_exhaustive]
#[derive(Debug, Copy, Clone)]
pub struct MemoryUsed {
    pub entries: usize,
    pub map: usize,
}

impl MemoryUsed {
    pub fn total(&self) -> usize {
        self.entries + self.map
    }
}

#[cfg(test)]
mod tests {
    use std::{
        hash::Hash,
        sync::{atomic::AtomicUsize, Arc},
        time::Duration,
    };

    use super::*;
    #[derive(Clone)]
    struct StringWeighter;

    impl Weighter<u64, String> for StringWeighter {
        fn weight(&self, _key: &u64, val: &String) -> u64 {
            val.len() as u64
        }
    }

    #[test]
    fn test_new() {
        sync::Cache::<(u64, u64), u64>::new(0);
        sync::Cache::<(u64, u64), u64>::new(1);
        sync::Cache::<(u64, u64), u64>::new(2);
        sync::Cache::<(u64, u64), u64>::new(3);
        sync::Cache::<(u64, u64), u64>::new(usize::MAX);
        sync::Cache::<u64, u64>::new(0);
        sync::Cache::<u64, u64>::new(1);
        sync::Cache::<u64, u64>::new(2);
        sync::Cache::<u64, u64>::new(3);
        sync::Cache::<u64, u64>::new(usize::MAX);
    }

    #[test]
    fn test_capacity_one() {
        // Sync cache with capacity 1 should be able to hold one item
        let cache = sync::Cache::<u64, u64>::new(1);
        cache.insert(1, 10);
        assert_eq!(cache.get(&1), Some(10));
        // Inserting a second key should evict the first
        cache.insert(2, 20);
        assert_eq!(cache.get(&2), Some(20));
        assert_eq!(cache.get(&1), None);

        // Unsync cache with capacity 1 should also work
        let mut cache = unsync::Cache::<u64, u64>::new(1);
        cache.insert(1, 10);
        assert_eq!(cache.get(&1), Some(&10));
        cache.insert(2, 20);
        assert_eq!(cache.get(&2), Some(&20));
        assert_eq!(cache.get(&1), None);

        // Capacity 0 should store nothing
        let cache = sync::Cache::<u64, u64>::new(0);
        cache.insert(1, 10);
        assert_eq!(cache.get(&1), None);
    }

    #[test]
    fn test_custom_cost() {
        let cache = sync::Cache::with_weighter(100, 100_000, StringWeighter);
        cache.insert(1, "1".to_string());
        cache.insert(54, "54".to_string());
        cache.insert(1000, "1000".to_string());
        assert_eq!(cache.get(&1000).unwrap(), "1000");
    }

    #[test]
    fn test_change_get_mut_change_weight() {
        let mut cache = unsync::Cache::with_weighter(100, 100_000, StringWeighter);
        cache.insert(1, "1".to_string());
        assert_eq!(cache.get(&1).unwrap(), "1");
        assert_eq!(cache.weight(), 1);
        let _old = {
            cache
                .get_mut(&1)
                .map(|mut v| std::mem::replace(&mut *v, "11".to_string()))
        };
        let _old = {
            cache
                .get_mut(&1)
                .map(|mut v| std::mem::replace(&mut *v, "".to_string()))
        };
        assert_eq!(cache.get(&1).unwrap(), "");
        assert_eq!(cache.weight(), 0);
        cache.validate(false);
    }

    #[derive(Debug, Hash)]
    pub struct Pair<A, B>(pub A, pub B);

    impl<A, B, C, D> PartialEq<(A, B)> for Pair<C, D>
    where
        C: PartialEq<A>,
        D: PartialEq<B>,
    {
        fn eq(&self, rhs: &(A, B)) -> bool {
            self.0 == rhs.0 && self.1 == rhs.1
        }
    }

    impl<A, B, X> Equivalent<X> for Pair<A, B>
    where
        Pair<A, B>: PartialEq<X>,
        A: Hash + Eq,
        B: Hash + Eq,
    {
        fn equivalent(&self, other: &X) -> bool {
            *self == *other
        }
    }

    #[test]
    fn test_equivalent() {
        let mut cache = unsync::Cache::new(5);
        cache.insert(("square".to_string(), 2022), "blue".to_string());
        cache.insert(("square".to_string(), 2023), "black".to_string());
        assert_eq!(cache.get(&Pair("square", 2022)).unwrap(), "blue");
    }

    #[test]
    fn test_borrow_keys() {
        let cache = sync::Cache::<(Vec<u8>, Vec<u8>), u64>::new(0);
        cache.get(&Pair(&b""[..], &b""[..]));
        let cache = sync::Cache::<(String, String), u64>::new(0);
        cache.get(&Pair("", ""));
    }

    #[test]
    #[cfg_attr(miri, ignore)]
    fn test_get_or_insert() {
        use rand::prelude::*;
        for _i in 0..2000 {
            dbg!(_i);
            let mut entered = AtomicUsize::default();
            let cache = sync::Cache::<(u64, u64), u64>::new(100);
            const THREADS: usize = 100;
            let wg = std::sync::Barrier::new(THREADS);
            let solve_at = rand::rng().random_range(0..THREADS);
            std::thread::scope(|s| {
                for _ in 0..THREADS {
                    s.spawn(|| {
                        wg.wait();
                        let result = cache.get_or_insert_with(&(1, 1), || {
                            let before = entered.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                            if before == solve_at {
                                Ok(1)
                            } else {
                                Err(())
                            }
                        });
                        assert!(matches!(result, Ok(1) | Err(())));
                    });
                }
            });
            assert_eq!(*entered.get_mut(), solve_at + 1);
        }
    }

    #[test]
    fn test_get_or_insert_unsync() {
        let mut cache = unsync::Cache::<u64, u64>::new(100);
        let guard = cache.get_ref_or_guard(&0).unwrap_err();
        guard.insert(0);
        assert_eq!(cache.get_ref_or_guard(&0).ok().copied(), Some(0));
        let guard = cache.get_mut_or_guard(&1).err().unwrap();
        guard.insert(1);
        let v = *cache.get_mut_or_guard(&1).ok().unwrap().unwrap();
        assert_eq!(v, 1);
        let result = cache.get_or_insert_with::<_, ()>(&0, || panic!());
        assert_eq!(result, Ok(Some(&0)));
        let result = cache.get_or_insert_with::<_, ()>(&1, || panic!());
        assert_eq!(result, Ok(Some(&1)));
        let result = cache.get_or_insert_with::<_, ()>(&3, || Ok(3));
        assert_eq!(result, Ok(Some(&3)));
        let result = cache.get_or_insert_with::<_, ()>(&4, || Err(()));
        assert_eq!(result, Err(()));
    }

    #[tokio::test]
    async fn test_get_or_insert_sync() {
        use crate::sync::*;
        let cache = sync::Cache::<u64, u64>::new(100);
        let GuardResult::Guard(guard) = cache.get_value_or_guard(&0, None) else {
            panic!();
        };
        guard.insert(0).unwrap();
        let GuardResult::Value(v) = cache.get_value_or_guard(&0, None) else {
            panic!();
        };
        assert_eq!(v, 0);
        let Err(guard) = cache.get_value_or_guard_async(&1).await else {
            panic!();
        };
        guard.insert(1).unwrap();
        let Ok(v) = cache.get_value_or_guard_async(&1).await else {
            panic!();
        };
        assert_eq!(v, 1);

        let result = cache.get_or_insert_with::<_, ()>(&0, || panic!());
        assert_eq!(result, Ok(0));
        let result = cache.get_or_insert_with::<_, ()>(&3, || Ok(3));
        assert_eq!(result, Ok(3));
        let result = cache.get_or_insert_with::<_, ()>(&4, || Err(()));
        assert_eq!(result, Err(()));
        let result = cache
            .get_or_insert_async::<_, ()>(&0, async { panic!() })
            .await;
        assert_eq!(result, Ok(0));
        let result = cache
            .get_or_insert_async::<_, ()>(&4, async { Err(()) })
            .await;
        assert_eq!(result, Err(()));
        let result = cache
            .get_or_insert_async::<_, ()>(&4, async { Ok(4) })
            .await;
        assert_eq!(result, Ok(4));
    }

    #[test]
    fn test_retain_unsync() {
        let mut cache = unsync::Cache::<u64, u64>::new(100);
        let ranges = 0..10;
        for i in ranges.clone() {
            let guard = cache.get_ref_or_guard(&i).unwrap_err();
            guard.insert(i);
            assert_eq!(cache.get_ref_or_guard(&i).ok().copied(), Some(i));
        }
        let small = 3;
        cache.retain(|&key, &val| val > small && key > small);
        for i in ranges.clone() {
            let actual = cache.get(&i);
            if i > small {
                assert!(actual.is_some());
                assert_eq!(*actual.unwrap(), i);
            } else {
                assert!(actual.is_none());
            }
        }
        let big = 7;
        cache.retain(|&key, &val| val < big && key < big);
        for i in ranges {
            let actual = cache.get(&i);
            if i > small && i < big {
                assert!(actual.is_some());
                assert_eq!(*actual.unwrap(), i);
            } else {
                assert!(actual.is_none());
            }
        }
    }

    #[tokio::test]
    async fn test_retain_sync() {
        use crate::sync::*;
        let cache = Cache::<u64, u64>::new(100);
        let ranges = 0..10;
        for i in ranges.clone() {
            let GuardResult::Guard(guard) = cache.get_value_or_guard(&i, None) else {
                panic!();
            };
            guard.insert(i).unwrap();
            let GuardResult::Value(v) = cache.get_value_or_guard(&i, None) else {
                panic!();
            };
            assert_eq!(v, i);
        }
        let small = 4;
        cache.retain(|&key, &val| val > small && key > small);
        for i in ranges.clone() {
            let actual = cache.get(&i);
            if i > small {
                assert!(actual.is_some());
                assert_eq!(actual.unwrap(), i);
            } else {
                assert!(actual.is_none());
            }
        }
        let big = 8;
        cache.retain(|&key, &val| val < big && key < big);
        for i in ranges {
            let actual = cache.get(&i);
            if i > small && i < big {
                assert!(actual.is_some());
                assert_eq!(actual.unwrap(), i);
            } else {
                assert!(actual.is_none());
            }
        }
    }

    #[test]
    #[cfg_attr(miri, ignore)]
    fn test_value_or_guard() {
        use crate::sync::*;
        use rand::prelude::*;
        for _i in 0..2000 {
            dbg!(_i);
            let mut entered = AtomicUsize::default();
            let cache = sync::Cache::<(u64, u64), u64>::new(100);
            const THREADS: usize = 100;
            let wg = std::sync::Barrier::new(THREADS);
            let solve_at = rand::rng().random_range(0..THREADS);
            std::thread::scope(|s| {
                for _ in 0..THREADS {
                    s.spawn(|| {
                        wg.wait();
                        loop {
                            match cache.get_value_or_guard(&(1, 1), Some(Duration::from_millis(1)))
                            {
                                GuardResult::Value(v) => assert_eq!(v, 1),
                                GuardResult::Guard(g) => {
                                    let before =
                                        entered.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                                    if before == solve_at {
                                        g.insert(1).unwrap();
                                    }
                                }
                                GuardResult::Timeout => continue,
                            }
                            break;
                        }
                    });
                }
            });
            assert_eq!(*entered.get_mut(), solve_at + 1);
        }
    }

    #[tokio::test(flavor = "multi_thread")]
    #[cfg_attr(miri, ignore)]
    async fn test_get_or_insert_async() {
        use rand::prelude::*;
        for _i in 0..5000 {
            dbg!(_i);
            let entered = Arc::new(AtomicUsize::default());
            let cache = Arc::new(sync::Cache::<(u64, u64), u64>::new(100));
            const TASKS: usize = 100;
            let wg = Arc::new(tokio::sync::Barrier::new(TASKS));
            let solve_at = rand::rng().random_range(0..TASKS);
            let mut tasks = Vec::new();
            for _ in 0..TASKS {
                let cache = cache.clone();
                let wg = wg.clone();
                let entered = entered.clone();
                let task = tokio::spawn(async move {
                    wg.wait().await;
                    let result = cache
                        .get_or_insert_async(&(1, 1), async {
                            let before = entered.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                            if before == solve_at {
                                Ok(1)
                            } else {
                                Err(())
                            }
                        })
                        .await;
                    assert!(matches!(result, Ok(1) | Err(())));
                });
                tasks.push(task);
            }
            for task in tasks {
                task.await.unwrap();
            }
            assert_eq!(cache.get(&(1, 1)), Some(1));
            assert_eq!(
                entered.load(std::sync::atomic::Ordering::Relaxed),
                solve_at + 1
            );
        }
    }

    #[tokio::test(flavor = "multi_thread")]
    #[cfg_attr(miri, ignore)]
    async fn test_value_or_guard_async() {
        use rand::prelude::*;
        for _i in 0..5000 {
            dbg!(_i);
            let entered = Arc::new(AtomicUsize::default());
            let cache = Arc::new(sync::Cache::<(u64, u64), u64>::new(100));
            const TASKS: usize = 100;
            let wg = Arc::new(tokio::sync::Barrier::new(TASKS));
            let solve_at = rand::rng().random_range(0..TASKS);
            let mut tasks = Vec::new();
            for _ in 0..TASKS {
                let cache = cache.clone();
                let wg = wg.clone();
                let entered = entered.clone();
                let task = tokio::spawn(async move {
                    wg.wait().await;
                    loop {
                        match tokio::time::timeout(
                            Duration::from_millis(1),
                            cache.get_value_or_guard_async(&(1, 1)),
                        )
                        .await
                        {
                            Ok(Ok(r)) => assert_eq!(r, 1),
                            Ok(Err(g)) => {
                                let before =
                                    entered.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                                if before == solve_at {
                                    g.insert(1).unwrap();
                                }
                            }
                            Err(_) => continue,
                        }
                        break;
                    }
                });
                tasks.push(task);
            }
            for task in tasks {
                task.await.unwrap();
            }
            assert_eq!(cache.get(&(1, 1)), Some(1));
            assert_eq!(
                entered.load(std::sync::atomic::Ordering::Relaxed),
                solve_at + 1
            );
        }
    }
}