logicaffeine_data/crdt/
orset.rs1use super::causal::{Dot, DotContext, VClock};
7use super::delta::DeltaCrdt;
8use super::replica::{generate_replica_id, ReplicaId};
9use super::Merge;
10use serde::de::DeserializeOwned;
11use serde::{Deserialize, Serialize};
12use std::collections::{HashMap, HashSet};
13use std::hash::Hash;
14use std::marker::PhantomData;
15
16#[derive(Debug, Clone, Serialize, Deserialize)]
18#[serde(bound = "T: Serialize + serde::de::DeserializeOwned + Hash + Eq")]
19pub struct ORSetDelta<T> {
20 pub entries: HashMap<T, HashSet<Dot>>,
21 pub context: DotContext,
22}
23
24pub trait SetBias: Default + Clone + Send + 'static {
41 fn resolve(
54 local_has_dots: bool,
55 remote_has_dots: bool,
56 local_removed: bool,
57 remote_removed: bool,
58 ) -> bool;
59}
60
61#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
68pub struct AddWins;
69
70impl SetBias for AddWins {
71 fn resolve(
72 local_has_dots: bool,
73 remote_has_dots: bool,
74 _local_removed: bool,
75 _remote_removed: bool,
76 ) -> bool {
77 local_has_dots || remote_has_dots
78 }
79}
80
81#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
88pub struct RemoveWins;
89
90impl SetBias for RemoveWins {
91 fn resolve(
92 local_has_dots: bool,
93 remote_has_dots: bool,
94 local_removed: bool,
95 remote_removed: bool,
96 ) -> bool {
97 if local_removed || remote_removed {
99 false
100 } else {
101 local_has_dots || remote_has_dots
103 }
104 }
105}
106
107#[derive(Debug, Clone, Serialize, Deserialize)]
113#[serde(bound = "T: Serialize + serde::de::DeserializeOwned + Hash + Eq")]
114pub struct ORSet<T, B: SetBias = AddWins> {
115 entries: HashMap<T, HashSet<Dot>>,
117 context: DotContext,
119 replica_id: ReplicaId,
121 #[serde(skip)]
123 _bias: PhantomData<B>,
124}
125
126impl<T: Hash + Eq + Clone, B: SetBias> ORSet<T, B> {
127 pub fn new(replica_id: ReplicaId) -> Self {
129 Self {
130 entries: HashMap::new(),
131 context: DotContext::new(),
132 replica_id,
133 _bias: PhantomData,
134 }
135 }
136
137 pub fn new_random() -> Self {
139 Self::new(generate_replica_id())
140 }
141
142 pub fn add(&mut self, value: T) {
144 let dot = self.context.next(self.replica_id);
145 self.entries.entry(value).or_default().insert(dot);
146 }
147
148 pub fn insert(&mut self, value: T) {
150 self.add(value);
151 }
152
153 pub fn remove(&mut self, value: &T) {
157 self.entries.remove(value);
158 }
159
160 pub fn contains(&self, value: &T) -> bool {
162 self.entries
163 .get(value)
164 .map_or(false, |dots| !dots.is_empty())
165 }
166
167 pub fn len(&self) -> usize {
169 self.entries
170 .values()
171 .filter(|dots| !dots.is_empty())
172 .count()
173 }
174
175 pub fn is_empty(&self) -> bool {
177 self.len() == 0
178 }
179
180 pub fn iter(&self) -> impl Iterator<Item = &T> {
182 self.entries
183 .iter()
184 .filter(|(_, dots)| !dots.is_empty())
185 .map(|(v, _)| v)
186 }
187
188 pub fn replica_id(&self) -> ReplicaId {
190 self.replica_id
191 }
192}
193
194impl<T: Hash + Eq, B: SetBias> PartialEq for ORSet<T, B> {
195 fn eq(&self, other: &Self) -> bool {
196 self.entries == other.entries && self.context == other.context
197 }
198}
199
200impl<T: Hash + Eq + Clone, B: SetBias> Merge for ORSet<T, B> {
201 fn merge(&mut self, other: &Self) {
202 let all_keys: HashSet<T> = self
204 .entries
205 .keys()
206 .chain(other.entries.keys())
207 .cloned()
208 .collect();
209
210 for value in all_keys {
211 let my_dots_before: HashSet<Dot> =
212 self.entries.get(&value).cloned().unwrap_or_default();
213 let other_dots: HashSet<Dot> = other.entries.get(&value).cloned().unwrap_or_default();
214
215 let my_removed = my_dots_before.is_empty()
220 && other_dots.iter().any(|dot| self.context.has_seen(dot));
221 let other_removed = other_dots.is_empty()
222 && my_dots_before.iter().any(|dot| other.context.has_seen(dot));
223
224 let mut combined_dots: HashSet<Dot> = HashSet::new();
226
227 for dot in &my_dots_before {
229 if !other.context.has_seen(dot) || other_dots.contains(dot) {
230 combined_dots.insert(*dot);
231 }
232 }
233
234 for dot in &other_dots {
236 if !self.context.has_seen(dot) || my_dots_before.contains(dot) {
237 combined_dots.insert(*dot);
238 }
239 }
240
241 let my_has_dots = !my_dots_before.is_empty();
242 let other_has_dots = !other_dots.is_empty();
243
244 let keep = B::resolve(my_has_dots, other_has_dots, my_removed, other_removed);
246
247 let my_dots = self.entries.entry(value).or_default();
248 if keep {
249 *my_dots = combined_dots;
250 } else {
251 my_dots.clear();
252 }
253 }
254
255 self.context.merge(&other.context);
257
258 self.entries.retain(|_, dots| !dots.is_empty());
260 }
261}
262
263impl<T: Hash + Eq + Clone + Serialize + DeserializeOwned + Send + 'static, B: SetBias> DeltaCrdt
264 for ORSet<T, B>
265{
266 type Delta = ORSetDelta<T>;
267
268 fn delta_since(&self, since: &VClock) -> Option<Self::Delta> {
269 let current = self.version();
270 if since.dominates(¤t) {
271 return None;
272 }
273
274 let mut entries: HashMap<T, HashSet<Dot>> = HashMap::new();
281 let mut context = DotContext::new();
282 for (value, dots) in &self.entries {
283 let fresh: HashSet<Dot> = dots
284 .iter()
285 .filter(|d| d.counter > since.get(d.replica))
286 .copied()
287 .collect();
288 if !fresh.is_empty() {
289 for d in &fresh {
290 context.add(*d);
291 }
292 entries.insert(value.clone(), fresh);
293 }
294 }
295 Some(ORSetDelta { entries, context })
296 }
297
298 fn apply_delta(&mut self, delta: &Self::Delta) {
299 let temp: ORSet<T, B> = ORSet {
301 entries: delta.entries.clone(),
302 context: delta.context.clone(),
303 replica_id: 0, _bias: PhantomData,
305 };
306 self.merge(&temp);
307 }
308
309 fn version(&self) -> VClock {
310 self.context.version()
311 }
312}
313
314impl<T: Hash + Eq + Clone, B: SetBias> Default for ORSet<T, B> {
315 fn default() -> Self {
316 Self::new_random()
317 }
318}
319
320impl<T: Hash + Eq + Clone + Ord, B: SetBias> IntoIterator for ORSet<T, B> {
323 type Item = T;
324 type IntoIter = std::vec::IntoIter<T>;
325
326 fn into_iter(self) -> Self::IntoIter {
327 let mut elements: Vec<T> = self.iter().cloned().collect();
328 elements.sort();
329 elements.into_iter()
330 }
331}
332
333#[cfg(test)]
334#[path = "../../../logicaffeine_tests/unit/logicaffeine_data/crdt/orset/tests.rs"]
335mod tests;