forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

tracker.rs896 lines, 31.9 KiBHistoryRawDownload
1use std::ops::ControlFlow;
2
3use generic_btree::{
4 rle::{HasLength as _, Sliceable},
5 LeafIndex,
6};
7use loro_common::{Counter, HasId, HasIdSpan, IdFull, IdSpan, Lamport, PeerID, ID};
8use rle::HasLength as _;
9use tracing::instrument;
10
11use crate::{cursor::AbsolutePosition, VersionVector};
12
13use self::{crdt_rope::CrdtRope, id_to_cursor::IdToCursor};
14
15use super::{
16 fugue_span::{FugueSpan, Status},
17 RichtextChunk,
18};
19
20mod crdt_rope;
21mod id_to_cursor;
22
23/// Length of the placeholder span that stands for history the tracker has not
24/// replayed (`Tracker::new_with_unknown`). Op positions must stay below it; see
25/// `InnerListOp::check_positions`.
26pub(crate) const UNKNOWN_SPAN_LEN: u32 = u32::MAX / 4;
27
28pub(crate) use crdt_rope::CrdtRopeDelta;
29
30#[derive(Debug)]
31pub(crate) struct Tracker {
32 applied_vv: VersionVector,
33 current_vv: VersionVector,
34 rope: CrdtRope,
35 id_to_cursor: IdToCursor,
36}
37
38impl Default for Tracker {
39 fn default() -> Self {
40 Self::new_with_unknown()
41 }
42}
43
44pub(super) const UNKNOWN_PEER_ID: PeerID = u64::MAX;
45impl Tracker {
46 pub fn new_with_unknown() -> Self {
47 let mut this = Self {
48 rope: CrdtRope::new(),
49 id_to_cursor: IdToCursor::default(),
50 applied_vv: Default::default(),
51 current_vv: Default::default(),
52 };
53
54 let result = this.rope.tree.push(FugueSpan {
55 content: RichtextChunk::new_unknown(UNKNOWN_SPAN_LEN),
56 id: IdFull::new(UNKNOWN_PEER_ID, 0, 0),
57 real_id: None,
58 status: Status::default(),
59 diff_status: None,
60 origin_left: None,
61 origin_right: None,
62 });
63 this.id_to_cursor.insert_without_split(
64 ID::new(UNKNOWN_PEER_ID, 0),
65 id_to_cursor::Cursor::new_insert(result.leaf, UNKNOWN_SPAN_LEN as usize),
66 );
67 this
68 }
69
70 #[allow(unused)]
71 fn new() -> Self {
72 Self::new_empty()
73 }
74
75 pub(crate) fn new_empty() -> Self {
76 Self {
77 rope: CrdtRope::new(),
78 id_to_cursor: IdToCursor::default(),
79 applied_vv: Default::default(),
80 current_vv: Default::default(),
81 }
82 }
83
84 #[inline]
85 pub fn all_vv(&self) -> &VersionVector {
86 &self.applied_vv
87 }
88
89 #[inline]
90 pub fn current_vv(&self) -> &VersionVector {
91 &self.current_vv
92 }
93
94 pub(crate) fn insert(&mut self, op_id: IdFull, pos: usize, content: RichtextChunk) {
95 self.insert_with(op_id, pos, content.len(), |skip| {
96 if skip == 0 {
97 content
98 } else {
99 content.slice(skip..)
100 }
101 });
102 }
103
104 /// [`Self::insert`] for an op of `len` atoms whose content is built by
105 /// `content(skip)` for the part after its first `skip` atoms, which the
106 /// tracker has not applied yet. `content` is not called when the whole op
107 /// was applied. A caller that records the content elsewhere (the diff
108 /// calculators' text and value tables) then records each atom once,
109 /// however often a checkout replays the op.
110 pub(crate) fn insert_with(
111 &mut self,
112 mut op_id: IdFull,
113 mut pos: usize,
114 len: usize,
115 content: impl FnOnce(usize) -> RichtextChunk,
116 ) {
117 let mut skip = 0;
118 if let ControlFlow::Break(_) = self.skip_applied(op_id.id(), len, |applied_counter_end| {
119 skip = (applied_counter_end - op_id.counter) as usize;
120 }) {
121 return;
122 }
123
124 op_id.lamport += skip as Lamport;
125 op_id.counter += skip as Counter;
126 pos += skip;
127 let content = content(skip);
128 debug_assert_eq!(content.len(), len - skip);
129 self._insert(pos, content, op_id);
130 }
131
132 fn _insert(&mut self, pos: usize, content: RichtextChunk, op_id: IdFull) {
133 self._insert_inner(pos, content, op_id, true);
134 }
135
136 pub(crate) fn insert_seeded(&mut self, pos: usize, content: RichtextChunk, op_id: IdFull) {
137 self._insert_inner(pos, content, op_id, false);
138 }
139
140 fn _insert_inner(
141 &mut self,
142 pos: usize,
143 content: RichtextChunk,
144 op_id: IdFull,
145 update_vv: bool,
146 ) {
147 let result = self.rope.insert(
148 pos,
149 FugueSpan {
150 content,
151 id: op_id,
152 real_id: if op_id.peer == UNKNOWN_PEER_ID {
153 None
154 } else {
155 Some(op_id.id().try_into().unwrap())
156 },
157 status: Status::default(),
158 diff_status: None,
159 origin_left: None,
160 origin_right: None,
161 },
162 |id| self.id_to_cursor.get_insert(id).unwrap(),
163 );
164 self.id_to_cursor.insert(
165 op_id.id(),
166 id_to_cursor::Cursor::new_insert(result.leaf, content.len()),
167 );
168
169 self.update_insert_by_split(&result.splitted.arr);
170
171 if update_vv {
172 let end_id = op_id.inc(content.len() as Counter);
173 self.current_vv.extend_to_include_end_id(end_id.id());
174 self.applied_vv.extend_to_include_end_id(end_id.id());
175 }
176 }
177
178 fn update_insert_by_split(&mut self, split: &[LeafIndex]) {
179 match split.len() {
180 0 => {}
181 1 => {
182 let new_leaf_idx = split[0];
183 let leaf = self.rope.tree().get_elem(new_leaf_idx).unwrap();
184 self.id_to_cursor
185 .update_insert(leaf.id_span(), new_leaf_idx);
186 }
187 _ => {
188 let mut updates = Vec::with_capacity(split.len());
189 for &new_leaf_idx in split {
190 let leaf = self.rope.tree().get_elem(new_leaf_idx).unwrap();
191 updates.push((leaf.id_span(), new_leaf_idx));
192 }
193 self.id_to_cursor.update_insert_batch(&mut updates);
194 }
195 }
196 }
197
198 /// Delete the element from pos..pos+len
199 ///
200 /// If `reverse` is true, the deletion happens from the end of the range to the start.
201 /// So the first op is the one that deletes element at `pos+len-1`, the last op
202 /// is the one that deletes element at `pos`.
203 ///
204 /// - op_id: the first op that perform the deletion
205 /// - target_start_id: in the target deleted span, it's the first id of the span
206 /// - pos: the start pos of the deletion in the target span
207 /// - len: the length of the deletion span
208 /// - reverse: if true, the kth op delete the last kth element of the span
209 pub(crate) fn delete(
210 &mut self,
211 mut op_id: ID,
212 mut target_start_id: ID,
213 pos: usize,
214 mut len: usize,
215 reverse: bool,
216 ) {
217 if let ControlFlow::Break(_) = self.skip_applied(op_id, len, |applied_counter_end: i32| {
218 // the op is partially included, need to slice the op
219 let start = (applied_counter_end - op_id.counter) as usize;
220 op_id.counter = applied_counter_end;
221 if !reverse {
222 target_start_id = target_start_id.inc(start as i32);
223 }
224 // Okay, this looks pretty weird, but it's correct.
225 // If it's reverse, we don't need to change the target_start_id, because target_start_id always pointing towards the
226 // leftmost element of the span. After applying the initial part of the deletion, which starts from the right side,
227 // the target_start_id will be still pointing towards the same leftmost element, thus no need to change.
228 len -= start;
229 // If reverse, don't need to change the pos, because it's deleting backwards.
230 // If not reverse, we don't need to change the pos either, because the `start` chars after it are already deleted
231 }) {
232 return;
233 }
234
235 // tracing::info!("after forwarding pos={} len={}", pos, len);
236
237 self._delete(target_start_id, pos, len, reverse, op_id);
238 }
239
240 fn _delete(&mut self, target_start_id: ID, pos: usize, len: usize, reverse: bool, op_id: ID) {
241 let mut ans = Vec::new();
242 let split = self
243 .rope
244 .delete(target_start_id, pos, len, reverse, &mut |span| {
245 let mut id_span = span.id_span();
246 if reverse {
247 id_span.reverse();
248 }
249 ans.push(id_span);
250 });
251
252 let mut cur_id = op_id;
253 for id_span in ans {
254 let len = id_span.atom_len();
255 self.id_to_cursor
256 .insert(cur_id, id_to_cursor::Cursor::Delete(id_span));
257 cur_id = cur_id.inc(len as Counter);
258 }
259
260 debug_assert_eq!(cur_id.counter - op_id.counter, len as Counter);
261 for s in split {
262 self.update_insert_by_split(&s.arr);
263 }
264
265 let end_id = op_id.inc(len as Counter);
266 self.current_vv.extend_to_include_end_id(end_id);
267 self.applied_vv.extend_to_include_end_id(end_id);
268 }
269
270 fn skip_applied(
271 &mut self,
272 op_id: ID,
273 len: usize,
274 mut f: impl FnMut(Counter),
275 ) -> ControlFlow<()> {
276 let last_id = op_id.inc(len as Counter - 1);
277 let applied_counter_end = self.applied_vv.get(&last_id.peer).copied().unwrap_or(0);
278 if applied_counter_end > op_id.counter {
279 if !self.current_vv.includes_id(last_id) {
280 // PERF: may be slow
281 let mut updates = Default::default();
282 let cnt_start = self.current_vv.get(&op_id.peer).copied().unwrap_or(0);
283 self.forward(
284 IdSpan::new(op_id.peer, cnt_start, op_id.counter + len as Counter),
285 &mut updates,
286 );
287 self.batch_update(updates, false);
288 }
289
290 if applied_counter_end > last_id.counter {
291 self.current_vv.extend_to_include_last_id(last_id);
292 return ControlFlow::Break(());
293 }
294
295 f(applied_counter_end);
296 }
297 ControlFlow::Continue(())
298 }
299
300 /// Internally it's delete at the src and insert at the dst.
301 ///
302 /// But it needs special behavior for id_to_cursor data structure
303 ///
304 #[instrument(skip(self))]
305 pub(crate) fn move_item(
306 &mut self,
307 op_id: IdFull,
308 deleted_id: ID,
309 from_pos: usize,
310 to_pos: usize,
311 ) {
312 if let ControlFlow::Break(_) = self.skip_applied(op_id.id(), 1, |_| unreachable!()) {
313 return;
314 }
315
316 // We record the **fake** id of the deleted item, and store it in the `id_to_cursor`.
317 // This is because when we retreat, we need to know the **fake** id of the deleted item,
318 // so that we can look up the insert pos in `id_to_cursor`
319 //
320 // > `id_to_cursor` only stores the mappings from **fake** insert id to the leaf index.
321 // > **Fake** means the id may be a temporary placeholder, created with UNKNOWN_PEER_ID.
322 let mut fake_delete_id = None;
323 let split = self.rope.delete(deleted_id, from_pos, 1, false, &mut |s| {
324 debug_assert_eq!(s.rle_len(), 1);
325 fake_delete_id = Some(s.id.id());
326 });
327
328 for s in split {
329 self.update_insert_by_split(&s.arr);
330 }
331
332 let result = self.rope.insert(
333 to_pos,
334 FugueSpan {
335 // we need to use the special move content to avoid
336 // its merging with other [FugueSpan], which will make
337 // id_to_cursor need to track its split.
338 // It would be much harder to implement correctly
339 content: RichtextChunk::new_move(),
340 id: op_id,
341 real_id: if op_id.peer == UNKNOWN_PEER_ID {
342 None
343 } else {
344 Some(op_id.id().try_into().unwrap())
345 },
346 status: Status::default(),
347 diff_status: None,
348 origin_left: None,
349 origin_right: None,
350 },
351 |id| self.id_to_cursor.get_insert(id).unwrap(),
352 );
353 self.update_insert_by_split(&result.splitted.arr);
354
355 self.id_to_cursor.insert(
356 op_id.id(),
357 id_to_cursor::Cursor::new_move(result.leaf, fake_delete_id.unwrap()),
358 );
359
360 let end_id = op_id.inc(1);
361 self.current_vv.extend_to_include_end_id(end_id.id());
362 self.applied_vv.extend_to_include_end_id(end_id.id());
363 }
364
365 #[inline]
366 pub(crate) fn checkout(&mut self, vv: &VersionVector) {
367 self._checkout(vv, false);
368 }
369
370 fn _checkout(&mut self, vv: &VersionVector, on_diff_status: bool) {
371 // tracing::info!("Checkout to {:?} from {:?}", vv, self.current_vv);
372 if on_diff_status {
373 self.rope.clear_diff_status();
374 }
375
376 let current_vv = std::mem::take(&mut self.current_vv);
377 let (retreat, forward) = current_vv.diff_iter(vv);
378 let mut updates = Vec::new();
379 for span in retreat {
380 for c in self.id_to_cursor.iter(span) {
381 match c {
382 id_to_cursor::IterCursor::Insert { leaf, id_span } => {
383 updates.push(crdt_rope::LeafUpdate {
384 leaf,
385 id_span,
386 set_future: Some(true),
387 delete_times_diff: 0,
388 })
389 }
390 id_to_cursor::IterCursor::Delete(span) => {
391 for to_del in self.id_to_cursor.iter(span) {
392 match to_del {
393 id_to_cursor::IterCursor::Insert { leaf, id_span } => {
394 updates.push(crdt_rope::LeafUpdate {
395 leaf,
396 id_span,
397 set_future: None,
398 delete_times_diff: -1,
399 })
400 }
401 id_to_cursor::IterCursor::Move {
402 from_id: _,
403 to_leaf,
404 new_op_id,
405 } => updates.push(crdt_rope::LeafUpdate {
406 leaf: to_leaf,
407 id_span: new_op_id.to_span(1),
408 set_future: None,
409 delete_times_diff: -1,
410 }),
411 _ => unreachable!(),
412 }
413 }
414 }
415 id_to_cursor::IterCursor::Move {
416 from_id: from,
417 to_leaf: to,
418 new_op_id: op_id,
419 } => {
420 let mut visited = false;
421 for to_del in self.id_to_cursor.iter(IdSpan::new(
422 from.peer,
423 from.counter,
424 from.counter + 1,
425 )) {
426 visited = true;
427
428 match to_del {
429 id_to_cursor::IterCursor::Move {
430 from_id: _,
431 to_leaf: to,
432 new_op_id: op_id,
433 } => updates.push(crdt_rope::LeafUpdate {
434 leaf: to,
435 id_span: op_id.to_span(1),
436 set_future: None,
437 delete_times_diff: -1,
438 }),
439 // Un delete the from
440 id_to_cursor::IterCursor::Insert { leaf, id_span } => {
441 debug_assert_eq!(id_span.atom_len(), 1);
442 debug_assert_eq!(id_span.counter.start, from.counter);
443 updates.push(crdt_rope::LeafUpdate {
444 leaf,
445 id_span,
446 set_future: None,
447 delete_times_diff: -1,
448 })
449 }
450 _ => unreachable!(),
451 }
452 }
453 assert!(visited);
454 // insert the new
455 updates.push(crdt_rope::LeafUpdate {
456 leaf: to,
457 id_span: IdSpan::new(op_id.peer, op_id.counter, op_id.counter + 1),
458 set_future: Some(true),
459 delete_times_diff: 0,
460 });
461 }
462 }
463 }
464 }
465
466 for span in forward {
467 self.forward(span, &mut updates);
468 }
469
470 if !on_diff_status {
471 self.current_vv = vv.clone();
472 } else {
473 self.current_vv = current_vv;
474 }
475
476 self.batch_update(updates, on_diff_status);
477 }
478
479 fn batch_update(&mut self, updates: Vec<crdt_rope::LeafUpdate>, on_diff_status: bool) {
480 let leaf_indexes = self.rope.update(updates, on_diff_status);
481 self.update_insert_by_split(&leaf_indexes);
482 }
483
484 fn forward(&mut self, span: loro_common::IdSpan, updates: &mut Vec<crdt_rope::LeafUpdate>) {
485 for c in self.id_to_cursor.iter(span) {
486 match c {
487 id_to_cursor::IterCursor::Insert { leaf, id_span } => {
488 updates.push(crdt_rope::LeafUpdate {
489 leaf,
490 id_span,
491 set_future: Some(false),
492 delete_times_diff: 0,
493 })
494 }
495 id_to_cursor::IterCursor::Delete(span) => {
496 for to_del in self.id_to_cursor.iter(span) {
497 match to_del {
498 id_to_cursor::IterCursor::Insert { leaf, id_span } => {
499 updates.push(crdt_rope::LeafUpdate {
500 leaf,
501 id_span,
502 set_future: None,
503 delete_times_diff: 1,
504 })
505 }
506 id_to_cursor::IterCursor::Move {
507 from_id: _,
508 to_leaf,
509 new_op_id,
510 } => updates.push(crdt_rope::LeafUpdate {
511 leaf: to_leaf,
512 id_span: new_op_id.to_span(1),
513 set_future: None,
514 delete_times_diff: 1,
515 }),
516 _ => unreachable!(),
517 }
518 }
519 }
520 id_to_cursor::IterCursor::Move {
521 from_id: from,
522 to_leaf: to,
523 new_op_id: op_id,
524 } => {
525 for to_del in self.id_to_cursor.iter(IdSpan::new(
526 from.peer,
527 from.counter,
528 from.counter + 1,
529 )) {
530 match to_del {
531 id_to_cursor::IterCursor::Move {
532 from_id: _,
533 to_leaf: to,
534 new_op_id: op_id,
535 } => updates.push(crdt_rope::LeafUpdate {
536 leaf: to,
537 id_span: op_id.to_span(1),
538 set_future: None,
539 delete_times_diff: 1,
540 }),
541 id_to_cursor::IterCursor::Insert { leaf, id_span } => {
542 updates.push(crdt_rope::LeafUpdate {
543 leaf,
544 id_span,
545 set_future: None,
546 delete_times_diff: 1,
547 })
548 }
549 _ => unreachable!(),
550 }
551 }
552
553 updates.push(crdt_rope::LeafUpdate {
554 leaf: to,
555 id_span: IdSpan::new(op_id.peer, op_id.counter, op_id.counter + 1),
556 set_future: Some(false),
557 delete_times_diff: 0,
558 });
559 }
560 }
561 }
562 }
563
564 #[allow(unused)]
565 pub(crate) fn check(&self) {
566 if !cfg!(debug_assertions) {
567 return;
568 }
569
570 self.check_vv_correctness();
571 self.check_id_to_cursor_insertions_correctness();
572 }
573
574 fn check_vv_correctness(&self) {
575 if !cfg!(debug_assertions) {
576 return;
577 }
578
579 for span in self.rope.tree().iter() {
580 if span.id.peer == UNKNOWN_PEER_ID {
581 continue;
582 }
583
584 let id_span = span.id_span();
585 assert!(self.all_vv().includes_id(id_span.id_last()));
586 if span.status.future {
587 assert!(!self.current_vv.includes_id(id_span.id_start()));
588 } else {
589 assert!(self.current_vv.includes_id(id_span.id_last()));
590 }
591 }
592 }
593
594 // It can only check the correctness of insertions in id_to_cursor.
595 // The deletions are not checked.
596 fn check_id_to_cursor_insertions_correctness(&self) {
597 if !cfg!(debug_assertions) {
598 return;
599 }
600
601 for rope_elem in self.rope.tree().iter() {
602 let id_span = rope_elem.id_span();
603 let leaf_from_start = self.id_to_cursor.get_insert(id_span.id_start()).unwrap();
604 let leaf_from_last = self.id_to_cursor.get_insert(id_span.id_last()).unwrap();
605 assert_eq!(leaf_from_start, leaf_from_last);
606 let elem_from_id_to_cursor_map = self.rope.tree().get_elem(leaf_from_last).unwrap();
607 assert_eq!(rope_elem, elem_from_id_to_cursor_map);
608 }
609
610 for content in self.id_to_cursor.iter_all() {
611 match content {
612 id_to_cursor::IterCursor::Insert { leaf, id_span } => {
613 let leaf = self.rope.tree().get_elem(leaf).unwrap();
614 let span = leaf.id_span();
615 span.contains(id_span.id_start());
616 span.contains(id_span.id_last());
617 }
618 id_to_cursor::IterCursor::Delete(_) => {}
619 id_to_cursor::IterCursor::Move { .. } => {}
620 }
621 }
622 }
623
624 pub(crate) fn get_target_id_latest_index_at_new_version(
625 &self,
626 id: ID,
627 ) -> Option<AbsolutePosition> {
628 // TODO: PERF this can be sped up from O(n) to O(log(n)) but I'm not sure if it's worth it
629 let mut index = 0;
630 for span in self.rope.tree.iter() {
631 let is_activated = span.is_activated_in_diff();
632 let span_id = span.real_id();
633 let id_span = span_id.to_span(span.rle_len());
634 if id_span.contains(id) {
635 if is_activated {
636 index += (id.counter - id_span.counter.start) as usize;
637 }
638
639 return Some(AbsolutePosition {
640 pos: index,
641 side: if is_activated {
642 crate::cursor::Side::Middle
643 } else {
644 crate::cursor::Side::Left
645 },
646 });
647 }
648
649 if is_activated {
650 index += span.rle_len();
651 }
652 }
653
654 None
655 }
656
657 // #[tracing::instrument(skip(self), level = "info")]
658 pub(crate) fn diff(
659 &mut self,
660 from: &VersionVector,
661 to: &VersionVector,
662 ) -> impl Iterator<Item = CrdtRopeDelta> + '_ {
663 // tracing::info!("Init: {:#?}, ", &self);
664 self._checkout(from, false);
665 self._checkout(to, true);
666 // self.id_to_cursor.diagnose();
667 // tracing::trace!("Trace::diff {:#?}, ", &self);
668
669 self.rope.get_diff()
670 }
671
672 pub(crate) fn len(&self) -> usize {
673 self.rope.len()
674 }
675
676 pub(crate) fn active_real_span_at(&self, pos: usize) -> Option<(ID, usize)> {
677 self.rope.active_real_span_at(pos)
678 }
679
680 pub(crate) fn active_segments_of_real_id_span(
681 &self,
682 target_start: ID,
683 len: usize,
684 ) -> Vec<(ID, usize, usize)> {
685 let target_end = target_start.counter + len as Counter;
686 let mut index = 0;
687 let mut ans = Vec::new();
688
689 for span in self.rope.tree().iter() {
690 if !span.is_activated() {
691 continue;
692 }
693
694 let span_len = span.rle_len();
695 let real_id = span.real_id();
696 if real_id.peer == UNKNOWN_PEER_ID {
697 index += span_len;
698 continue;
699 }
700
701 if real_id.peer == target_start.peer {
702 let span_end = real_id.counter + span_len as Counter;
703 let overlap_start = real_id.counter.max(target_start.counter);
704 let overlap_end = span_end.min(target_end);
705 if overlap_start < overlap_end {
706 let offset = (overlap_start - real_id.counter) as usize;
707 let len = (overlap_end - overlap_start) as usize;
708 ans.push((
709 ID::new(target_start.peer, overlap_start),
710 index + offset,
711 len,
712 ));
713 }
714 }
715
716 index += span_len;
717 }
718
719 ans
720 }
721
722 pub(crate) fn mark_shallow_root_applied(&mut self, vv: &VersionVector) {
723 self.applied_vv = vv.clone();
724 self.current_vv = vv.clone();
725 }
726}
727
728#[cfg(test)]
729mod test {
730 use crate::{container::richtext::RichtextChunk, vv};
731 use generic_btree::rle::HasLength;
732
733 use super::*;
734 use std::time::Instant;
735
736 #[test]
737 fn test_len() {
738 let mut t = Tracker::new();
739 t.insert(IdFull::new(1, 0, 0), 0, RichtextChunk::new_text(0..2));
740 assert_eq!(t.rope.len(), 2);
741 t.checkout(&Default::default());
742 assert_eq!(t.rope.len(), 0);
743 t.insert(IdFull::new(2, 0, 0), 0, RichtextChunk::new_text(2..4));
744 let v = vv!(1 => 2, 2 => 2);
745 t.checkout(&v);
746 assert_eq!(&t.applied_vv, &v);
747 assert_eq!(t.rope.len(), 4);
748 }
749
750 /// A re-replayed op whose prefix the tracker has gets content built only
751 /// for the rest; a fully applied one gets none built.
752 #[test]
753 fn insert_with_builds_content_only_for_the_unapplied_suffix() {
754 let mut t = Tracker::new();
755 t.insert(IdFull::new(1, 0, 0), 0, RichtextChunk::new_text(0..2));
756
757 let mut skipped = None;
758 t.insert_with(IdFull::new(1, 0, 0), 0, 4, |skip| {
759 skipped = Some(skip);
760 RichtextChunk::new_text(10..12)
761 });
762 assert_eq!(skipped, Some(2));
763 assert_eq!(t.rope.len(), 4);
764
765 t.insert_with(IdFull::new(1, 0, 0), 0, 4, |_| {
766 panic!("a fully applied op must not build content")
767 });
768 assert_eq!(t.rope.len(), 4);
769 }
770
771 #[test]
772 fn test_retreat_and_forward_delete() {
773 let mut t = Tracker::new();
774 t.insert(IdFull::new(1, 0, 0), 0, RichtextChunk::new_text(0..10));
775 t.delete(ID::new(2, 0), ID::NONE_ID, 0, 10, true);
776 t.checkout(&vv!(1 => 10, 2=>5));
777 assert_eq!(t.rope.len(), 5);
778 t.checkout(&vv!(1 => 10, 2=>0));
779 assert_eq!(t.rope.len(), 10);
780 t.checkout(&vv!(1 => 10, 2=>10));
781 assert_eq!(t.rope.len(), 0);
782 t.checkout(&vv!(1 => 10, 2=>0));
783 assert_eq!(t.rope.len(), 10);
784 }
785
786 #[test]
787 fn repeated_tail_splits_keep_id_to_cursor_consistent() {
788 let mut t = Tracker::new();
789 t.insert(IdFull::new(1, 0, 0), 0, RichtextChunk::new_text(0..300));
790
791 for (i, pos) in [100, 201, 252, 278].into_iter().enumerate() {
792 let op_id = IdFull::new(2, i as Counter, i as Lamport);
793 let start = 1000 + i as u32;
794 t.insert(op_id, pos, RichtextChunk::new_text(start..start + 1));
795 }
796
797 t.check();
798 }
799
800 #[test]
801 fn test_checkout_in_doc_with_del_span() {
802 let mut t = Tracker::new();
803 t.insert(IdFull::new(1, 0, 0), 0, RichtextChunk::new_text(0..10));
804 t.delete(ID::new(2, 0), ID::NONE_ID, 0, 10, false);
805 t.checkout(&vv!(1 => 10, 2=>4));
806 let v: Vec<FugueSpan> = t.rope.tree().iter().copied().collect();
807 assert_eq!(v.len(), 2);
808 assert!(!v[0].is_activated());
809 assert_eq!(v[0].rle_len(), 4);
810 assert!(v[1].is_activated());
811 assert_eq!(v[1].rle_len(), 6);
812 }
813
814 #[test]
815 #[ignore]
816 fn perf_update_insert_by_split_quadratic() {
817 // Run with:
818 // cargo test -p loro-internal perf_update_insert_by_split_quadratic -- --ignored --nocapture
819 const CHUNK_LEN: usize = 256;
820 let fragments: usize = std::env::var("LORO_PERF_FRAGMENTS")
821 .ok()
822 .and_then(|v| v.parse().ok())
823 .unwrap_or(8192);
824 const PEER_A: PeerID = 1;
825 const PEER_B: PeerID = 2;
826
827 let doc_len = CHUNK_LEN * fragments;
828
829 let mut t = Tracker::new();
830 t.insert(
831 IdFull::new(PEER_A, 0, 0),
832 0,
833 RichtextChunk::new_text(0..doc_len as u32),
834 );
835 t.id_to_cursor.diagnose();
836
837 let start = Instant::now();
838 let expected_fragment_updates = (fragments as u64) * ((fragments - 1) as u64) / 2;
839
840 for i in 0..(fragments - 1) {
841 let pos = (i + 1) * CHUNK_LEN + i;
842 let op_id = IdFull::new(PEER_B, i as Counter, i as Lamport);
843 let chunk = RichtextChunk::new_text(
844 (doc_len as u32 + i as u32)..(doc_len as u32 + i as u32 + 1),
845 );
846 t.insert(op_id, pos, chunk);
847 }
848
849 let elapsed = start.elapsed();
850 let before_vv = vv!(PEER_A => doc_len as Counter);
851 let after_vv = vv!(PEER_A => doc_len as Counter, PEER_B => (fragments - 1) as Counter);
852 let diff_start = Instant::now();
853 let diff_len = t.diff(&before_vv, &after_vv).count();
854 let diff_elapsed = diff_start.elapsed();
855 assert_eq!(t.rope.tree().iter().count(), 1 + 2 * (fragments - 1));
856 println!(
857 "perf_update_insert_by_split_quadratic: doc_len={}, fragments={}, expected_fragment_updates={}, insert_elapsed={:?}, diff_items={}, diff_elapsed={:?}",
858 doc_len, fragments, expected_fragment_updates, elapsed, diff_len, diff_elapsed
859 );
860 }
861
862 #[test]
863 #[ignore]
864 fn perf_update_insert_by_split_quadratic_unknown() {
865 // Run with:
866 // LORO_PERF_FRAGMENTS=8192 cargo test -p loro-internal perf_update_insert_by_split_quadratic_unknown -- --ignored --nocapture
867 const CHUNK_LEN: usize = 256;
868 let fragments: usize = std::env::var("LORO_PERF_FRAGMENTS")
869 .ok()
870 .and_then(|v| v.parse().ok())
871 .unwrap_or(8192);
872 const PEER_B: PeerID = 2;
873
874 let doc_len = CHUNK_LEN * fragments;
875
876 let mut t = Tracker::new_with_unknown();
877 t.checkout(&vv!());
878 t.id_to_cursor.diagnose();
879
880 let start = Instant::now();
881 for i in 0..(fragments - 1) {
882 let pos = (i + 1) * CHUNK_LEN + i;
883 let op_id = IdFull::new(PEER_B, i as Counter, i as Lamport);
884 let chunk = RichtextChunk::new_text(
885 (doc_len as u32 + i as u32)..(doc_len as u32 + i as u32 + 1),
886 );
887 t.insert(op_id, pos, chunk);
888 }
889
890 let elapsed = start.elapsed();
891 println!(
892 "perf_update_insert_by_split_quadratic_unknown: doc_len={}, fragments={}, elapsed={:?}",
893 doc_len, fragments, elapsed
894 );
895 }
896}