1use crate::error::{Error, Result};
7use std::collections::HashMap;
8use std::sync::{Arc, RwLock};
9use std::time::{Duration, Instant};
10
11#[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
45pub 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 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 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 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 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 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 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 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 if let Some(max_size) = self.max_size {
207 while data.len() >= max_size {
208 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 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 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 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 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 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 pub fn is_empty(&self) -> Result<bool> {
366 Ok(self.size()? == 0)
367 }
368
369 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 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 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 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 pub fn get_or_compute<F>(&self, key: K, compute_fn: F) -> Result<V>
495 where
496 F: FnOnce() -> V,
497 {
498 if let Some(value) = self.get(&key)? {
500 return Ok(value);
501 }
502
503 let value = compute_fn();
505 self.put(key.clone(), value.clone())?;
506 Ok(value)
507 }
508
509 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 if let Some(value) = self.get(&key)? {
532 return Ok(value);
533 }
534
535 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#[derive(Debug, Clone)]
568pub struct CacheStats {
569 pub total_entries: usize,
571 pub active_entries: usize,
573 pub expired_entries: usize,
575 pub total_access_count: u64,
577 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 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 assert!(cache.contains_key(&"key1".to_string()).unwrap());
600 assert!(!cache.contains_key(&"nonexistent".to_string()).unwrap());
601
602 assert_eq!(cache.size().unwrap(), 1);
604 assert!(!cache.is_empty().unwrap());
605
606 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 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 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 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(); assert_eq!(cache.size().unwrap(), 2);
674 assert_eq!(cache.get(&"key1".to_string()).unwrap(), None); 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 let value = cache
717 .get_or_compute("key".to_string(), || "computed".to_string())
718 .unwrap();
719 assert_eq!(value, "computed".to_string());
720
721 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(); cache.get(&"key1".to_string()).unwrap(); 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())); }
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 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}