1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
use std::{fmt::Debug, sync::Arc};
use parking_lot::{Mutex, MutexGuard, RwLock};
use crate::chunk_cache::AnySendSync;
#[derive(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>, root: Root) -> Self {
let state = ActiveState {
file_id,
max_order,
current_position: 0,
root,
};
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>, mut root: Root) -> Self {
root.initialize_default();
let state = ActiveState {
file_id,
max_order,
current_position: 0,
root,
};
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()
}
}
impl<Root> Default for State<Root>
where
Root: super::Root + Default,
{
fn default() -> Self {
Self::new(None, None, Root::default())
}
}
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();
}
}