use std::collections::HashMap;
use std::fmt;
pub trait Store {
type Error: fmt::Debug;
fn put(&mut self, hash: [u8; 32], data: &[u8]) -> Result<(), Self::Error>;
fn get(&self, hash: [u8; 32]) -> Result<Vec<u8>, Self::Error>;
}
#[derive(Clone, Debug, Default)]
pub struct MemStore {
map: HashMap<[u8; 32], Vec<u8>>,
}
impl MemStore {
pub fn new() -> Self {
Self::default()
}
pub fn len(&self) -> usize {
self.map.len()
}
pub fn is_empty(&self) -> bool {
self.map.is_empty()
}
}
#[derive(Debug, Clone)]
pub struct NotFound;
impl fmt::Display for NotFound {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "not found")
}
}
impl Store for MemStore {
type Error = NotFound;
fn put(&mut self, hash: [u8; 32], data: &[u8]) -> Result<(), NotFound> {
self.map.entry(hash).or_insert_with(|| data.to_vec());
Ok(())
}
fn get(&self, hash: [u8; 32]) -> Result<Vec<u8>, NotFound> {
self.map.get(&hash).cloned().ok_or(NotFound)
}
}