mod memory;
mod traits;
pub use memory::MemoryCache;
pub use traits::*;
pub trait CacheKey {
fn cache_key(&self) -> String;
}
impl CacheKey for String {
fn cache_key(&self) -> String {
self.clone()
}
}
impl CacheKey for &str {
fn cache_key(&self) -> String {
(*self).to_string()
}
}
impl CacheKey for u64 {
fn cache_key(&self) -> String {
self.to_string()
}
}
impl CacheKey for i64 {
fn cache_key(&self) -> String {
self.to_string()
}
}
#[derive(Debug, Clone, Default)]
pub struct CacheConfig {
pub prefix: Option<String>,
pub default_ttl: Option<std::time::Duration>,
pub max_entries: Option<usize>,
}
impl CacheConfig {
pub fn new() -> Self {
Self::default()
}
pub fn prefix(mut self, prefix: impl Into<String>) -> Self {
self.prefix = Some(prefix.into());
self
}
pub fn default_ttl(mut self, ttl: std::time::Duration) -> Self {
self.default_ttl = Some(ttl);
self
}
pub fn max_entries(mut self, max: usize) -> Self {
self.max_entries = Some(max);
self
}
pub fn build_key(&self, key: &str) -> String {
match &self.prefix {
Some(prefix) => format!("{}:{}", prefix, key),
None => key.to_string(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_cache_key_string() {
let key = "test".to_string();
assert_eq!(key.cache_key(), "test");
}
#[test]
fn test_cache_key_str() {
let key = "test";
assert_eq!(key.cache_key(), "test");
}
#[test]
fn test_cache_key_u64() {
let key: u64 = 42;
assert_eq!(key.cache_key(), "42");
}
#[test]
fn test_cache_config_prefix() {
let config = CacheConfig::new().prefix("myapp");
assert_eq!(config.build_key("user:1"), "myapp:user:1");
}
#[test]
fn test_cache_config_no_prefix() {
let config = CacheConfig::new();
assert_eq!(config.build_key("user:1"), "user:1");
}
}