use std::path::Path;
use std::sync::{Arc, Mutex, MutexGuard};
pub enum NativeThingdEngine {
Memory(thingd::MemoryEngine),
Persistent(thingd::PersistentEngine),
}
#[derive(Clone)]
pub struct NativeThingdStore {
engine: Arc<Mutex<NativeThingdEngine>>,
}
impl NativeThingdStore {
#[must_use]
pub fn memory() -> Self {
Self {
engine: Arc::new(Mutex::new(NativeThingdEngine::Memory(
thingd::MemoryEngine::new(),
))),
}
}
pub fn persistent(path: impl AsRef<Path>) -> Result<Self, thingd::ThingdError> {
let engine = thingd::PersistentEngine::open(path)
.map_err(|error| thingd::ThingdError::Storage(error.to_string()))?;
Ok(Self {
engine: Arc::new(Mutex::new(NativeThingdEngine::Persistent(engine))),
})
}
pub fn with_engine<R>(&self, operation: impl FnOnce(&mut NativeThingdEngine) -> R) -> R {
let mut engine = self.engine.lock().expect("thingd engine mutex poisoned");
operation(&mut engine)
}
pub fn lock(&self) -> MutexGuard<'_, NativeThingdEngine> {
self.engine.lock().expect("thingd engine mutex poisoned")
}
}