use super::KvStore;
use crate::Result;
use dashmap::DashMap;
use std::future::Future;
pub struct MemoryKvStore {
store: DashMap<String, Vec<u8>>,
}
impl MemoryKvStore {
#[must_use]
pub fn new() -> Self {
Self { store: DashMap::new() }
}
#[must_use]
pub fn with_capacity(capacity: usize) -> Self {
Self { store: DashMap::with_capacity(capacity) }
}
#[must_use]
pub fn len(&self) -> usize {
self.store.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.store.is_empty()
}
pub fn clear(&self) {
self.store.clear();
}
}
impl Default for MemoryKvStore {
fn default() -> Self {
Self::new()
}
}
impl KvStore for MemoryKvStore {
fn get(&self, key: &str) -> impl Future<Output = Result<Option<Vec<u8>>>> + Send {
std::future::ready(Ok(self.store.get(key).map(|v| v.value().clone())))
}
fn set(&self, key: &str, value: Vec<u8>) -> impl Future<Output = Result<()>> + Send {
self.store.insert(key.to_string(), value);
std::future::ready(Ok(()))
}
fn delete(&self, key: &str) -> impl Future<Output = Result<()>> + Send {
self.store.remove(key);
std::future::ready(Ok(()))
}
fn exists(&self, key: &str) -> impl Future<Output = Result<bool>> + Send {
std::future::ready(Ok(self.store.contains_key(key)))
}
}