use dashmap::DashMap;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::path::PathBuf;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum CacheConfig {
InMemory(bool),
File(String),
}
pub struct OpCache {
map: DashMap<u64, Value>,
path: Option<PathBuf>,
}
impl OpCache {
pub fn new(config: &CacheConfig) -> Self {
let path = match config {
CacheConfig::InMemory(_) => None,
CacheConfig::File(p) => Some(PathBuf::from(p)),
};
OpCache {
map: DashMap::new(),
path,
}
}
pub fn get(&self, hash: u64) -> Option<Value> {
self.map.get(&hash).map(|v| v.value().clone())
}
pub fn insert(&self, hash: u64, value: Value) {
self.map.insert(hash, value);
}
pub fn len(&self) -> usize {
self.map.len()
}
pub fn is_empty(&self) -> bool {
self.map.is_empty()
}
pub fn path(&self) -> Option<&PathBuf> {
self.path.as_ref()
}
}
impl std::fmt::Debug for OpCache {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("OpCache")
.field("entries", &self.map.len())
.field("path", &self.path)
.finish()
}
}