cached 3.0.0-rc.1

Generic cache implementations and simplified function memoization
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
//! Proves that the `#[concurrent_cached]` autoref shim (`cached::__set_dispatch`)
//! picks the borrowed `SerializeCached::cache_set_ref` arm for stores that implement
//! `SerializeCached`, and falls back to the owned `ConcurrentCached::cache_set` (cloning
//! the value) for stores that do not. Clone counts are the observable signal.
//!
//! Part 3: sync clone-elision proof with custom in-memory stores.
//! Part 4: async clone-elision proof with custom `SerializeCachedAsync` vs
//! `ConcurrentCachedAsync`-only stores (0 clones on the borrowed arm, 1 on the fallback).

#![cfg(feature = "proc_macro")]

use std::sync::atomic::{AtomicUsize, Ordering};

static CLONES: AtomicUsize = AtomicUsize::new(0);

/// A value type that counts every Clone invocation via the global `CLONES` counter.
#[derive(PartialEq, Debug)]
struct Counted(u32);

impl Clone for Counted {
    fn clone(&self) -> Self {
        CLONES.fetch_add(1, Ordering::SeqCst);
        Counted(self.0)
    }
}

// Manual serialization: just store the u32 as a string. No serde needed.
fn counted_to_string(v: &Counted) -> String {
    v.0.to_string()
}

fn counted_from_str(s: &str) -> Counted {
    Counted(s.parse().expect("parse Counted"))
}

// ---------------------------------------------------------------------------
// SerStore: implements both ConcurrentCached AND SerializeCached.
// Backing storage is HashMap<u32, String>; cache_set_ref serializes from &V
// without ever cloning Counted.
// ---------------------------------------------------------------------------

mod stores {
    use super::{Counted, counted_from_str, counted_to_string};
    use cached::{ConcurrentCacheBase, ConcurrentCached, SerializeCached};
    use std::collections::HashMap;
    use std::convert::Infallible;
    use std::sync::Mutex;

    pub struct SerStore {
        map: Mutex<HashMap<u32, String>>,
    }

    impl SerStore {
        pub fn new() -> Self {
            SerStore {
                map: Mutex::new(HashMap::new()),
            }
        }
    }

    impl ConcurrentCacheBase for SerStore {
        type Error = Infallible;
    }

    impl ConcurrentCached<u32, Counted> for SerStore {
        fn cache_get(&self, k: &u32) -> Result<Option<Counted>, Infallible> {
            let map = self.map.lock().unwrap();
            Ok(map.get(k).map(|s| counted_from_str(s)))
        }

        fn cache_set(&self, k: u32, v: Counted) -> Result<Option<Counted>, Infallible> {
            let s = counted_to_string(&v);
            let mut map = self.map.lock().unwrap();
            Ok(map.insert(k, s).map(|s| counted_from_str(&s)))
        }

        fn cache_remove(&self, k: &u32) -> Result<Option<Counted>, Infallible> {
            let mut map = self.map.lock().unwrap();
            Ok(map.remove(k).map(|s| counted_from_str(&s)))
        }

        fn cache_remove_entry(&self, k: &u32) -> Result<Option<(u32, Counted)>, Infallible> {
            let mut map = self.map.lock().unwrap();
            Ok(map.remove_entry(k).map(|(k, s)| (k, counted_from_str(&s))))
        }

        fn cache_clear(&self) -> Result<(), Infallible> {
            self.map.lock().unwrap().clear();
            Ok(())
        }

        fn cache_reset(&self) -> Result<(), Infallible> {
            self.cache_clear()
        }
    }

    impl SerializeCached<u32, Counted> for SerStore {
        /// Serialize from &Counted — never clones Counted.
        fn cache_set_ref(&self, k: &u32, v: &Counted) -> Result<Option<Counted>, Infallible> {
            let s = counted_to_string(v);
            let mut map = self.map.lock().unwrap();
            Ok(map.insert(*k, s).map(|s| counted_from_str(&s)))
        }
    }

    // ---------------------------------------------------------------------------
    // OwnedStore: implements ONLY ConcurrentCached (NOT SerializeCached).
    // Backing storage is HashMap<u32, Counted>; cache_set stores the owned value.
    // Since SerializeCached is not implemented, the shim falls back to the owned
    // arm which clones the value once before calling cache_set.
    // ---------------------------------------------------------------------------

