use std::time::Duration;
#[derive(Debug, Clone)]
pub struct CacheConfig {
pub enabled: bool,
pub ttl: Duration,
pub max_entries: usize,
pub negative_caching: bool,
pub negative_ttl: Option<Duration>,
}
impl Default for CacheConfig {
fn default() -> Self {
Self {
enabled: false,
ttl: Duration::from_secs(60),
max_entries: 10_000,
negative_caching: true,
negative_ttl: None,
}
}
}
impl CacheConfig {
pub fn new() -> Self {
Self::default()
}
pub fn enabled() -> Self {
Self {
enabled: true,
..Default::default()
}
}
#[must_use]
pub fn with_enabled(mut self, enabled: bool) -> Self {
self.enabled = enabled;
self
}
#[must_use]
pub fn with_ttl(mut self, ttl: Duration) -> Self {
self.ttl = ttl;
self
}
#[must_use]
pub fn with_max_entries(mut self, max_entries: usize) -> Self {
self.max_entries = max_entries;
self
}
#[must_use]
pub fn with_negative_caching(mut self, enabled: bool) -> Self {
self.negative_caching = enabled;
self
}
#[must_use]
pub fn with_negative_ttl(mut self, ttl: Duration) -> Self {
self.negative_ttl = Some(ttl);
self
}
pub fn effective_negative_ttl(&self) -> Duration {
self.negative_ttl.unwrap_or(self.ttl)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_default_disabled() {
let config = CacheConfig::new();
assert!(!config.enabled);
}
#[test]
fn test_enabled() {
let config = CacheConfig::enabled();
assert!(config.enabled);
assert_eq!(config.ttl, Duration::from_secs(60));
}
#[test]
fn test_builder() {
let config = CacheConfig::enabled()
.with_ttl(Duration::from_secs(120))
.with_max_entries(5000)
.with_negative_caching(false);
assert!(config.enabled);
assert_eq!(config.ttl, Duration::from_secs(120));
assert_eq!(config.max_entries, 5000);
assert!(!config.negative_caching);
}
#[test]
fn test_negative_ttl() {
let config = CacheConfig::enabled()
.with_ttl(Duration::from_secs(300))
.with_negative_ttl(Duration::from_secs(30));
assert_eq!(config.effective_negative_ttl(), Duration::from_secs(30));
}
#[test]
fn test_effective_negative_ttl_fallback() {
let config = CacheConfig::enabled().with_ttl(Duration::from_secs(60));
assert_eq!(config.effective_negative_ttl(), Duration::from_secs(60));
}
}