use std::borrow::Cow;
use std::rc::Rc;
use crate::scheduler::value::Value;
use super::Node;
mod view;
pub use view::View;
#[derive(Clone, Debug, Default)]
pub struct Storage {
inner: Vec<Node<Rc<dyn Value>>>,
}
impl Storage {
pub fn new() -> Self {
Self { inner: Vec::new() }
}
pub fn get(&self, id: usize) -> Option<&dyn Value> {
self.position(id)
.map(|index| self.inner[index].data.as_ref())
}
pub fn select<'a, I>(&'a self, ids: I) -> View<'a>
where
I: Into<Cow<'a, [usize]>>,
{
View::new(self, ids)
}
pub fn append<V>(&mut self, id: usize, value: V)
where
V: Into<Rc<dyn Value>>,
{
self.inner.push(Node { id, data: value.into() });
}
pub fn remove(&mut self, id: usize) -> Option<Rc<dyn Value>> {
self.position(id).map(|index| {
let prior = self.inner.swap_remove(index);
prior.data
})
}
#[inline]
fn position(&self, id: usize) -> Option<usize> {
self.inner.iter().position(|item| item.id == id)
}
}
#[allow(clippy::must_use_candidate)]
impl Storage {
#[inline]
pub fn len(&self) -> usize {
self.inner.len()
}
#[inline]
pub fn is_empty(&self) -> bool {
self.inner.is_empty()
}
}