forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

counter_state.rs145 lines, 3.9 KiBHistoryRawDownload
1use std::sync::Weak;
2
3use loro_common::{ContainerID, LoroResult, LoroValue};
4
5use crate::{
6 configure::Configure,
7 container::idx::ContainerIdx,
8 event::{Diff, Index, InternalDiff},
9 op::{Op, RawOp, RawOpContent},
10 LoroDocInner,
11};
12
13use super::{ApplyLocalOpReturn, ContainerState, DiffApplyContext};
14
15#[derive(Debug, Clone)]
16pub struct CounterState {
17 idx: ContainerIdx,
18 value: f64,
19}
20
21impl CounterState {
22 pub(crate) fn value(&self) -> f64 {
23 self.value
24 }
25
26 /// For rolling back local ops (`DocState::finish_local_rollback`).
27 pub(crate) fn set_value(&mut self, value: f64) {
28 self.value = value;
29 }
30}
31
32impl CounterState {
33 pub(crate) fn new(idx: ContainerIdx) -> Self {
34 Self { idx, value: 0. }
35 }
36}
37
38impl ContainerState for CounterState {
39 fn container_idx(&self) -> ContainerIdx {
40 self.idx
41 }
42
43 fn is_state_empty(&self) -> bool {
44 false
45 }
46
47 fn apply_diff_and_convert(&mut self, diff: InternalDiff, _ctx: DiffApplyContext) -> Diff {
48 if let InternalDiff::Counter(diff) = diff {
49 self.value += diff;
50 Diff::Counter(diff)
51 } else {
52 unreachable!()
53 }
54 }
55
56 fn apply_diff(&mut self, diff: InternalDiff, ctx: DiffApplyContext) -> LoroResult<()> {
57 let _ = self.apply_diff_and_convert(diff, ctx);
58 Ok(())
59 }
60
61 fn apply_local_op(&mut self, raw_op: &RawOp, _op: &Op) -> LoroResult<ApplyLocalOpReturn> {
62 if let RawOpContent::Counter(diff) = raw_op.content {
63 self.value += diff;
64 Ok(Default::default())
65 } else {
66 unreachable!()
67 }
68 }
69
70 #[doc = " Convert a state to a diff, such that an empty state will be transformed into the same as this state when it\'s applied."]
71 fn to_diff(&mut self, _doc: &Weak<LoroDocInner>) -> Diff {
72 Diff::Counter(self.value)
73 }
74
75 fn get_value(&mut self) -> LoroValue {
76 LoroValue::Double(self.value)
77 }
78
79 #[doc = " Get the index of the child container"]
80 #[allow(unused)]
81 fn get_child_index(&self, id: &ContainerID) -> Option<Index> {
82 None
83 }
84
85 #[allow(unused)]
86 fn get_child_containers(&self) -> Vec<ContainerID> {
87 vec![]
88 }
89
90 fn contains_child(&self, _id: &ContainerID) -> bool {
91 false
92 }
93
94 fn fork(&self, _config: &Configure) -> Self {
95 self.clone()
96 }
97}
98
99mod snapshot {
100 use crate::state::FastStateSnapshot;
101
102 use super::*;
103
104 impl FastStateSnapshot for CounterState {
105 fn encode_snapshot_fast<W: std::io::Write>(&mut self, mut w: W) {
106 let bytes = self.value.to_le_bytes();
107 w.write_all(&bytes).unwrap();
108 }
109
110 fn decode_value(bytes: &[u8]) -> LoroResult<(LoroValue, &[u8])> {
111 // Builds without the counter feature can re-export an untouched counter as header only.
112 if bytes.is_empty() {
113 return Ok((LoroValue::Double(0.0), bytes));
114 }
115
116 if bytes.len() != 8 {
117 return Err(loro_common::LoroError::DecodeError(
118 "Decode counter value failed".to_string().into_boxed_str(),
119 ));
120 }
121
122 let value = f64::from_le_bytes(bytes[..8].try_into().unwrap());
123 Ok((LoroValue::Double(value), &bytes[8..]))
124 }
125
126 fn decode_snapshot_fast(
127 idx: ContainerIdx,
128 v: (LoroValue, &[u8]),
129 _ctx: crate::state::ContainerCreationContext,
130 ) -> LoroResult<Self>
131 where
132 Self: Sized,
133 {
134 if !v.1.is_empty() {
135 return Err(loro_common::LoroError::DecodeError(
136 "Decode counter state failed".to_string().into_boxed_str(),
137 ));
138 }
139
140 let mut counter = CounterState::new(idx);
141 counter.value = *v.0.as_double().unwrap();
142 Ok(counter)
143 }
144 }
145}