pub trait Cache<K, V>{
// Required methods
fn get(&self, key: &K) -> Option<V>;
fn set(&self, key: &K, value: &V, ttl: Duration) -> Result<(), CacheError>;
fn invalidate(&self, key: &K) -> Result<(), CacheError>;
fn clear(&self) -> Result<(), CacheError>;
}Expand description
What: Trait for cache implementations.
Inputs:
K: Cache key type (must beAsRef<str>)V: Value type (must beClone + Serialize + Deserialize)
Output:
- Various methods return
Option<V>for cache hits orResultfor operations
Details:
- Provides abstract interface for cache operations
- Supports get, set, invalidate, and clear operations
- Generic over value type to support different cached data
Required Methods§
Sourcefn get(&self, key: &K) -> Option<V>
fn get(&self, key: &K) -> Option<V>
What: Get a value from the cache.
Inputs:
key: Cache key to look up
Output:
Option<V>containing cached value if found and not expired,Noneotherwise
Details:
- Returns
Noneif key not found or entry has expired - Should check TTL before returning value
Sourcefn set(&self, key: &K, value: &V, ttl: Duration) -> Result<(), CacheError>
fn set(&self, key: &K, value: &V, ttl: Duration) -> Result<(), CacheError>
What: Store a value in the cache.
Inputs:
key: Cache keyvalue: Value to cachettl: Time-to-live duration
Output:
Result<(), CacheError>indicating success or failure
Details:
- Stores value with specified TTL
- May evict entries if cache is full (LRU)
- Should not block the main operation
§Errors
- Returns
Err(CacheError::Serialization)if value serialization fails - Returns
Err(CacheError::Io)if disk cache write fails (disk cache only)
Sourcefn invalidate(&self, key: &K) -> Result<(), CacheError>
fn invalidate(&self, key: &K) -> Result<(), CacheError>
What: Invalidate a specific cache entry.
Inputs:
key: Cache key to invalidate
Output:
Result<(), CacheError>indicating success or failure
Details:
- Removes the entry from cache
- Safe to call if key doesn’t exist
§Errors
- Returns
Err(CacheError::Io)if disk cache file removal fails (disk cache only)
Sourcefn clear(&self) -> Result<(), CacheError>
fn clear(&self) -> Result<(), CacheError>
What: Clear all entries from the cache.
Inputs: None
Output:
Result<(), CacheError>indicating success or failure
Details:
- Removes all entries from cache
- Useful for cache invalidation operations
§Errors
- Returns
Err(CacheError::Io)if disk cache cleanup fails (disk cache only)