crdt_sample/
aworset.rs

1use core::hash::Hash;
2use std::{collections::{HashMap, HashSet}, fmt::Display};
3use std::fmt::Debug;
4use crate::NodeId;
5
6#[derive(Clone, Debug, PartialEq, Eq)]
7pub struct Aworset<E>
8where
9    E: Eq + Display + Clone + Hash + Debug,
10{
11    pub id: NodeId,
12    pub cc: HashSet<(NodeId, u64)>,
13    pub set: HashSet<(NodeId, E, u64)>,
14    pub local_counter: u64,
15}
16
17impl<E> Aworset<E>
18where
19    E: Eq + Display + Clone + Hash + Debug,
20{
21    pub fn new(id: NodeId) -> Self {
22        Self {
23            id,
24            cc: HashSet::new(),
25            set: HashSet::new(),
26            local_counter: 1,
27        }
28    }
29    
30    pub fn elements(&self) -> HashSet<E>{
31        self.set.iter().map(|triple| triple.1.clone()).collect()
32    }
33
34    pub fn add(&mut self, element: E) {
35        self.cc.insert((self.id.clone(), self.local_counter));
36        self.set
37            .insert((self.id.clone(), element, self.local_counter));
38
39        self.local_counter += 1;
40    }
41
42    pub fn rm(&mut self, element: &E) {
43        self.set = self.set.drain().filter(|(_, ele, _)| ele != element).collect();
44    }
45
46    pub fn join(&mut self, other: &Self){
47        self.set = self.set
48            .drain()
49            .filter(|v| 
50                other.set.contains(v) || !other.cc.contains(&(v.0.clone(),v.2)))
51            .collect();
52        
53        for entry in other.set.iter() {
54            if !self.cc.contains(&(entry.0.clone(), entry.2)) {
55                self.set.insert(entry.clone());
56            }
57        }
58
59        self.cc.extend(other.cc.clone());
60    }
61}