diff --git a/packages/backend-rs/src/cache/bare.rs b/packages/backend-rs/src/cache/bare.rs index d471a1d6d4..fbf914e533 100644 --- a/packages/backend-rs/src/cache/bare.rs +++ b/packages/backend-rs/src/cache/bare.rs @@ -3,6 +3,7 @@ use chrono::{DateTime, Duration, Utc}; use std::sync::Mutex; +/// Cache stored directly in memory pub struct Cache { cache: Mutex>, ttl: Option, @@ -20,6 +21,7 @@ impl Default for Cache { } impl Cache { + /// Creates a new cache object with no auto invalidation. pub const fn new() -> Self { Self { cache: Mutex::new(TimedData { @@ -30,6 +32,30 @@ impl Cache { } } + /// Creates a new cache object whose content is invalidated + /// in the specified duration. + /// + /// # Example + /// ``` + /// # use backend_rs::cache::Cache; + /// use chrono::Duration; + /// static CACHE: Cache = Cache::new_with_ttl(Duration::seconds(1)); + /// + /// fn use_cache() { + /// let data = 998244353; + /// + /// // Set cache + /// CACHE.set(data); + /// + /// // wait for the cache to expire + /// std::thread::sleep(std::time::Duration::from_millis(1100)); + /// + /// // Get cache + /// let cache = CACHE.get(); + /// + /// assert!(cache.is_none()); + /// } + /// ``` pub const fn new_with_ttl(ttl: Duration) -> Self { Self { cache: Mutex::new(TimedData { @@ -40,6 +66,30 @@ impl Cache { } } + /// Sets a cache. This function overwrites the existing data. + /// + /// # Example + /// ``` + /// # use backend_rs::cache::Cache; + /// static CACHE: Cache = Cache::new(); + /// + /// fn use_cache() { + /// let data = 998244353; + /// + /// // Set cache + /// CACHE.set(data); + /// + /// // Get cache + /// let cache = CACHE.get(); + /// + /// if let Some(cached_data) = cache { + /// println!("found a cached value"); + /// assert_eq!(data, cached_data) + /// } else { + /// println!("cache not found"); + /// } + /// } + /// ``` pub fn set(&self, value: T) { if self.ttl.is_none() { let _ = self.cache.lock().map(|mut cache| cache.value = Some(value)); @@ -53,6 +103,7 @@ impl Cache { } } + /// Gets a cache. Returns [`None`] is the cache is not set or expired. pub fn get(&self) -> Option { let data = self.cache.lock().ok()?; diff --git a/packages/backend-rs/src/cache/mod.rs b/packages/backend-rs/src/cache/mod.rs index 3b3d04c198..c68f689a4a 100644 --- a/packages/backend-rs/src/cache/mod.rs +++ b/packages/backend-rs/src/cache/mod.rs @@ -1,3 +1,5 @@ +//! Cache handlers + pub mod bare; pub mod redis;