use crate::{error::Error, index::GenerationalIndex};
pub trait SoftAlloc {
fn match_generation(&self, index: &GenerationalIndex) -> bool;
fn allocate(&mut self, vec_len: usize) -> GenerationalIndex;
fn deallocate(&mut self, index: &GenerationalIndex) -> Result<(), Error>;
}
pub struct SoftVec<T>(Vec<T>);
impl<T> SoftVec<T> {
pub fn with_capacity(capacity: usize) -> SoftVec<T> {
SoftVec(Vec::with_capacity(capacity))
}
pub fn get(&self, index: &GenerationalIndex, alloc: &mut impl SoftAlloc) -> Option<&T> {
if alloc.match_generation(index) {
self.0.get(index.index())
} else {
None
}
}
pub fn insert(&mut self, value: T, alloc: &mut impl SoftAlloc) -> GenerationalIndex {
let temp_idx: GenerationalIndex = alloc.allocate(self.0.len());
self.0.insert(temp_idx.index(), value);
temp_idx
}
pub fn remove(
&mut self,
index: GenerationalIndex,
alloc: &mut impl SoftAlloc,
) -> Result<(), Error> {
if let Some(_val) = self.0.get(index.index()) {
alloc.deallocate(&index)?;
self.0.remove(index.index());
Ok(())
} else {
Err(Error::ElementNotFound)
}
}
}