forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

content.rs470 lines, 15.3 KiBHistoryRawDownload
1use std::sync::Arc;
2
3use enum_as_inner::EnumAsInner;
4use loro_common::{ContainerID, ContainerType, LoroValue};
5use rle::{HasLength, Mergable, Sliceable};
6#[cfg(feature = "wasm")]
7use serde::{Deserialize, Serialize};
8
9use crate::{
10 container::{
11 list::list_op::{InnerListOp, ListOp},
12 map::MapSet,
13 tree::tree_op::TreeOp,
14 },
15 encoding::OwnedValue,
16};
17
18#[derive(EnumAsInner, Debug, Clone)]
19pub enum InnerContent {
20 List(InnerListOp),
21 Map(MapSet),
22 Tree(Arc<TreeOp>),
23 // The future content should not use any encoded arena context.
24 Future(FutureInnerContent),
25}
26
27impl InnerContent {
28 pub fn visit_created_children(&self, f: &mut dyn FnMut(&ContainerID)) {
29 match self {
30 InnerContent::List(l) => match l {
31 InnerListOp::Insert { slice, .. } => {
32 for v in slice.as_slice() {
33 if let LoroValue::Container(c) = v {
34 f(c);
35 }
36 }
37 }
38 InnerListOp::Set { value, .. } => {
39 if let LoroValue::Container(c) = value {
40 f(c);
41 }
42 }
43
44 InnerListOp::Move { .. } => {}
45 InnerListOp::InsertText { .. } => {}
46 InnerListOp::Delete(_) => {}
47 InnerListOp::StyleStart { .. } => {}
48 InnerListOp::StyleEnd => {}
49 },
50 crate::op::InnerContent::Map(m) => {
51 if let Some(LoroValue::Container(c)) = &m.value {
52 f(c);
53 }
54 }
55 crate::op::InnerContent::Tree(t) => {
56 if let TreeOp::Create { target, .. } = t.as_ref() {
57 let id = target.associated_meta_container();
58 f(&id);
59 }
60 }
61 crate::op::InnerContent::Future(f) => match &f {
62 #[cfg(feature = "counter")]
63 crate::op::FutureInnerContent::Counter(_) => {}
64 crate::op::FutureInnerContent::Unknown { .. } => {}
65 },
66 }
67 }
68}
69
70impl InnerContent {
71 pub fn estimate_storage_size(&self, kind: ContainerType) -> usize {
72 match self {
73 InnerContent::List(l) => l.estimate_storage_size(kind),
74 InnerContent::Map(_) => 3,
75 InnerContent::Tree(_) => 8,
76 InnerContent::Future(f) => f.estimate_storage_size(),
77 }
78 }
79}
80
81#[derive(EnumAsInner, Debug, Clone)]
82pub enum FutureInnerContent {
83 #[cfg(feature = "counter")]
84 Counter(f64),
85 Unknown {
86 prop: i32,
87 value: Box<OwnedValue>,
88 },
89}
90impl FutureInnerContent {
91 fn estimate_storage_size(&self) -> usize {
92 match self {
93 #[cfg(feature = "counter")]
94 FutureInnerContent::Counter(_) => 4,
95 FutureInnerContent::Unknown { .. } => 6,
96 }
97 }
98}
99
100// Note: It will be encoded into binary format, so the order of its fields should not be changed.
101#[derive(EnumAsInner, Debug, PartialEq)]
102#[cfg_attr(feature = "wasm", derive(Serialize, Deserialize,))]
103pub enum RawOpContent<'a> {
104 Map(MapSet),
105 List(ListOp<'a>),
106 Tree(Arc<TreeOp>),
107 #[cfg(feature = "counter")]
108 Counter(f64),
109 Unknown {
110 prop: i32,
111 value: OwnedValue,
112 },
113}
114
115impl Clone for RawOpContent<'_> {
116 fn clone(&self) -> Self {
117 match self {
118 Self::Map(arg0) => Self::Map(arg0.clone()),
119 Self::List(arg0) => Self::List(arg0.clone()),
120 Self::Tree(arg0) => Self::Tree(arg0.clone()),
121 #[cfg(feature = "counter")]
122 Self::Counter(x) => Self::Counter(*x),
123 Self::Unknown { prop, value } => Self::Unknown {
124 prop: *prop,
125 value: value.clone(),
126 },
127 }
128 }
129}
130
131impl RawOpContent<'_> {
132 pub fn to_static(&self) -> RawOpContent<'static> {
133 match self {
134 Self::Map(arg0) => RawOpContent::Map(arg0.clone()),
135 Self::List(arg0) => match arg0 {
136 ListOp::Insert { slice, pos } => RawOpContent::List(ListOp::Insert {
137 slice: slice.to_static(),
138 pos: *pos,
139 }),
140 ListOp::Delete(x) => RawOpContent::List(ListOp::Delete(*x)),
141 ListOp::StyleStart {
142 start,
143 end,
144 key,
145 value,
146 info,
147 } => RawOpContent::List(ListOp::StyleStart {
148 start: *start,
149 end: *end,
150 key: key.clone(),
151 value: value.clone(),
152 info: *info,
153 }),
154 ListOp::StyleEnd => RawOpContent::List(ListOp::StyleEnd),
155 ListOp::Move {
156 from,
157 to,
158 elem_id: from_id,
159 } => RawOpContent::List(ListOp::Move {
160 from: *from,
161 to: *to,
162 elem_id: *from_id,
163 }),
164 ListOp::Set { elem_id, value } => RawOpContent::List(ListOp::Set {
165 elem_id: *elem_id,
166 value: value.clone(),
167 }),
168 },
169 Self::Tree(arg0) => RawOpContent::Tree(arg0.clone()),
170 #[cfg(feature = "counter")]
171 Self::Counter(x) => RawOpContent::Counter(*x),
172 Self::Unknown { prop, value } => RawOpContent::Unknown {
173 prop: *prop,
174 value: value.clone(),
175 },
176 }
177 }
178}
179
180impl HasLength for RawOpContent<'_> {
181 fn content_len(&self) -> usize {
182 match self {
183 RawOpContent::Map(x) => x.content_len(),
184 RawOpContent::List(x) => x.content_len(),
185 RawOpContent::Tree(x) => x.content_len(),
186 #[cfg(feature = "counter")]
187 RawOpContent::Counter(_) => 1,
188 RawOpContent::Unknown { .. } => 1,
189 }
190 }
191}
192
193impl Mergable for RawOpContent<'_> {
194 fn is_mergable(&self, other: &Self, _conf: &()) -> bool
195 where
196 Self: Sized,
197 {
198 match (self, other) {
199 (RawOpContent::List(x), RawOpContent::List(y)) => x.is_mergable(y, &()),
200 (RawOpContent::Tree(x), RawOpContent::Tree(y)) => x.is_mergable(y, &()),
201 _ => false,
202 }
203 }
204
205 fn merge(&mut self, _other: &Self, _conf: &())
206 where
207 Self: Sized,
208 {
209 match self {
210 RawOpContent::List(x) => match _other {
211 RawOpContent::List(y) => x.merge(y, &()),
212 _ => unreachable!(),
213 },
214 _ => unreachable!(),
215 }
216 }
217}
218
219impl HasLength for InnerContent {
220 fn content_len(&self) -> usize {
221 match self {
222 InnerContent::List(list) => list.atom_len(),
223 InnerContent::Map(_) => 1,
224 InnerContent::Tree(_) => 1,
225 InnerContent::Future(_) => 1,
226 }
227 }
228}
229
230impl Sliceable for InnerContent {
231 fn slice(&self, from: usize, to: usize) -> Self {
232 match self {
233 a @ InnerContent::Map(_) => {
234 assert!(from == 0 && to == 1);
235 a.clone()
236 }
237 a @ InnerContent::Tree(_) => {
238 assert!(from == 0 && to == 1);
239 a.clone()
240 }
241 InnerContent::List(x) => InnerContent::List(x.slice(from, to)),
242 InnerContent::Future(f) => {
243 assert!(from == 0 && to == 1);
244 InnerContent::Future(f.clone())
245 }
246 }
247 }
248}
249
250impl Mergable for InnerContent {
251 fn is_mergable(&self, other: &Self, _conf: &()) -> bool
252 where
253 Self: Sized,
254 {
255 match (self, other) {
256 (InnerContent::List(x), InnerContent::List(y)) => x.is_mergable(y, &()),
257 _ => false,
258 }
259 }
260
261 fn merge(&mut self, _other: &Self, _conf: &())
262 where
263 Self: Sized,
264 {
265 match self {
266 InnerContent::List(x) => match _other {
267 InnerContent::List(y) => x.merge(y, &()),
268 _ => unreachable!(),
269 },
270 _ => unreachable!(),
271 }
272 }
273}
274
275#[cfg(test)]
276mod tests {
277 use std::{borrow::Cow, sync::Arc};
278
279 use fractional_index::FractionalIndex;
280 use loro_common::{ContainerID, ContainerType, TreeID};
281 use rle::{HasLength, Mergable, Sliceable};
282
283 use super::*;
284 use crate::{
285 container::{
286 list::list_op::{DeleteSpanWithId, ListOp},
287 map::MapSet,
288 tree::tree_op::TreeOp,
289 },
290 op::{ListSlice, ValueSlice},
291 InternalString, LoroValue, ID,
292 };
293
294 #[test]
295 fn raw_op_content_reports_lengths_and_static_content_without_borrowing() {
296 let raw_insert = RawOpContent::List(ListOp::Insert {
297 slice: ListSlice::RawData(Cow::Owned(vec![1_i64.into(), 2_i64.into()])),
298 pos: 3,
299 });
300 assert_eq!(raw_insert.content_len(), 2);
301 match raw_insert.to_static() {
302 RawOpContent::List(ListOp::Insert { slice, pos }) => {
303 assert_eq!(pos, 3);
304 assert_eq!(
305 slice,
306 ListSlice::RawData(Cow::Owned(vec![1_i64.into(), 2_i64.into()]))
307 );
308 }
309 other => panic!("expected list insert, got {other:?}"),
310 }
311
312 let raw_map = RawOpContent::Map(MapSet {
313 key: InternalString::from("title"),
314 value: Some("draft".into()),
315 });
316 assert_eq!(raw_map.content_len(), 1);
317 assert_eq!(raw_map.to_static(), raw_map);
318
319 let raw_tree = RawOpContent::Tree(Arc::new(TreeOp::Delete {
320 target: TreeID::new(2, 9),
321 }));
322 assert_eq!(raw_tree.content_len(), 1);
323 assert_eq!(raw_tree.to_static(), raw_tree);
324
325 let raw_unknown = RawOpContent::Unknown {
326 prop: 7,
327 value: OwnedValue::I64(11),
328 };
329 assert_eq!(raw_unknown.content_len(), 1);
330 assert_eq!(raw_unknown.to_static(), raw_unknown);
331
332 #[cfg(feature = "counter")]
333 {
334 let raw_counter = RawOpContent::Counter(1.25);
335 assert_eq!(raw_counter.content_len(), 1);
336 assert_eq!(raw_counter.to_static(), raw_counter);
337 }
338 }
339
340 #[test]
341 fn raw_op_content_merges_only_mergeable_list_operations() {
342 let mut left =
343 RawOpContent::List(ListOp::Delete(DeleteSpanWithId::new(ID::new(1, 0), 0, 1)));
344 let right = RawOpContent::List(ListOp::Delete(DeleteSpanWithId::new(ID::new(1, 1), 0, 1)));
345 assert!(left.is_mergable(&right, &()));
346 left.merge(&right, &());
347 assert_eq!(left.content_len(), 2);
348
349 let map = RawOpContent::Map(MapSet {
350 key: InternalString::from("k"),
351 value: Some(1_i64.into()),
352 });
353 assert!(!left.is_mergable(&map, &()));
354 }
355
356 #[test]
357 fn inner_content_lengths_storage_estimates_slices_and_merges_follow_inner_ops() {
358 let mut left = InnerContent::List(InnerListOp::Insert {
359 slice: ValueSlice::new(vec![0_i64.into(), 1_i64.into()]),
360 pos: 0,
361 });
362 let right = InnerContent::List(InnerListOp::Insert {
363 slice: ValueSlice::new(vec![2_i64.into(), 3_i64.into()]),
364 pos: 2,
365 });
366 assert_eq!(left.content_len(), 2);
367 assert_eq!(left.estimate_storage_size(ContainerType::List), 8);
368 assert!(left.is_mergable(&right, &()));
369 left.merge(&right, &());
370 assert_eq!(left.content_len(), 4);
371
372 let sliced = left.slice(1, 3);
373 match sliced {
374 InnerContent::List(InnerListOp::Insert { slice, pos }) => {
375 assert_eq!(slice, ValueSlice::new(vec![1_i64.into(), 2_i64.into()]));
376 assert_eq!(pos, 1);
377 }
378 other => panic!("expected sliced list insert, got {other:?}"),
379 }
380
381 let map = InnerContent::Map(MapSet {
382 key: InternalString::from("flag"),
383 value: Some(true.into()),
384 });
385 assert_eq!(map.content_len(), 1);
386 assert_eq!(map.estimate_storage_size(ContainerType::Map), 3);
387 assert!(matches!(map.slice(0, 1), InnerContent::Map(_)));
388
389 let tree = InnerContent::Tree(Arc::new(TreeOp::Delete {
390 target: TreeID::new(4, 5),
391 }));
392 assert_eq!(tree.content_len(), 1);
393 assert_eq!(tree.estimate_storage_size(ContainerType::Tree), 8);
394 assert!(matches!(tree.slice(0, 1), InnerContent::Tree(_)));
395
396 let future = InnerContent::Future(FutureInnerContent::Unknown {
397 prop: 99,
398 value: Box::new(OwnedValue::Null),
399 });
400 assert_eq!(future.content_len(), 1);
401 assert_eq!(future.estimate_storage_size(ContainerType::Unknown(3)), 6);
402 assert!(matches!(future.slice(0, 1), InnerContent::Future(_)));
403
404 #[cfg(feature = "counter")]
405 {
406 let counter = InnerContent::Future(FutureInnerContent::Counter(2.0));
407 assert_eq!(counter.estimate_storage_size(ContainerType::Counter), 4);
408 }
409 }
410
411 #[test]
412 fn visit_created_children_reports_containers_created_by_list_map_and_tree_content() {
413 let list_child = ContainerID::new_normal(ID::new(1, 1), ContainerType::List);
414 let text_child = ContainerID::new_normal(ID::new(1, 2), ContainerType::Text);
415 let list = InnerContent::List(InnerListOp::Insert {
416 slice: ValueSlice::new(vec![
417 LoroValue::Container(list_child.clone()),
418 "plain".into(),
419 LoroValue::Container(text_child.clone()),
420 ]),
421 pos: 0,
422 });
423 let mut children = Vec::new();
424 list.visit_created_children(&mut |id| children.push(id.clone()));
425 assert_eq!(children, vec![list_child.clone(), text_child.clone()]);
426
427 let map_child = ContainerID::new_normal(ID::new(2, 1), ContainerType::Map);
428 let map = InnerContent::Map(MapSet {
429 key: InternalString::from("child"),
430 value: Some(LoroValue::Container(map_child.clone())),
431 });
432 let mut children = Vec::new();
433 map.visit_created_children(&mut |id| children.push(id.clone()));
434 assert_eq!(children, vec![map_child]);
435
436 let tree_target = TreeID::new(3, 7);
437 let tree = InnerContent::Tree(Arc::new(TreeOp::Create {
438 target: tree_target,
439 parent: None,
440 position: FractionalIndex::default(),
441 }));
442 let mut children = Vec::new();
443 tree.visit_created_children(&mut |id| children.push(id.clone()));
444 assert_eq!(children, vec![tree_target.associated_meta_container()]);
445
446 for tree in [
447 TreeOp::Move {
448 target: tree_target,
449 parent: None,
450 position: FractionalIndex::default(),
451 },
452 TreeOp::Delete {
453 target: tree_target,
454 },
455 ] {
456 let tree = InnerContent::Tree(Arc::new(tree));
457 let mut children = Vec::new();
458 tree.visit_created_children(&mut |id| children.push(id.clone()));
459 assert!(children.is_empty());
460 }
461
462 let future = InnerContent::Future(FutureInnerContent::Unknown {
463 prop: 1,
464 value: Box::new(OwnedValue::False),
465 });
466 let mut children = Vec::new();
467 future.visit_created_children(&mut |id| children.push(id.clone()));
468 assert!(children.is_empty());
469 }
470}