antimatter 2.0.13

antimatter.io Rust library for data control
Documentation
use lru::LruCache;
use std::num::NonZeroUsize;

#[derive(Clone, Debug)]
pub struct DomainCache {
    cache: Option<LruCache<String, String>>,
    enabled: bool,
    size: usize,
}

/// DomainCache is a simple wrapper for an LRU cache used to hold domain IDs based on known
/// nicknames. This allows the client to bypass resolving a domain nickname to its ID if the
/// operation has been performed before.
impl DomainCache {
    pub fn new(size: usize) -> Self {
        if let Some(cache_size) = NonZeroUsize::new(size) {
            Self {
                cache: Some(LruCache::new(cache_size)),
                enabled: true,
                size,
            }
        } else {
            Self {
                cache: None,
                enabled: false,
                size,
            }
        }
    }

    pub fn cache(&mut self) -> Option<&mut LruCache<String, String>> {
        if self.enabled {
            self.cache.as_mut()
        } else {
            None
        }
    }

    pub fn size(&self) -> usize {
        self.size
    }
}