use std::sync::Arc;
use dashmap::DashMap;
use parking_lot::FairMutex;
use crate::{node::Node, Kind, Rex, StateId};
pub struct StateStore<Id, S> {
trees: DashMap<Id, Arc<FairMutex<Node<Id, S>>>>,
}
impl<K> Default for StateStore<StateId<K>, K::State>
where
K: Rex,
{
fn default() -> Self {
Self::new()
}
}
pub(crate) type Tree<K> = Arc<FairMutex<Node<StateId<K>, <K as Kind>::State>>>;
impl<K: Rex> StateStore<StateId<K>, K::State> {
#[must_use]
pub fn new() -> Self {
Self {
trees: DashMap::new(),
}
}
pub fn new_tree(node: Node<StateId<K>, K::State>) -> Tree<K> {
assert!(!node.id.is_nil());
Arc::new(FairMutex::new(node))
}
pub fn insert_ref(&self, id: StateId<K>, node: Tree<K>) {
assert!(!id.is_nil());
self.trees.insert(id, node);
}
pub fn remove_ref(&self, id: StateId<K>) {
assert!(!id.is_nil());
self.trees.remove(&id);
}
pub fn get_tree(&self, id: StateId<K>) -> Option<Tree<K>> {
assert!(!id.is_nil());
let node = self.trees.get(&id);
node.map(|n| n.value().clone())
}
}