chore (backend-rs): add doc comments

This commit is contained in:
naskya 2024-08-03 11:53:41 +09:00
parent fef478fc12
commit 1b2e58ef33
No known key found for this signature in database
GPG key ID: 712D413B3A9FED5C
2 changed files with 53 additions and 0 deletions

View file

@ -3,6 +3,7 @@
use chrono::{DateTime, Duration, Utc}; use chrono::{DateTime, Duration, Utc};
use std::sync::Mutex; use std::sync::Mutex;
/// Cache stored directly in memory
pub struct Cache<T: Clone> { pub struct Cache<T: Clone> {
cache: Mutex<TimedData<T>>, cache: Mutex<TimedData<T>>,
ttl: Option<Duration>, ttl: Option<Duration>,
@ -20,6 +21,7 @@ impl<T: Clone> Default for Cache<T> {
} }
impl<T: Clone> Cache<T> { impl<T: Clone> Cache<T> {
/// Creates a new cache object with no auto invalidation.
pub const fn new() -> Self { pub const fn new() -> Self {
Self { Self {
cache: Mutex::new(TimedData { cache: Mutex::new(TimedData {
@ -30,6 +32,30 @@ impl<T: Clone> Cache<T> {
} }
} }
/// 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<i32> = 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 { pub const fn new_with_ttl(ttl: Duration) -> Self {
Self { Self {
cache: Mutex::new(TimedData { cache: Mutex::new(TimedData {
@ -40,6 +66,30 @@ impl<T: Clone> Cache<T> {
} }
} }
/// Sets a cache. This function overwrites the existing data.
///
/// # Example
/// ```
/// # use backend_rs::cache::Cache;
/// static CACHE: Cache<i32> = 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) { pub fn set(&self, value: T) {
if self.ttl.is_none() { if self.ttl.is_none() {
let _ = self.cache.lock().map(|mut cache| cache.value = Some(value)); let _ = self.cache.lock().map(|mut cache| cache.value = Some(value));
@ -53,6 +103,7 @@ impl<T: Clone> Cache<T> {
} }
} }
/// Gets a cache. Returns [`None`] is the cache is not set or expired.
pub fn get(&self) -> Option<T> { pub fn get(&self) -> Option<T> {
let data = self.cache.lock().ok()?; let data = self.cache.lock().ok()?;

View file

@ -1,3 +1,5 @@
//! Cache handlers
pub mod bare; pub mod bare;
pub mod redis; pub mod redis;