rok-cache 0.1.0

Cache façade for the rok ecosystem — Memory/Redis drivers, Cache::get/set/remember
Documentation
use std::{
    sync::Arc,
    time::{Duration, Instant},
};

use dashmap::DashMap;

use crate::CacheError;

#[derive(Clone, Default)]
pub struct MemoryDriver {
    store: Arc<DashMap<String, (String, Option<Instant>)>>,
}

impl MemoryDriver {
    pub fn new() -> Self {
        Self::default()
    }

    pub async fn get(&self, key: &str) -> Result<Option<String>, CacheError> {
        match self.store.get(key) {
            None => Ok(None),
            Some(entry) => {
                let (value, expiry) = entry.value();
                if let Some(exp) = expiry {
                    if Instant::now() >= *exp {
                        drop(entry);
                        self.store.remove(key);
                        return Ok(None);
                    }
                }
                Ok(Some(value.clone()))
            }
        }
    }

    pub async fn set(
        &self,
        key: &str,
        value: String,
        ttl: Option<Duration>,
    ) -> Result<(), CacheError> {
        let expiry = ttl.map(|d| Instant::now() + d);
        self.store.insert(key.to_string(), (value, expiry));
        Ok(())
    }

    pub async fn forget(&self, key: &str) -> Result<(), CacheError> {
        self.store.remove(key);
        Ok(())
    }

    pub async fn flush(&self) -> Result<(), CacheError> {
        self.store.clear();
        Ok(())
    }
}