use std::num::NonZeroUsize;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CacheStrategy {
#[cfg(feature = "lru-cache")]
Lru(NonZeroUsize),
NoCache,
}
impl CacheStrategy {
pub fn new(capacity: usize) -> Self {
if capacity == 0 {
Self::NoCache
} else {
#[cfg(feature = "lru-cache")]
{
Self::Lru(
NonZeroUsize::new(capacity).expect("Capacity must be > 0"),
)
}
#[cfg(not(feature = "lru-cache"))]
{
tracing::warn!(
capacity,
"LRU cache requested with capacity {}, but 'lru-cache' \
feature is disabled. Falling back to NoCache. Enable \
'lru-cache' feature in Cargo.toml to use caching.",
capacity
);
Self::NoCache
}
}
}
pub fn capacity(&self) -> Option<NonZeroUsize> {
match self {
#[cfg(feature = "lru-cache")]
| Self::Lru(size) => Some(*size),
| Self::NoCache => None,
}
}
}
impl Default for CacheStrategy {
fn default() -> Self {
Self::NoCache
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[cfg(feature = "lru-cache")]
fn test_new_with_capacity() {
let cache = CacheStrategy::new(100);
assert!(matches!(cache, CacheStrategy::Lru(_)));
assert_eq!(cache.capacity(), NonZeroUsize::new(100));
}
#[test]
#[cfg(not(feature = "lru-cache"))]
fn test_new_with_capacity_no_lru() {
let cache = CacheStrategy::new(100);
assert_eq!(cache, CacheStrategy::NoCache);
assert_eq!(cache.capacity(), None);
}
#[test]
fn test_new_with_zero_capacity() {
let cache = CacheStrategy::new(0);
assert_eq!(cache, CacheStrategy::NoCache);
assert_eq!(cache.capacity(), None);
}
#[test]
fn test_default() {
let cache = CacheStrategy::default();
assert_eq!(cache, CacheStrategy::NoCache);
}
#[test]
#[cfg(feature = "lru-cache")]
fn test_capacity() {
let lru = CacheStrategy::Lru(NonZeroUsize::new(50).unwrap());
assert_eq!(lru.capacity(), NonZeroUsize::new(50));
let no_cache = CacheStrategy::NoCache;
assert_eq!(no_cache.capacity(), None);
}
#[test]
fn test_capacity_no_cache() {
let no_cache = CacheStrategy::NoCache;
assert_eq!(no_cache.capacity(), None);
}
#[test]
fn test_clone_and_copy() {
let cache = CacheStrategy::new(100);
let cloned = cache;
assert_eq!(cache, cloned);
}
}