    pub struct OwnedStore {
        map: Mutex<HashMap<u32, Counted>>,
    }

    impl OwnedStore {
        pub fn new() -> Self {
            OwnedStore {
                map: Mutex::new(HashMap::new()),
            }
        }
    }

    impl ConcurrentCacheBase for OwnedStore {
        type Error = Infallible;
    }

    impl ConcurrentCached<u32, Counted> for OwnedStore {
        fn cache_get(&self, k: &u32) -> Result<Option<Counted>, Infallible> {
            // Reading requires a Clone to return an owned value from the locked map.
            // We reset CLONES before each test and only care about the set-path clone.
            let map = self.map.lock().unwrap();
            Ok(map.get(k).cloned())
        }

        fn cache_set(&self, k: u32, v: Counted) -> Result<Option<Counted>, Infallible> {
            let mut map = self.map.lock().unwrap();
            Ok(map.insert(k, v))
        }

        fn cache_remove(&self, k: &u32) -> Result<Option<Counted>, Infallible> {
            let mut map = self.map.lock().unwrap();
            Ok(map.remove(k))
        }

        fn cache_remove_entry(&self, k: &u32) -> Result<Option<(u32, Counted)>, Infallible> {
            let mut map = self.map.lock().unwrap();
            Ok(map.remove_entry(k))
        }

        fn cache_clear(&self) -> Result<(), Infallible> {
            self.map.lock().unwrap().clear();
            Ok(())
        }

        fn cache_reset(&self) -> Result<(), Infallible> {
            self.cache_clear()
        }
    }

    // OwnedStore intentionally does NOT impl SerializeCached.
}

// ---------------------------------------------------------------------------
// Memoized functions using the two stores.
// ---------------------------------------------------------------------------

mod fns {
    use super::Counted;
    use super::stores::{OwnedStore, SerStore};
    use cached::macros::concurrent_cached;

    #[concurrent_cached(
        ty = "SerStore",
        create = "{ SerStore::new() }",
        map_error = "|e| e",
        key = "u32",
        convert = "{ n }"
    )]
    pub fn via_serialize(n: u32) -> Result<Counted, std::convert::Infallible> {
        Ok(Counted(n))
    }

    #[concurrent_cached(
        ty = "OwnedStore",
        create = "{ OwnedStore::new() }",
        map_error = "|e| e",
        key = "u32",
        convert = "{ n }"
    )]
    pub fn via_owned(n: u32) -> Result<Counted, std::convert::Infallible> {
        Ok(Counted(n))
    }
}

// Serialize each clone-counting test to avoid interference from parallel test
// execution sharing the global CLONES counter.
mod clone_count_tests {
    use super::*;
    use cached::ConcurrentCached;
    use fns::{VIA_OWNED, VIA_SERIALIZE, via_owned, via_serialize};
    use std::sync::Mutex;

    // A global mutex to serialize the two clone-counting tests so they don't
    // interleave and corrupt the shared CLONES counter.
    static CLONE_TEST_LOCK: Mutex<()> = Mutex::new(());

    /// Proves the borrowed arm (SerializeCached) is taken: no Clone of Counted occurs
    /// at the set site, so CLONES stays 0 after a cache miss.
    #[test]
    fn serialize_store_skips_value_clone() {
        let _guard = CLONE_TEST_LOCK.lock().unwrap();
        CLONES.store(0, Ordering::SeqCst);
        VIA_SERIALIZE.cache_clear().unwrap();

        // First call: cache miss; body runs, result stored via cache_set_ref (&Counted).
        let v = via_serialize(7).unwrap();
        assert_eq!(v, Counted(7));

        // The borrowed setter serialized from &Counted — no Clone.
        assert_eq!(
            CLONES.load(Ordering::SeqCst),
            0,
            "SerializeCached path must not clone the value at the set site"
        );

        // Second call: cache hit; deserializes to a fresh Counted (via counted_from_str,
        // not Clone), so CLONES is still 0.
        CLONES.store(0, Ordering::SeqCst);
        let hit = via_serialize(7).unwrap();
        assert_eq!(hit, Counted(7));
        assert_eq!(
            CLONES.load(Ordering::SeqCst),
            0,
            "Cache hit on SerializeCached path must not clone"
        );
    }

