crdt: Small improvements

Signed-off-by: Alexis Sellier <alexis@radicle.xyz>
This commit is contained in:
Alexis Sellier 2022-11-30 00:03:35 +01:00
parent f140c6d28e
commit 252b6cd7bc
No known key found for this signature in database
4 changed files with 23 additions and 3 deletions

View File

@ -100,13 +100,14 @@ impl<G: Signer, A: Clone + Serialize> Actor<G, A> {
/// Create a new change.
pub fn change(&mut self, action: A) -> Change<A> {
let author = *self.signer.public_key();
let clock = self.clock.tick();
let clock = self.clock;
let change = Change {
action,
author,
clock,
};
self.changes.insert((self.clock, author), change.clone());
self.clock.tick();
change
}

View File

@ -29,6 +29,11 @@ impl Lamport {
self.counter.merge(other.counter);
self.tick()
}
/// Reset clock to default state.
pub fn reset(&mut self) {
self.counter = Max::default();
}
}
impl From<u64> for Lamport {

View File

@ -2,11 +2,14 @@ use std::collections::btree_map::Entry;
use std::collections::BTreeMap;
use crate::lwwreg::LWWReg;
use crate::Semilattice;
use crate::{clock, Semilattice};
/// Last-Write-Wins Map.
///
/// In case a value is added and removed under a key at the same time,
/// the "add" takes precedence over the "remove".
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LWWMap<K, V, C> {
pub struct LWWMap<K, V, C = clock::Lamport> {
inner: BTreeMap<K, LWWReg<Option<V>, C>>,
}

View File

@ -2,6 +2,9 @@ use crate::clock;
use crate::{lwwmap::LWWMap, Semilattice};
/// Last-Write-Wins Set.
///
/// In case the same value is added and removed at the same time,
/// the "add" takes precedence over the "remove".
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LWWSet<T, C = clock::Lamport> {
inner: LWWMap<T, (), C>,
@ -129,6 +132,14 @@ mod tests {
set.remove('a', 2);
assert!(!set.contains(&'a'));
assert!(!set.iter().any(|c| *c == 'a'));
set.insert('b', 3);
set.remove('b', 3);
assert!(set.contains(&'b')); // Insert precedence.
set.remove('c', 3);
set.insert('c', 3);
assert!(set.contains(&'c')); // Insert precedence.
}
#[test]