use std::{fmt::Debug, sync::Arc};
use parking_lot::{Mutex, MutexGuard, RwLock};
use crate::chunk_cache::AnySendSync;
#[derive(Default, Clone, Debug)]
#[must_use]
pub struct State<Root: super::Root> {
reader: Arc<RwLock<Arc<ActiveState<Root>>>>,
writer: Arc<Mutex<ActiveState<Root>>>,
}
impl<Root> State<Root>
where
Root: super::Root,
{
pub fn new(file_id: Option<u64>, max_order: Option<usize>) -> Self {
let state = ActiveState {
file_id,
max_order,
current_position: 0,
root: Root::default(),
};
Self {
reader: Arc::new(RwLock::new(Arc::new(state.clone()))),
writer: Arc::new(Mutex::new(state)),
}
}
pub fn initialized(file_id: Option<u64>, max_order: Option<usize>) -> Self {
let mut header = Root::default();
header.initialize_default();
let state = ActiveState {
file_id,
max_order,
current_position: 0,
root: header,
};
Self {
reader: Arc::new(RwLock::new(Arc::new(state.clone()))),
writer: Arc::new(Mutex::new(state)),
}
}
pub(crate) fn lock(&self) -> MutexGuard<'_, ActiveState<Root>> {
self.writer.lock()
}
#[must_use]
pub fn read(&self) -> Arc<ActiveState<Root>> {
let reader = self.reader.read();
reader.clone()
}
}
pub trait AnyTreeState: AnySendSync + Debug {
fn cloned(&self) -> Box<dyn AnyTreeState>;
fn publish(&self);
}
impl<Root: super::Root> AnyTreeState for State<Root> {
fn cloned(&self) -> Box<dyn AnyTreeState> {
Box::new(self.clone())
}
fn publish(&self) {
let state = self.lock();
state.publish(self);
}
}
#[derive(Clone, Debug, Default)]
pub struct ActiveState<Root: super::Root> {
pub file_id: Option<u64>,
pub current_position: u64,
pub root: Root,
pub max_order: Option<usize>,
}
impl<Root> ActiveState<Root>
where
Root: super::Root,
{
pub fn initialized(&self) -> bool {
self.root.initialized()
}
pub(crate) fn publish(&self, state: &State<Root>) {
let mut reader = state.reader.write();
*reader = Arc::new(self.clone());
}
pub(crate) fn rollback(&mut self, state: &State<Root>) {
let reader = state.reader.read();
self.root = reader.root.clone();
}
}