    /// Proves the owned fallback arm is taken on a cache miss: the shim clones
    /// the value exactly once (to call the owned cache_set), so CLONES == 1
    /// after the first (miss) call. The hit-path clone count is an implementation
    /// detail of OwnedStore::cache_get and is not asserted here; only the
    /// returned value is checked for correctness.
    #[test]
    fn owned_store_clones_once() {
        let _guard = CLONE_TEST_LOCK.lock().unwrap();
        CLONES.store(0, Ordering::SeqCst);
        VIA_OWNED.cache_clear().unwrap();

        // First call: cache miss; body runs, result stored via owned cache_set.
        // The shim does `value.clone()` before calling cache_set.
        let v = via_owned(7).unwrap();
        assert_eq!(v, Counted(7));

        assert_eq!(
            CLONES.load(Ordering::SeqCst),
            1,
            "Owned fallback path must clone the value exactly once at the set site"
        );

        // Second call: cache hit; the set-site shim is not invoked.
        // Assert only the returned value — the clone count on the hit path is
        // an OwnedStore implementation detail and not part of the dispatch contract.
        CLONES.store(0, Ordering::SeqCst);
        let hit = via_owned(7).unwrap();
        assert_eq!(hit, Counted(7), "Cache hit must return the correct value");
    }
}

// ---------------------------------------------------------------------------
// Part 4: async custom SerializeCachedAsync store round-trip.
// ---------------------------------------------------------------------------

#[cfg(feature = "async")]
mod async_serialize_store {
    use cached::{ConcurrentCacheBase, ConcurrentCachedAsync, SerializeCachedAsync};
    use std::collections::HashMap;
    use std::convert::Infallible;
    use std::sync::Mutex;
    use std::sync::atomic::{AtomicUsize, Ordering};

    // Counts every Clone of AsyncVal, so the borrowed-vs-owned async arm is observable
    // the same way `CLONES` makes it observable for the sync path.
    static ASYNC_CLONES: AtomicUsize = AtomicUsize::new(0);

    #[derive(PartialEq, Debug)]
    pub struct AsyncVal(u32);

    impl Clone for AsyncVal {
        fn clone(&self) -> Self {
            ASYNC_CLONES.fetch_add(1, Ordering::SeqCst);
            AsyncVal(self.0)
        }
    }

    fn async_val_to_string(v: &AsyncVal) -> String {
        v.0.to_string()
    }

    fn async_val_from_str(s: &str) -> AsyncVal {
        AsyncVal(s.parse().expect("parse AsyncVal"))
    }

    pub struct AsyncSerStore {
        map: Mutex<HashMap<u32, String>>,
    }

    impl AsyncSerStore {
        pub fn new() -> Self {
            AsyncSerStore {
                map: Mutex::new(HashMap::new()),
            }
        }
    }

    impl ConcurrentCacheBase for AsyncSerStore {
        type Error = Infallible;
    }

    impl ConcurrentCachedAsync<u32, AsyncVal> for AsyncSerStore {
        fn async_cache_get(
            &self,
            k: &u32,
        ) -> impl std::future::Future<Output = Result<Option<AsyncVal>, Infallible>> + Send
        {
            let result = {
                let map = self.map.lock().unwrap();
                map.get(k).map(|s| async_val_from_str(s))
            };
            async move { Ok(result) }
        }

        fn async_cache_set(
            &self,
            k: u32,
            v: AsyncVal,
        ) -> impl std::future::Future<Output = Result<Option<AsyncVal>, Infallible>> + Send
        {
            let s = async_val_to_string(&v);
            let prev = {
                let mut map = self.map.lock().unwrap();
                map.insert(k, s)
            };
            let prev_val = prev.map(|s| async_val_from_str(&s));
            async move { Ok(prev_val) }
        }

        fn async_cache_remove(
            &self,
            k: &u32,
        ) -> impl std::future::Future<Output = Result<Option<AsyncVal>, Infallible>> + Send
        {
            let result = {
                let mut map = self.map.lock().unwrap();
                map.remove(k).map(|s| async_val_from_str(&s))
            };
            async move { Ok(result) }
        }

