crdt_woot/
dumb_common.rs

1use std::{collections::HashSet, ops::Deref};
2
3use crate::crdt::OpSet;
4
5#[derive(Debug, Clone, PartialEq, Eq)]
6pub struct Op {
7    pub id: OpId,
8    pub left: Option<OpId>,
9    pub right: Option<OpId>,
10}
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
13pub struct OpId {
14    pub client_id: usize,
15    pub clock: usize,
16}
17
18#[derive(Default)]
19pub struct OpSetImpl {
20    pub set: HashSet<OpId>,
21}
22
23impl OpSet<Op, OpId> for OpSetImpl {
24    fn insert(&mut self, value: &Op) {
25        self.set.insert(value.id);
26    }
27
28    fn contain(&self, id: OpId) -> bool {
29        self.set.contains(&id)
30    }
31
32    fn clear(&mut self) {
33        self.set.clear();
34    }
35}
36
37#[derive(Debug, Default)]
38pub struct Container {
39    pub content: Vec<Op>,
40    /// exclusive end
41    pub version_vector: Vec<usize>,
42    pub max_clock: usize,
43    pub id: usize,
44}
45
46pub struct Iter<'a> {
47    pub arr: &'a mut Vec<Op>,
48    pub index: usize,
49    pub start: Option<OpId>,
50    pub end: Option<OpId>,
51    pub done: bool,
52    pub started: bool,
53}
54
55pub struct Cursor<'a> {
56    pub arr: &'a mut Vec<Op>,
57    pub pos: usize,
58}
59
60impl<'a> Iterator for Iter<'a> {
61    type Item = Cursor<'a>;
62
63    fn next(&mut self) -> Option<Self::Item> {
64        if self.start.is_none() {
65            self.started = true;
66        }
67
68        if self.done {
69            return None;
70        }
71
72        if self.index >= self.arr.len() {
73            return None;
74        }
75
76        let op = &self.arr[self.index];
77        self.index += 1;
78
79        if Some(op.id) == self.end {
80            self.done = true;
81        }
82
83        if Some(op.id) == self.start {
84            self.started = true;
85        }
86
87        if !self.started {
88            return self.next();
89        }
90
91        Some(Cursor {
92            arr: unsafe { &mut *(self.arr as *mut _) },
93            pos: self.index - 1,
94        })
95    }
96}
97
98impl Deref for Cursor<'_> {
99    type Target = Op;
100
101    fn deref(&self) -> &Self::Target {
102        &self.arr[self.pos]
103    }
104}