use serde::{Deserialize, Serialize};
use super::{Crdt, ReplicaId};
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct LwwRegister<T> {
value: T,
timestamp: u64,
replica: ReplicaId,
}
impl<T> LwwRegister<T> {
pub fn new(value: T, timestamp: u64, replica: ReplicaId) -> Self {
Self {
value,
timestamp,
replica,
}
}
pub fn value(&self) -> &T {
&self.value
}
pub fn timestamp(&self) -> u64 {
self.timestamp
}
pub fn replica(&self) -> &ReplicaId {
&self.replica
}
pub fn assign(&mut self, value: T, timestamp: u64, replica: ReplicaId) -> bool {
if (timestamp, &replica) > (self.timestamp, &self.replica) {
self.value = value;
self.timestamp = timestamp;
self.replica = replica;
return true;
}
false
}
}
impl<T: Clone> Crdt for LwwRegister<T> {
fn merge(&mut self, other: &Self) -> bool {
self.assign(other.value.clone(), other.timestamp, other.replica.clone())
}
}