use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use super::{Crdt, CrdtError, ReplicaId};
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
pub struct GCounter {
components: BTreeMap<ReplicaId, u64>,
}
impl GCounter {
pub fn new() -> Self {
Self::default()
}
pub fn increment(&mut self, replica: &ReplicaId, amount: u64) -> Result<(), CrdtError> {
let entry = self.components.entry(replica.clone()).or_insert(0);
*entry = entry
.checked_add(amount)
.ok_or(CrdtError::CounterOverflow)?;
Ok(())
}
pub fn value(&self) -> Result<u64, CrdtError> {
self.components.values().try_fold(0_u64, |total, value| {
total.checked_add(*value).ok_or(CrdtError::ValueOverflow)
})
}
pub fn component(&self, replica: &ReplicaId) -> u64 {
self.components.get(replica).copied().unwrap_or(0)
}
pub fn components(&self) -> impl Iterator<Item = (&ReplicaId, &u64)> {
self.components.iter()
}
}
impl Crdt for GCounter {
fn merge(&mut self, other: &Self) -> bool {
let mut changed = false;
for (replica, remote) in &other.components {
let local = self.components.entry(replica.clone()).or_insert(0);
if *remote > *local {
*local = *remote;
changed = true;
}
}
changed
}
}