use serde::{Deserialize, Serialize};
use super::{Crdt, CrdtError, GCounter, ReplicaId};
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
pub struct PNCounter {
positive: GCounter,
negative: GCounter,
}
impl PNCounter {
pub fn new() -> Self {
Self::default()
}
pub fn increment(&mut self, replica: &ReplicaId, amount: u64) -> Result<(), CrdtError> {
self.positive.increment(replica, amount)
}
pub fn decrement(&mut self, replica: &ReplicaId, amount: u64) -> Result<(), CrdtError> {
self.negative.increment(replica, amount)
}
pub fn value(&self) -> Result<i128, CrdtError> {
let positive = i128::from(self.positive.value()?);
let negative = i128::from(self.negative.value()?);
positive
.checked_sub(negative)
.ok_or(CrdtError::ValueOverflow)
}
pub fn positive(&self) -> &GCounter {
&self.positive
}
pub fn negative(&self) -> &GCounter {
&self.negative
}
}
impl Crdt for PNCounter {
fn merge(&mut self, other: &Self) -> bool {
let positive_changed = self.positive.merge(&other.positive);
let negative_changed = self.negative.merge(&other.negative);
positive_changed || negative_changed
}
}