        fn async_cache_remove_entry(
            &self,
            k: &u32,
        ) -> impl std::future::Future<Output = Result<Option<(u32, AsyncVal)>, Infallible>> + Send
        {
            let result = {
                let mut map = self.map.lock().unwrap();
                map.remove_entry(k)
                    .map(|(k, s)| (k, async_val_from_str(&s)))
            };
            async move { Ok(result) }
        }

        fn async_cache_clear(
            &self,
        ) -> impl std::future::Future<Output = Result<(), Infallible>> + Send
        where
            Self: Sync,
        {
            self.map.lock().unwrap().clear();
            async move { Ok(()) }
        }

        fn async_cache_reset(
            &self,
        ) -> impl std::future::Future<Output = Result<(), Infallible>> + Send
        where
            Self: Sync,
        {
            self.map.lock().unwrap().clear();
            async move { Ok(()) }
        }
    }

    impl SerializeCachedAsync<u32, AsyncVal> for AsyncSerStore {
        fn async_cache_set_ref(
            &self,
            k: &u32,
            v: &AsyncVal,
        ) -> impl std::future::Future<Output = Result<Option<AsyncVal>, Infallible>> + Send
        {
            let s = async_val_to_string(v);
            let k = *k;
            let prev = {
                let mut map = self.map.lock().unwrap();
                map.insert(k, s)
            };
            let prev_val = prev.map(|s| async_val_from_str(&s));
            async move { Ok(prev_val) }
        }
    }

    // AsyncOwnedStore: implements ONLY ConcurrentCachedAsync (NOT SerializeCachedAsync).
    // Backing storage is HashMap<u32, AsyncVal>; the shim must take the owned fallback arm,
    // cloning the value once before async_cache_set.
    pub struct AsyncOwnedStore {
        map: Mutex<HashMap<u32, AsyncVal>>,
    }

    impl AsyncOwnedStore {
        pub fn new() -> Self {
            AsyncOwnedStore {
                map: Mutex::new(HashMap::new()),
            }
        }
    }

    impl ConcurrentCacheBase for AsyncOwnedStore {
        type Error = Infallible;
    }

    impl ConcurrentCachedAsync<u32, AsyncVal> for AsyncOwnedStore {
        fn async_cache_get(
            &self,
            k: &u32,
        ) -> impl std::future::Future<Output = Result<Option<AsyncVal>, Infallible>> + Send
        {
            // Reading clones to return an owned value; the clone tests reset the counter
            // immediately before the set-triggering call, so a miss's get (None) does not
            // perturb the asserted set-path count.
            let result = {
                let map = self.map.lock().unwrap();
                map.get(k).cloned()
            };
            async move { Ok(result) }
        }

        fn async_cache_set(
            &self,
            k: u32,
            v: AsyncVal,
        ) -> impl std::future::Future<Output = Result<Option<AsyncVal>, Infallible>> + Send
        {
            let prev = {
                let mut map = self.map.lock().unwrap();
                map.insert(k, v)
            };
            async move { Ok(prev) }
        }

        fn async_cache_remove(
            &self,
            k: &u32,
        ) -> impl std::future::Future<Output = Result<Option<AsyncVal>, Infallible>> + Send
        {
            let result = {
                let mut map = self.map.lock().unwrap();
                map.remove(k)
            };
            async move { Ok(result) }
        }

        fn async_cache_remove_entry(
            &self,
            k: &u32,
        ) -> impl std::future::Future<Output = Result<Option<(u32, AsyncVal)>, Infallible>> + Send
        {
            let result = {
                let mut map = self.map.lock().unwrap();
                map.remove_entry(k)
            };
            async move { Ok(result) }
        }

        fn async_cache_clear(
            &self,
        ) -> impl std::future::Future<Output = Result<(), Infallible>> + Send
        where
            Self: Sync,
        {
            self.map.lock().unwrap().clear();
            async move { Ok(()) }
        }

        fn async_cache_reset(
            &self,
        ) -> impl std::future::Future<Output = Result<(), Infallible>> + Send
        where
            Self: Sync,
        {
            self.map.lock().unwrap().clear();
            async move { Ok(()) }
        }
    }

