Skip to main content

yimi_rutool/cache/
memory_cache.rs

1//! In-memory cache implementation with TTL support
2//!
3//! This module provides a thread-safe in-memory cache with time-to-live (TTL)
4//! functionality, inspired by Hutool's CacheUtil.
5
6use crate::error::{Error, Result};
7use std::collections::HashMap;
8use std::sync::{Arc, RwLock};
9use std::time::{Duration, Instant};
10
11/// Cache entry with value and expiration time
12#[derive(Debug, Clone)]
13struct CacheEntry<V> {
14    value: V,
15    expires_at: Option<Instant>,
16    created_at: Instant,
17    access_count: u64,
18    last_accessed: Instant,
19}
20
21impl<V> CacheEntry<V> {
22    fn new(value: V, ttl: Option<Duration>) -> Self {
23        let now = Instant::now();
24        Self {
25            value,
26            expires_at: ttl.map(|duration| now + duration),
27            created_at: now,
28            access_count: 0,
29            last_accessed: now,
30        }
31    }
32
33    fn is_expired(&self) -> bool {
34        self.expires_at
35            .map_or(false, |expires_at| Instant::now() > expires_at)
36    }
37
38    fn access(&mut self) -> &V {
39        self.access_count += 1;
40        self.last_accessed = Instant::now();
41        &self.value
42    }
43}
44
45/// Thread-safe in-memory cache with TTL support
46///
47/// # Examples
48///
49/// ```rust
50/// use yimi_rutool::cache::MemoryCache;
51/// use std::time::Duration;
52///
53/// let cache = MemoryCache::new();
54///
55/// // Store value without TTL
56/// cache.put("key1".to_string(), "value1".to_string()).unwrap();
57///
58/// // Store value with TTL
59/// cache.put_with_ttl("key2".to_string(), "value2".to_string(), Duration::from_secs(60)).unwrap();
60///
61/// // Retrieve values
62/// assert_eq!(cache.get(&"key1".to_string()).unwrap(), Some("value1".to_string()));
63/// assert_eq!(cache.get(&"key2".to_string()).unwrap(), Some("value2".to_string()));
64/// ```
65pub struct MemoryCache<K, V>
66where
67    K: Clone + Eq + std::hash::Hash,
68    V: Clone,
69{
70    data: Arc<RwLock<HashMap<K, CacheEntry<V>>>>,
71    default_ttl: Option<Duration>,
72    max_size: Option<usize>,
73}
74
75impl<K, V> MemoryCache<K, V>
76where
77    K: Clone + Eq + std::hash::Hash,
78    V: Clone,
79{
80    /// Create a new cache with no size limit and no default TTL
81    ///
82    /// # Examples
83    ///
84    /// ```rust
85    /// use yimi_rutool::cache::MemoryCache;
86    ///
87    /// let cache: MemoryCache<String, i32> = MemoryCache::new();
88    /// ```
89    pub fn new() -> Self {
90        Self {
91            data: Arc::new(RwLock::new(HashMap::new())),
92            default_ttl: None,
93            max_size: None,
94        }
95    }
96
97    /// Create a new cache with default TTL
98    ///
99    /// # Examples
100    ///
101    /// ```rust
102    /// use yimi_rutool::cache::MemoryCache;
103    /// use std::time::Duration;
104    ///
105    /// let cache: MemoryCache<String, i32> = MemoryCache::with_ttl(Duration::from_secs(300));
106    /// ```
107    pub fn with_ttl(default_ttl: Duration) -> Self {
108        Self {
109            data: Arc::new(RwLock::new(HashMap::new())),
110            default_ttl: Some(default_ttl),
111            max_size: None,
112        }
113    }
114
115    /// Create a new cache with maximum size limit
116    ///
117    /// # Examples
118    ///
119    /// ```rust
120    /// use yimi_rutool::cache::MemoryCache;
121    ///
122    /// let cache: MemoryCache<String, i32> = MemoryCache::with_max_size(1000);
123    /// ```
124    pub fn with_max_size(max_size: usize) -> Self {
125        Self {
126            data: Arc::new(RwLock::new(HashMap::new())),
127            default_ttl: None,
128            max_size: Some(max_size),
129        }
130    }
131
132    /// Create a new cache with both default TTL and maximum size
133    ///
134    /// # Examples
135    ///
136    /// ```rust
137    /// use yimi_rutool::cache::MemoryCache;
138    /// use std::time::Duration;
139    ///
140    /// let cache: MemoryCache<String, i32> = MemoryCache::with_ttl_and_size(
141    ///     Duration::from_secs(300),
142    ///     1000
143    /// );
144    /// ```
145    pub fn with_ttl_and_size(default_ttl: Duration, max_size: usize) -> Self {
146        Self {
147            data: Arc::new(RwLock::new(HashMap::new())),
148            default_ttl: Some(default_ttl),
149            max_size: Some(max_size),
150        }
151    }
152
153    /// Store a value in the cache with default TTL
154    ///
155    /// # Examples
156    ///
157    /// ```rust
158    /// use yimi_rutool::cache::MemoryCache;
159    ///
160    /// let cache = MemoryCache::new();
161    /// cache.put("key".to_string(), "value".to_string()).unwrap();
162    /// ```
163    pub fn put(&self, key: K, value: V) -> Result<()> {
164        let entry = CacheEntry::new(value, self.default_ttl);
165        self.put_entry(key, entry)
166    }
167
168    /// Store a value in the cache with specific TTL
169    ///
170    /// # Examples
171    ///
172    /// ```rust
173    /// use yimi_rutool::cache::MemoryCache;
174    /// use std::time::Duration;
175    ///
176    /// let cache = MemoryCache::new();
177    /// cache.put_with_ttl("key", "value", Duration::from_secs(60)).unwrap();
178    /// ```
179    pub fn put_with_ttl(&self, key: K, value: V, ttl: Duration) -> Result<()> {
180        let entry = CacheEntry::new(value, Some(ttl));
181        self.put_entry(key, entry)
182    }
183
184    /// Store a value in the cache without TTL (never expires)
185    ///
186    /// # Examples
187    ///
188    /// ```rust
189    /// use yimi_rutool::cache::MemoryCache;
190    ///
191    /// let cache = MemoryCache::new();
192    /// cache.put_permanent("key".to_string(), "value".to_string()).unwrap();
193    /// ```
194    pub fn put_permanent(&self, key: K, value: V) -> Result<()> {
195        let entry = CacheEntry::new(value, None);
196        self.put_entry(key, entry)
197    }
198
199    fn put_entry(&self, key: K, entry: CacheEntry<V>) -> Result<()> {
200        let mut data = self
201            .data
202            .write()
203            .map_err(|_| Error::concurrency("Failed to acquire write lock".to_string()))?;
204
205        // Check size limit and evict if necessary
206        if let Some(max_size) = self.max_size {
207            while data.len() >= max_size {
208                // Remove oldest entry
209                if let Some(oldest_key) = self.find_oldest_key(&data) {
210                    data.remove(&oldest_key);
211                } else {
212                    break;
213                }
214            }
215        }
216
217        data.insert(key, entry);
218        Ok(())
219    }
220
221    fn find_oldest_key(&self, data: &HashMap<K, CacheEntry<V>>) -> Option<K> {
222        data.iter()
223            .min_by_key(|(_, entry)| entry.created_at)
224            .map(|(key, _)| key.clone())
225    }
226
227    /// Retrieve a value from the cache
228    ///
229    /// # Examples
230    ///
231    /// ```rust
232    /// use yimi_rutool::cache::MemoryCache;
233    ///
234    /// let cache = MemoryCache::new();
235    /// cache.put("key".to_string(), "value".to_string()).unwrap();
236    ///
237    /// let result = cache.get(&"key".to_string()).unwrap();
238    /// assert_eq!(result, Some("value".to_string()));
239    /// ```
240    pub fn get(&self, key: &K) -> Result<Option<V>> {
241        let mut data = self
242            .data
243            .write()
244            .map_err(|_| Error::concurrency("Failed to acquire write lock".to_string()))?;
245
246        if let Some(entry) = data.get_mut(key) {
247            if entry.is_expired() {
248                data.remove(key);
249                Ok(None)
250            } else {
251                Ok(Some(entry.access().clone()))
252            }
253        } else {
254            Ok(None)
255        }
256    }
257
258    /// Check if a key exists in the cache (without updating access time)
259    ///
260    /// # Examples
261    ///
262    /// ```rust
263    /// use yimi_rutool::cache::MemoryCache;
264    ///
265    /// let cache = MemoryCache::new();
266    /// cache.put("key".to_string(), "value".to_string()).unwrap();
267    ///
268    /// assert!(cache.contains_key(&"key".to_string()).unwrap());
269    /// assert!(!cache.contains_key(&"nonexistent".to_string()).unwrap());
270    /// ```
271    pub fn contains_key(&self, key: &K) -> Result<bool> {
272        let data = self
273            .data
274            .read()
275            .map_err(|_| Error::concurrency("Failed to acquire read lock".to_string()))?;
276
277        if let Some(entry) = data.get(key) {
278            Ok(!entry.is_expired())
279        } else {
280            Ok(false)
281        }
282    }
283
284    /// Remove a value from the cache
285    ///
286    /// # Examples
287    ///
288    /// ```rust
289    /// use yimi_rutool::cache::MemoryCache;
290    ///
291    /// let cache = MemoryCache::new();
292    /// cache.put("key".to_string(), "value".to_string()).unwrap();
293    ///
294    /// let removed = cache.remove(&"key".to_string()).unwrap();
295    /// assert_eq!(removed, Some("value".to_string()));
296    /// ```
297    pub fn remove(&self, key: &K) -> Result<Option<V>> {
298        let mut data = self
299            .data
300            .write()
301            .map_err(|_| Error::concurrency("Failed to acquire write lock".to_string()))?;
302
303        Ok(data.remove(key).map(|entry| entry.value))
304    }
305
306    /// Clear all entries from the cache
307    ///
308    /// # Examples
309    ///
310    /// ```rust
311    /// use yimi_rutool::cache::MemoryCache;
312    ///
313    /// let cache = MemoryCache::new();
314    /// cache.put("key1".to_string(), "value1".to_string()).unwrap();
315    /// cache.put("key2".to_string(), "value2".to_string()).unwrap();
316    ///
317    /// cache.clear().unwrap();
318    /// assert_eq!(cache.size().unwrap(), 0);
319    /// ```
320    pub fn clear(&self) -> Result<()> {
321        let mut data = self
322            .data
323            .write()
324            .map_err(|_| Error::concurrency("Failed to acquire write lock".to_string()))?;
325
326        data.clear();
327        Ok(())
328    }
329
330    /// Get the number of entries in the cache
331    ///
332    /// # Examples
333    ///
334    /// ```rust
335    /// use yimi_rutool::cache::MemoryCache;
336    ///
337    /// let cache = MemoryCache::new();
338    /// cache.put("key1".to_string(), "value1".to_string()).unwrap();
339    /// cache.put("key2".to_string(), "value2".to_string()).unwrap();
340    ///
341    /// assert_eq!(cache.size().unwrap(), 2);
342    /// ```
343    pub fn size(&self) -> Result<usize> {
344        let data = self
345            .data
346            .read()
347            .map_err(|_| Error::concurrency("Failed to acquire read lock".to_string()))?;
348
349        Ok(data.len())
350    }
351
352    /// Check if the cache is empty
353    ///
354    /// # Examples
355    ///
356    /// ```rust
357    /// use yimi_rutool::cache::MemoryCache;
358    ///
359    /// let cache = MemoryCache::new();
360    /// assert!(cache.is_empty().unwrap());
361    ///
362    /// cache.put("key".to_string(), "value".to_string()).unwrap();
363    /// assert!(!cache.is_empty().unwrap());
364    /// ```
365    pub fn is_empty(&self) -> Result<bool> {
366        Ok(self.size()? == 0)
367    }
368
369    /// Remove all expired entries from the cache
370    ///
371    /// # Examples
372    ///
373    /// ```rust
374    /// use yimi_rutool::cache::MemoryCache;
375    /// use std::time::Duration;
376    ///
377    /// let cache = MemoryCache::new();
378    /// cache.put_with_ttl("key", "value", Duration::from_millis(1)).unwrap();
379    ///
380    /// std::thread::sleep(Duration::from_millis(10));
381    /// let removed = cache.cleanup_expired().unwrap();
382    /// assert_eq!(removed, 1);
383    /// ```
384    pub fn cleanup_expired(&self) -> Result<usize> {
385        let mut data = self
386            .data
387            .write()
388            .map_err(|_| Error::concurrency("Failed to acquire write lock".to_string()))?;
389
390        let expired_keys: Vec<K> = data
391            .iter()
392            .filter(|(_, entry)| entry.is_expired())
393            .map(|(key, _)| key.clone())
394            .collect();
395
396        let count = expired_keys.len();
397        for key in expired_keys {
398            data.remove(&key);
399        }
400
401        Ok(count)
402    }
403
404    /// Get all keys in the cache (excluding expired ones)
405    ///
406    /// # Examples
407    ///
408    /// ```rust
409    /// use yimi_rutool::cache::MemoryCache;
410    ///
411    /// let cache = MemoryCache::new();
412    /// cache.put("key1".to_string(), "value1".to_string()).unwrap();
413    /// cache.put("key2".to_string(), "value2".to_string()).unwrap();
414    ///
415    /// let keys = cache.keys().unwrap();
416    /// assert_eq!(keys.len(), 2);
417    /// ```
418    pub fn keys(&self) -> Result<Vec<K>> {
419        let data = self
420            .data
421            .read()
422            .map_err(|_| Error::concurrency("Failed to acquire read lock".to_string()))?;
423
424        let keys: Vec<K> = data
425            .iter()
426            .filter(|(_, entry)| !entry.is_expired())
427            .map(|(key, _)| key.clone())
428            .collect();
429
430        Ok(keys)
431    }
432
433    /// Get cache statistics
434    ///
435    /// # Examples
436    ///
437    /// ```rust
438    /// use yimi_rutool::cache::MemoryCache;
439    ///
440    /// let cache = MemoryCache::new();
441    /// cache.put("key1".to_string(), "value1".to_string()).unwrap();
442    /// cache.put("key2".to_string(), "value2".to_string()).unwrap();
443    ///
444    /// let stats = cache.stats().unwrap();
445    /// assert_eq!(stats.total_entries, 2);
446    /// ```
447    pub fn stats(&self) -> Result<CacheStats> {
448        let data = self
449            .data
450            .read()
451            .map_err(|_| Error::concurrency("Failed to acquire read lock".to_string()))?;
452
453        let total_entries = data.len();
454        let expired_entries = data.values().filter(|entry| entry.is_expired()).count();
455        let active_entries = total_entries - expired_entries;
456
457        let total_access_count: u64 = data.values().map(|entry| entry.access_count).sum();
458        let avg_access_count = if total_entries > 0 {
459            // Use safe conversion for better precision
460            if total_entries == 0 {
461                0.0
462            } else {
463                (total_access_count as f64) / (total_entries as f64)
464            }
465        } else {
466            0.0
467        };
468
469        Ok(CacheStats {
470            total_entries,
471            active_entries,
472            expired_entries,
473            total_access_count,
474            avg_access_count,
475        })
476    }
477
478    /// Get or compute a value for the given key
479    ///
480    /// # Examples
481    ///
482    /// ```rust
483    /// use yimi_rutool::cache::MemoryCache;
484    ///
485    /// let cache = MemoryCache::new();
486    ///
487    /// let value = cache.get_or_compute("key".to_string(), || "computed_value".to_string()).unwrap();
488    /// assert_eq!(value, "computed_value");
489    ///
490    /// // Second call should return cached value
491    /// let cached_value = cache.get_or_compute("key".to_string(), || "new_value".to_string()).unwrap();
492    /// assert_eq!(cached_value, "computed_value");
493    /// ```
494    pub fn get_or_compute<F>(&self, key: K, compute_fn: F) -> Result<V>
495    where
496        F: FnOnce() -> V,
497    {
498        // Try to get existing value first
499        if let Some(value) = self.get(&key)? {
500            return Ok(value);
501        }
502
503        // Compute and store new value
504        let value = compute_fn();
505        self.put(key.clone(), value.clone())?;
506        Ok(value)
507    }
508
509    /// Get or compute a value with TTL for the given key
510    ///
511    /// # Examples
512    ///
513    /// ```rust
514    /// use yimi_rutool::cache::MemoryCache;
515    /// use std::time::Duration;
516    ///
517    /// let cache = MemoryCache::new();
518    ///
519    /// let value = cache.get_or_compute_with_ttl(
520    ///     "key",
521    ///     || "computed_value".to_string(),
522    ///     Duration::from_secs(60)
523    /// ).unwrap();
524    /// assert_eq!(value, "computed_value");
525    /// ```
526    pub fn get_or_compute_with_ttl<F>(&self, key: K, compute_fn: F, ttl: Duration) -> Result<V>
527    where
528        F: FnOnce() -> V,
529    {
530        // Try to get existing value first
531        if let Some(value) = self.get(&key)? {
532            return Ok(value);
533        }
534
535        // Compute and store new value with TTL
536        let value = compute_fn();
537        self.put_with_ttl(key.clone(), value.clone(), ttl)?;
538        Ok(value)
539    }
540}
541
542impl<K, V> Default for MemoryCache<K, V>
543where
544    K: Clone + Eq + std::hash::Hash,
545    V: Clone,
546{
547    fn default() -> Self {
548        Self::new()
549    }
550}
551
552impl<K, V> Clone for MemoryCache<K, V>
553where
554    K: Clone + Eq + std::hash::Hash,
555    V: Clone,
556{
557    fn clone(&self) -> Self {
558        Self {
559            data: Arc::clone(&self.data),
560            default_ttl: self.default_ttl,
561            max_size: self.max_size,
562        }
563    }
564}
565
566/// Cache statistics
567#[derive(Debug, Clone)]
568pub struct CacheStats {
569    /// Total number of entries (including expired)
570    pub total_entries: usize,
571    /// Number of active (non-expired) entries
572    pub active_entries: usize,
573    /// Number of expired entries
574    pub expired_entries: usize,
575    /// Total access count across all entries
576    pub total_access_count: u64,
577    /// Average access count per entry
578    pub avg_access_count: f64,
579}
580
581#[cfg(test)]
582mod tests {
583    use super::*;
584    use std::thread;
585    use std::time::Duration;
586
587    #[test]
588    fn test_basic_operations() {
589        let cache: MemoryCache<String, String> = MemoryCache::new();
590
591        // Test put and get
592        cache.put("key1".to_string(), "value1".to_string()).unwrap();
593        assert_eq!(
594            cache.get(&"key1".to_string()).unwrap(),
595            Some("value1".to_string())
596        );
597
598        // Test contains_key
599        assert!(cache.contains_key(&"key1".to_string()).unwrap());
600        assert!(!cache.contains_key(&"nonexistent".to_string()).unwrap());
601
602        // Test size
603        assert_eq!(cache.size().unwrap(), 1);
604        assert!(!cache.is_empty().unwrap());
605
606        // Test remove
607        let removed = cache.remove(&"key1".to_string()).unwrap();
608        assert_eq!(removed, Some("value1".to_string()));
609        assert_eq!(cache.get(&"key1".to_string()).unwrap(), None);
610        assert!(cache.is_empty().unwrap());
611    }
612
613    #[test]
614    fn test_ttl() {
615        let cache: MemoryCache<String, String> = MemoryCache::new();
616
617        // Store with short TTL
618        cache
619            .put_with_ttl(
620                "key".to_string(),
621                "value".to_string(),
622                Duration::from_millis(10),
623            )
624            .unwrap();
625        assert_eq!(
626            cache.get(&"key".to_string()).unwrap(),
627            Some("value".to_string())
628        );
629
630        // Wait for expiration
631        thread::sleep(Duration::from_millis(15));
632        assert_eq!(cache.get(&"key".to_string()).unwrap(), None);
633    }
634
635    #[test]
636    fn test_default_ttl() {
637        let cache = MemoryCache::with_ttl(Duration::from_millis(10));
638
639        cache.put("key".to_string(), "value".to_string()).unwrap();
640        assert_eq!(
641            cache.get(&"key".to_string()).unwrap(),
642            Some("value".to_string())
643        );
644
645        thread::sleep(Duration::from_millis(15));
646        assert_eq!(cache.get(&"key".to_string()).unwrap(), None);
647    }
648
649    #[test]
650    fn test_permanent_storage() {
651        let cache = MemoryCache::with_ttl(Duration::from_millis(10));
652
653        cache
654            .put_permanent("key".to_string(), "value".to_string())
655            .unwrap();
656        thread::sleep(Duration::from_millis(15));
657
658        // Should still be available
659        assert_eq!(
660            cache.get(&"key".to_string()).unwrap(),
661            Some("value".to_string())
662        );
663    }
664
665    #[test]
666    fn test_max_size() {
667        let cache: MemoryCache<String, String> = MemoryCache::with_max_size(2);
668
669        cache.put("key1".to_string(), "value1".to_string()).unwrap();
670        cache.put("key2".to_string(), "value2".to_string()).unwrap();
671        cache.put("key3".to_string(), "value3".to_string()).unwrap(); // Should evict key1
672
673        assert_eq!(cache.size().unwrap(), 2);
674        assert_eq!(cache.get(&"key1".to_string()).unwrap(), None); // Evicted
675        assert_eq!(
676            cache.get(&"key2".to_string()).unwrap(),
677            Some("value2".to_string())
678        );
679        assert_eq!(
680            cache.get(&"key3".to_string()).unwrap(),
681            Some("value3".to_string())
682        );
683    }
684
685    #[test]
686    fn test_cleanup_expired() {
687        let cache: MemoryCache<String, String> = MemoryCache::new();
688
689        cache
690            .put_with_ttl(
691                "key1".to_string(),
692                "value1".to_string(),
693                Duration::from_millis(10),
694            )
695            .unwrap();
696        cache
697            .put_permanent("key2".to_string(), "value2".to_string())
698            .unwrap();
699
700        thread::sleep(Duration::from_millis(15));
701
702        let removed = cache.cleanup_expired().unwrap();
703        assert_eq!(removed, 1);
704        assert_eq!(cache.size().unwrap(), 1);
705        assert_eq!(
706            cache.get(&"key2".to_string()).unwrap(),
707            Some("value2".to_string())
708        );
709    }
710
711    #[test]
712    fn test_get_or_compute() {
713        let cache: MemoryCache<String, String> = MemoryCache::new();
714
715        // First call should compute
716        let value = cache
717            .get_or_compute("key".to_string(), || "computed".to_string())
718            .unwrap();
719        assert_eq!(value, "computed".to_string());
720
721        // Second call should return cached value
722        let cached = cache
723            .get_or_compute("key".to_string(), || "new_computed".to_string())
724            .unwrap();
725        assert_eq!(cached, "computed".to_string());
726    }
727
728    #[test]
729    fn test_stats() {
730        let cache: MemoryCache<String, String> = MemoryCache::new();
731
732        cache.put("key1".to_string(), "value1".to_string()).unwrap();
733        cache.put("key2".to_string(), "value2".to_string()).unwrap();
734        cache.get(&"key1".to_string()).unwrap(); // Access once
735        cache.get(&"key1".to_string()).unwrap(); // Access twice
736
737        let stats = cache.stats().unwrap();
738        assert_eq!(stats.total_entries, 2);
739        assert_eq!(stats.active_entries, 2);
740        assert_eq!(stats.expired_entries, 0);
741        assert_eq!(stats.total_access_count, 2);
742        assert_eq!(stats.avg_access_count, 1.0);
743    }
744
745    #[test]
746    fn test_keys() {
747        let cache: MemoryCache<String, String> = MemoryCache::new();
748
749        cache.put("key1".to_string(), "value1".to_string()).unwrap();
750        cache.put("key2".to_string(), "value2".to_string()).unwrap();
751        cache
752            .put_with_ttl(
753                "key3".to_string(),
754                "value3".to_string(),
755                Duration::from_millis(1),
756            )
757            .unwrap();
758
759        thread::sleep(Duration::from_millis(10));
760
761        let keys = cache.keys().unwrap();
762        assert_eq!(keys.len(), 2);
763        assert!(keys.contains(&"key1".to_string()));
764        assert!(keys.contains(&"key2".to_string()));
765        assert!(!keys.contains(&"key3".to_string())); // Expired
766    }
767
768    #[test]
769    fn test_clear() {
770        let cache: MemoryCache<String, String> = MemoryCache::new();
771
772        cache.put("key1".to_string(), "value1".to_string()).unwrap();
773        cache.put("key2".to_string(), "value2".to_string()).unwrap();
774
775        cache.clear().unwrap();
776        assert!(cache.is_empty().unwrap());
777    }
778
779    #[test]
780    fn test_clone() {
781        let cache1 = MemoryCache::new();
782        cache1.put("key".to_string(), "value".to_string()).unwrap();
783
784        let cache2 = cache1.clone();
785        assert_eq!(
786            cache2.get(&"key".to_string()).unwrap(),
787            Some("value".to_string())
788        );
789
790        // They should share the same underlying data
791        cache2
792            .put("key2".to_string(), "value2".to_string())
793            .unwrap();
794        assert_eq!(
795            cache1.get(&"key2".to_string()).unwrap(),
796            Some("value2".to_string())
797        );
798    }
799}