| 1 | use std::collections::BTreeMap; |
| 2 | |
| 3 | use loro_common::{ContainerID, ID}; |
| 4 | |
| 5 | use crate::{container::idx::ContainerIdx, event::InternalDiff, OpLog}; |
| 6 | |
| 7 | use super::{DiffCalcVersionInfo, DiffCalculatorTrait, DiffMode}; |
| 8 | |
| 9 | #[derive(Debug)] |
| 10 | pub(crate) struct CounterDiffCalculator { |
| 11 | ops: BTreeMap<ID, f64>, |
| 12 | } |
| 13 | |
| 14 | impl CounterDiffCalculator { |
| 15 | pub(crate) fn new(_idx: ContainerIdx) -> Self { |
| 16 | Self { |
| 17 | ops: BTreeMap::new(), |
| 18 | } |
| 19 | } |
| 20 | } |
| 21 | |
| 22 | impl DiffCalculatorTrait for CounterDiffCalculator { |
| 23 | fn start_tracking(&mut self, _oplog: &OpLog, _vv: &crate::VersionVector, _mode: DiffMode) {} |
| 24 | |
| 25 | fn apply_change( |
| 26 | &mut self, |
| 27 | _oplog: &OpLog, |
| 28 | op: crate::op::RichOp, |
| 29 | _vv: Option<&crate::VersionVector>, |
| 30 | ) { |
| 31 | let id = op.id(); |
| 32 | self.ops.insert( |
| 33 | id, |
| 34 | *op.op().content.as_future().unwrap().as_counter().unwrap(), |
| 35 | ); |
| 36 | } |
| 37 | |
| 38 | fn finish_this_round(&mut self) {} |
| 39 | |
| 40 | fn calculate_diff( |
| 41 | &mut self, |
| 42 | _idx: ContainerIdx, |
| 43 | _oplog: &OpLog, |
| 44 | info: DiffCalcVersionInfo, |
| 45 | _on_new_container: impl FnMut(&ContainerID), |
| 46 | ) -> (InternalDiff, DiffMode) { |
| 47 | let mut diff = 0.; |
| 48 | let (b, a) = info.from_vv.diff_iter(info.to_vv); |
| 49 | |
| 50 | for sub in b { |
| 51 | for (_, c) in self.ops.range(sub.norm_id_start()..sub.norm_id_end()) { |
| 52 | diff -= c; |
| 53 | } |
| 54 | } |
| 55 | for sub in a { |
| 56 | for (_, c) in self.ops.range(sub.norm_id_start()..sub.norm_id_end()) { |
| 57 | diff += c; |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | (InternalDiff::Counter(diff), DiffMode::Linear) |
| 62 | } |
| 63 | } |