use std::collections::HashMap;
use crate::format::Format;
use crate::{usize_to_nat, StoreError, StoreRatio, StoreResult, StoreUpdate};
#[derive(Clone, Debug)]
pub struct StoreModel {
content: HashMap<usize, Box<[u8]>>,
format: Format,
}
#[derive(Clone, Debug)]
pub enum StoreOperation {
Transaction {
updates: Vec<StoreUpdate<Vec<u8>>>,
},
Clear {
min_key: usize,
},
Prepare {
length: usize,
},
}
impl StoreModel {
pub fn new(format: Format) -> StoreModel {
let content = HashMap::new();
StoreModel { content, format }
}
pub fn content(&self) -> &HashMap<usize, Box<[u8]>> {
&self.content
}
pub fn format(&self) -> &Format {
&self.format
}
pub fn apply(&mut self, operation: StoreOperation) -> StoreResult<()> {
match operation {
StoreOperation::Transaction { updates } => self.transaction(updates),
StoreOperation::Clear { min_key } => self.clear(min_key),
StoreOperation::Prepare { length } => self.prepare(length),
}
}
pub fn capacity(&self) -> StoreRatio {
let total = self.format.total_capacity();
let used =
usize_to_nat(self.content.values().map(|x| self.format.entry_size(x) as usize).sum());
StoreRatio { used, total }
}
fn transaction(&mut self, updates: Vec<StoreUpdate<Vec<u8>>>) -> StoreResult<()> {
if self.format.transaction_valid(&updates).is_none() {
return Err(StoreError::InvalidArgument);
}
let capacity = self.format.transaction_capacity(&updates) as usize;
if self.capacity().remaining() < capacity {
return Err(StoreError::NoCapacity);
}
for update in updates {
match update {
StoreUpdate::Insert { key, value } => {
self.content.insert(key, value.into_boxed_slice());
}
StoreUpdate::Remove { key } => {
self.content.remove(&key);
}
}
}
Ok(())
}
fn clear(&mut self, min_key: usize) -> StoreResult<()> {
if min_key > self.format.max_key() as usize {
return Err(StoreError::InvalidArgument);
}
self.content.retain(|&k, _| k < min_key);
Ok(())
}
fn prepare(&self, length: usize) -> StoreResult<()> {
if self.capacity().remaining() < length {
return Err(StoreError::NoCapacity);
}
Ok(())
}
}