    // AsyncOwnedStore intentionally does NOT impl SerializeCachedAsync.

    use cached::macros::concurrent_cached;

    #[concurrent_cached(
        ty = "AsyncSerStore",
        create = "{ AsyncSerStore::new() }",
        map_error = "|e| e",
        key = "u32",
        convert = "{ n }"
    )]
    async fn async_via_serialize(n: u32) -> Result<AsyncVal, Infallible> {
        Ok(AsyncVal(n))
    }

    #[concurrent_cached(
        ty = "AsyncOwnedStore",
        create = "{ AsyncOwnedStore::new() }",
        map_error = "|e| e",
        key = "u32",
        convert = "{ n }"
    )]
    async fn async_via_owned(n: u32) -> Result<AsyncVal, Infallible> {
        Ok(AsyncVal(n))
    }

    // Both async clone-counting tests share the global ASYNC_CLONES counter; serialize
    // them with serial_test so a concurrent reset cannot corrupt the asserted count.
    #[tokio::test]
    #[serial_test::serial(async_clones)]
    async fn async_serialize_store_skips_value_clone() {
        ASYNC_CLONES.store(0, Ordering::SeqCst);
        // The store is a lazily-initialized OnceCell; clear it only if a prior
        // test already initialized it, so the first call below is provably a miss.
        if let Some(store) = ASYNC_VIA_SERIALIZE.get() {
            store.async_cache_clear().await.unwrap();
        }

        // First call: cache miss, body runs, stored via async_cache_set_ref (&AsyncVal).
        let first = async_via_serialize(42).await.unwrap();
        assert_eq!(first, AsyncVal(42));

        // The borrowed async setter serialized from &AsyncVal -- no Clone at the set site.
        assert_eq!(
            ASYNC_CLONES.load(Ordering::SeqCst),
            0,
            "SerializeCachedAsync path must not clone the value at the set site"
        );

        // Second call: cache hit, body not re-run; deserializes (no Clone).
        ASYNC_CLONES.store(0, Ordering::SeqCst);
        let second = async_via_serialize(42).await.unwrap();
        assert_eq!(second, AsyncVal(42));
        assert_eq!(
            ASYNC_CLONES.load(Ordering::SeqCst),
            0,
            "Cache hit on SerializeCachedAsync path must not clone"
        );

        // A different key causes the body to run again, still via the borrowed setter.
        ASYNC_CLONES.store(0, Ordering::SeqCst);
        let other = async_via_serialize(99).await.unwrap();
        assert_eq!(other, AsyncVal(99));
        assert_eq!(ASYNC_CLONES.load(Ordering::SeqCst), 0);
    }

    /// Proves the owned async fallback arm is taken on a cache miss: the shim
    /// clones the value exactly once before async_cache_set, so ASYNC_CLONES == 1
    /// after the first (miss) call. The hit-path clone count is an implementation
    /// detail of AsyncOwnedStore::async_cache_get and is not asserted here; only
    /// the returned value is checked for correctness.
    #[tokio::test]
    #[serial_test::serial(async_clones)]
    async fn async_owned_store_clones_once() {
        ASYNC_CLONES.store(0, Ordering::SeqCst);
        // The store is a lazily-initialized OnceCell; clear it only if a prior
        // test already initialized it, so the first call below is provably a miss.
        if let Some(store) = ASYNC_VIA_OWNED.get() {
            store.async_cache_clear().await.unwrap();
        }

        // First call: cache miss; the shim does `value.clone()` before async_cache_set.
        let v = async_via_owned(7).await.unwrap();
        assert_eq!(v, AsyncVal(7));

        assert_eq!(
            ASYNC_CLONES.load(Ordering::SeqCst),
            1,
            "Owned async fallback path must clone the value exactly once at the set site"
        );

        // Second call: cache hit; the set-site shim is not invoked.
        // Assert only the returned value — the clone count on the hit path is
        // an AsyncOwnedStore implementation detail and not part of the dispatch contract.
        ASYNC_CLONES.store(0, Ordering::SeqCst);
        let hit = async_via_owned(7).await.unwrap();
        assert_eq!(hit, AsyncVal(7), "Cache hit must return the correct value");
    }
}