Skip to main content

rok_cache/drivers/
memory.rs

1use std::{
2    sync::Arc,
3    time::{Duration, Instant},
4};
5
6use dashmap::DashMap;
7
8use crate::CacheError;
9
10#[derive(Clone, Default)]
11pub struct MemoryDriver {
12    store: Arc<DashMap<String, (String, Option<Instant>)>>,
13}
14
15impl MemoryDriver {
16    pub fn new() -> Self {
17        Self::default()
18    }
19
20    pub async fn get(&self, key: &str) -> Result<Option<String>, CacheError> {
21        match self.store.get(key) {
22            None => Ok(None),
23            Some(entry) => {
24                let (value, expiry) = entry.value();
25                if let Some(exp) = expiry {
26                    if Instant::now() >= *exp {
27                        drop(entry);
28                        self.store.remove(key);
29                        return Ok(None);
30                    }
31                }
32                Ok(Some(value.clone()))
33            }
34        }
35    }
36
37    pub async fn set(
38        &self,
39        key: &str,
40        value: String,
41        ttl: Option<Duration>,
42    ) -> Result<(), CacheError> {
43        let expiry = ttl.map(|d| Instant::now() + d);
44        self.store.insert(key.to_string(), (value, expiry));
45        Ok(())
46    }
47
48    pub async fn forget(&self, key: &str) -> Result<(), CacheError> {
49        self.store.remove(key);
50        Ok(())
51    }
52
53    pub async fn flush(&self) -> Result<(), CacheError> {
54        self.store.clear();
55        Ok(())
56    }
57}