1mod anchor;
2mod locator;
3pub mod operation_queue;
4mod patch;
5mod point;
6mod point_utf16;
7#[cfg(any(test, feature = "test-support"))]
8pub mod random_char_iter;
9pub mod rope;
10mod selection;
11#[cfg(test)]
12mod tests;
13
14pub use anchor::*;
15use anyhow::{anyhow, Result};
16use clock::ReplicaId;
17use collections::{HashMap, HashSet};
18use locator::Locator;
19use operation_queue::OperationQueue;
20use parking_lot::Mutex;
21pub use patch::Patch;
22pub use point::*;
23pub use point_utf16::*;
24#[cfg(any(test, feature = "test-support"))]
25pub use random_char_iter::*;
26use rope::TextDimension;
27pub use rope::{Chunks, Rope, TextSummary};
28pub use selection::*;
29use std::{
30 cmp::{self, Ordering},
31 iter::Iterator,
32 ops::{self, Deref, Range, Sub},
33 str,
34 sync::{Arc, Weak},
35 time::{Duration, Instant},
36};
37pub use sum_tree::Bias;
38use sum_tree::{FilterCursor, SumTree};
39
40pub struct Buffer {
41 snapshot: Snapshot,
42 last_edit: clock::Local,
43 history: History,
44 selections: HashMap<SelectionSetId, SelectionSet>,
45 deferred_ops: OperationQueue<Operation>,
46 deferred_replicas: HashSet<ReplicaId>,
47 replica_id: ReplicaId,
48 remote_id: u64,
49 local_clock: clock::Local,
50 lamport_clock: clock::Lamport,
51 subscriptions: Vec<Weak<Mutex<Vec<Patch<usize>>>>>,
52}
53
54#[derive(Clone)]
55pub struct Snapshot {
56 visible_text: Rope,
57 deleted_text: Rope,
58 undo_map: UndoMap,
59 fragments: SumTree<Fragment>,
60 insertions: SumTree<InsertionFragment>,
61 pub version: clock::Global,
62}
63
64#[derive(Clone, Debug)]
65pub struct Transaction {
66 start: clock::Global,
67 end: clock::Global,
68 edits: Vec<clock::Local>,
69 ranges: Vec<Range<FullOffset>>,
70 selections_before: HashMap<SelectionSetId, Arc<[Selection<Anchor>]>>,
71 selections_after: HashMap<SelectionSetId, Arc<[Selection<Anchor>]>>,
72 first_edit_at: Instant,
73 last_edit_at: Instant,
74}
75
76impl Transaction {
77 pub fn starting_selection_set_ids<'a>(&'a self) -> impl Iterator<Item = SelectionSetId> + 'a {
78 self.selections_before.keys().copied()
79 }
80
81 fn push_edit(&mut self, edit: &EditOperation) {
82 self.edits.push(edit.timestamp.local());
83 self.end.observe(edit.timestamp.local());
84
85 let mut other_ranges = edit.ranges.iter().peekable();
86 let mut new_ranges = Vec::new();
87 let insertion_len = edit.new_text.as_ref().map_or(0, |t| t.len());
88 let mut delta = 0;
89
90 for mut self_range in self.ranges.iter().cloned() {
91 self_range.start += delta;
92 self_range.end += delta;
93
94 while let Some(other_range) = other_ranges.peek() {
95 let mut other_range = (*other_range).clone();
96 other_range.start += delta;
97 other_range.end += delta;
98
99 if other_range.start <= self_range.end {
100 other_ranges.next().unwrap();
101 delta += insertion_len;
102
103 if other_range.end < self_range.start {
104 new_ranges.push(other_range.start..other_range.end + insertion_len);
105 self_range.start += insertion_len;
106 self_range.end += insertion_len;
107 } else {
108 self_range.start = cmp::min(self_range.start, other_range.start);
109 self_range.end = cmp::max(self_range.end, other_range.end) + insertion_len;
110 }
111 } else {
112 break;
113 }
114 }
115
116 new_ranges.push(self_range);
117 }
118
119 for other_range in other_ranges {
120 new_ranges.push(other_range.start + delta..other_range.end + delta + insertion_len);
121 delta += insertion_len;
122 }
123
124 self.ranges = new_ranges;
125 }
126}
127
128#[derive(Clone)]
129pub struct History {
130 // TODO: Turn this into a String or Rope, maybe.
131 pub base_text: Arc<str>,
132 ops: HashMap<clock::Local, EditOperation>,
133 undo_stack: Vec<Transaction>,
134 redo_stack: Vec<Transaction>,
135 transaction_depth: usize,
136 group_interval: Duration,
137}
138
139impl History {
140 pub fn new(base_text: Arc<str>) -> Self {
141 Self {
142 base_text,
143 ops: Default::default(),
144 undo_stack: Vec::new(),
145 redo_stack: Vec::new(),
146 transaction_depth: 0,
147 group_interval: Duration::from_millis(300),
148 }
149 }
150
151 fn push(&mut self, op: EditOperation) {
152 self.ops.insert(op.timestamp.local(), op);
153 }
154
155 fn start_transaction(
156 &mut self,
157 start: clock::Global,
158 selections_before: HashMap<SelectionSetId, Arc<[Selection<Anchor>]>>,
159 now: Instant,
160 ) {
161 self.transaction_depth += 1;
162 if self.transaction_depth == 1 {
163 self.undo_stack.push(Transaction {
164 start: start.clone(),
165 end: start,
166 edits: Vec::new(),
167 ranges: Vec::new(),
168 selections_before,
169 selections_after: Default::default(),
170 first_edit_at: now,
171 last_edit_at: now,
172 });
173 }
174 }
175
176 fn end_transaction(
177 &mut self,
178 selections_after: HashMap<SelectionSetId, Arc<[Selection<Anchor>]>>,
179 now: Instant,
180 ) -> Option<&Transaction> {
181 assert_ne!(self.transaction_depth, 0);
182 self.transaction_depth -= 1;
183 if self.transaction_depth == 0 {
184 if self.undo_stack.last().unwrap().ranges.is_empty() {
185 self.undo_stack.pop();
186 None
187 } else {
188 let transaction = self.undo_stack.last_mut().unwrap();
189 transaction.selections_after = selections_after;
190 transaction.last_edit_at = now;
191 Some(transaction)
192 }
193 } else {
194 None
195 }
196 }
197
198 fn group(&mut self) {
199 let mut new_len = self.undo_stack.len();
200 let mut transactions = self.undo_stack.iter_mut();
201
202 if let Some(mut transaction) = transactions.next_back() {
203 while let Some(prev_transaction) = transactions.next_back() {
204 if transaction.first_edit_at - prev_transaction.last_edit_at <= self.group_interval
205 && transaction.start == prev_transaction.end
206 {
207 transaction = prev_transaction;
208 new_len -= 1;
209 } else {
210 break;
211 }
212 }
213 }
214
215 let (transactions_to_keep, transactions_to_merge) = self.undo_stack.split_at_mut(new_len);
216 if let Some(last_transaction) = transactions_to_keep.last_mut() {
217 for transaction in &*transactions_to_merge {
218 for edit_id in &transaction.edits {
219 last_transaction.push_edit(&self.ops[edit_id]);
220 }
221 }
222
223 if let Some(transaction) = transactions_to_merge.last_mut() {
224 last_transaction.last_edit_at = transaction.last_edit_at;
225 last_transaction
226 .selections_after
227 .extend(transaction.selections_after.drain());
228 last_transaction.end = transaction.end.clone();
229 }
230 }
231
232 self.undo_stack.truncate(new_len);
233 }
234
235 fn push_undo(&mut self, edit_id: clock::Local) {
236 assert_ne!(self.transaction_depth, 0);
237 let last_transaction = self.undo_stack.last_mut().unwrap();
238 last_transaction.push_edit(&self.ops[&edit_id]);
239 }
240
241 fn pop_undo(&mut self) -> Option<&Transaction> {
242 assert_eq!(self.transaction_depth, 0);
243 if let Some(transaction) = self.undo_stack.pop() {
244 self.redo_stack.push(transaction);
245 self.redo_stack.last()
246 } else {
247 None
248 }
249 }
250
251 fn pop_redo(&mut self) -> Option<&Transaction> {
252 assert_eq!(self.transaction_depth, 0);
253 if let Some(transaction) = self.redo_stack.pop() {
254 self.undo_stack.push(transaction);
255 self.undo_stack.last()
256 } else {
257 None
258 }
259 }
260}
261
262#[derive(Clone, Default, Debug)]
263struct UndoMap(HashMap<clock::Local, Vec<(clock::Local, u32)>>);
264
265impl UndoMap {
266 fn insert(&mut self, undo: &UndoOperation) {
267 for (edit_id, count) in &undo.counts {
268 self.0.entry(*edit_id).or_default().push((undo.id, *count));
269 }
270 }
271
272 fn is_undone(&self, edit_id: clock::Local) -> bool {
273 self.undo_count(edit_id) % 2 == 1
274 }
275
276 fn was_undone(&self, edit_id: clock::Local, version: &clock::Global) -> bool {
277 let undo_count = self
278 .0
279 .get(&edit_id)
280 .unwrap_or(&Vec::new())
281 .iter()
282 .filter(|(undo_id, _)| version.observed(*undo_id))
283 .map(|(_, undo_count)| *undo_count)
284 .max()
285 .unwrap_or(0);
286 undo_count % 2 == 1
287 }
288
289 fn undo_count(&self, edit_id: clock::Local) -> u32 {
290 self.0
291 .get(&edit_id)
292 .unwrap_or(&Vec::new())
293 .iter()
294 .map(|(_, undo_count)| *undo_count)
295 .max()
296 .unwrap_or(0)
297 }
298}
299
300struct Edits<'a, D: TextDimension<'a>, F: FnMut(&FragmentSummary) -> bool> {
301 visible_cursor: rope::Cursor<'a>,
302 deleted_cursor: rope::Cursor<'a>,
303 fragments_cursor: Option<FilterCursor<'a, F, Fragment, FragmentTextSummary>>,
304 undos: &'a UndoMap,
305 since: &'a clock::Global,
306 old_end: D,
307 new_end: D,
308}
309
310#[derive(Clone, Debug, Default, Eq, PartialEq)]
311pub struct Edit<D> {
312 pub old: Range<D>,
313 pub new: Range<D>,
314}
315
316impl<D> Edit<D>
317where
318 D: Sub<D, Output = D> + PartialEq + Copy,
319{
320 pub fn old_len(&self) -> D {
321 self.old.end - self.old.start
322 }
323
324 pub fn new_len(&self) -> D {
325 self.new.end - self.new.start
326 }
327
328 pub fn is_empty(&self) -> bool {
329 self.old.start == self.old.end && self.new.start == self.new.end
330 }
331}
332
333impl<D1, D2> Edit<(D1, D2)> {
334 pub fn flatten(self) -> (Edit<D1>, Edit<D2>) {
335 (
336 Edit {
337 old: self.old.start.0..self.old.end.0,
338 new: self.new.start.0..self.new.end.0,
339 },
340 Edit {
341 old: self.old.start.1..self.old.end.1,
342 new: self.new.start.1..self.new.end.1,
343 },
344 )
345 }
346}
347
348#[derive(Clone, Default)]
349pub struct Subscription(Arc<Mutex<Vec<Patch<usize>>>>);
350
351impl Subscription {
352 pub fn consume(&self) -> Patch<usize> {
353 let mut patches = self.0.lock();
354 let mut changes = Patch::default();
355 for patch in patches.drain(..) {
356 changes = changes.compose(&patch);
357 }
358 changes
359 }
360}
361
362#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, PartialOrd, Ord)]
363pub struct InsertionTimestamp {
364 pub replica_id: ReplicaId,
365 pub local: clock::Seq,
366 pub lamport: clock::Seq,
367}
368
369impl InsertionTimestamp {
370 fn local(&self) -> clock::Local {
371 clock::Local {
372 replica_id: self.replica_id,
373 value: self.local,
374 }
375 }
376
377 fn lamport(&self) -> clock::Lamport {
378 clock::Lamport {
379 replica_id: self.replica_id,
380 value: self.lamport,
381 }
382 }
383}
384
385#[derive(Eq, PartialEq, Clone, Debug)]
386struct Fragment {
387 id: Locator,
388 insertion_timestamp: InsertionTimestamp,
389 insertion_offset: usize,
390 len: usize,
391 visible: bool,
392 deletions: HashSet<clock::Local>,
393 max_undos: clock::Global,
394}
395
396#[derive(Eq, PartialEq, Clone, Debug)]
397pub struct FragmentSummary {
398 text: FragmentTextSummary,
399 max_id: Locator,
400 max_version: clock::Global,
401 min_insertion_version: clock::Global,
402 max_insertion_version: clock::Global,
403}
404
405#[derive(Copy, Default, Clone, Debug, PartialEq, Eq)]
406struct FragmentTextSummary {
407 visible: usize,
408 deleted: usize,
409}
410
411#[derive(Eq, PartialEq, Clone, Debug)]
412struct InsertionFragment {
413 timestamp: clock::Local,
414 split_offset: usize,
415 fragment_id: Locator,
416}
417
418#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
419struct InsertionFragmentKey {
420 timestamp: clock::Local,
421 split_offset: usize,
422}
423
424#[derive(Clone, Debug, Eq, PartialEq)]
425pub enum Operation {
426 Edit(EditOperation),
427 Undo {
428 undo: UndoOperation,
429 lamport_timestamp: clock::Lamport,
430 },
431 UpdateSelections {
432 set_id: SelectionSetId,
433 selections: Arc<[Selection<Anchor>]>,
434 lamport_timestamp: clock::Lamport,
435 },
436 RemoveSelections {
437 set_id: SelectionSetId,
438 lamport_timestamp: clock::Lamport,
439 },
440 SetActiveSelections {
441 set_id: Option<SelectionSetId>,
442 lamport_timestamp: clock::Lamport,
443 },
444}
445
446#[derive(Clone, Debug, Eq, PartialEq)]
447pub struct EditOperation {
448 pub timestamp: InsertionTimestamp,
449 pub version: clock::Global,
450 pub ranges: Vec<Range<FullOffset>>,
451 pub new_text: Option<String>,
452}
453
454#[derive(Clone, Debug, Eq, PartialEq)]
455pub struct UndoOperation {
456 pub id: clock::Local,
457 pub counts: HashMap<clock::Local, u32>,
458 pub ranges: Vec<Range<FullOffset>>,
459 pub version: clock::Global,
460}
461
462impl Buffer {
463 pub fn new(replica_id: u16, remote_id: u64, history: History) -> Buffer {
464 let mut fragments = SumTree::new();
465 let mut insertions = SumTree::new();
466
467 let mut local_clock = clock::Local::new(replica_id);
468 let mut lamport_clock = clock::Lamport::new(replica_id);
469 let mut version = clock::Global::new();
470 let visible_text = Rope::from(history.base_text.as_ref());
471 if visible_text.len() > 0 {
472 let insertion_timestamp = InsertionTimestamp {
473 replica_id: 0,
474 local: 1,
475 lamport: 1,
476 };
477 local_clock.observe(insertion_timestamp.local());
478 lamport_clock.observe(insertion_timestamp.lamport());
479 version.observe(insertion_timestamp.local());
480 let fragment_id = Locator::between(&Locator::min(), &Locator::max());
481 let fragment = Fragment {
482 id: fragment_id,
483 insertion_timestamp,
484 insertion_offset: 0,
485 len: visible_text.len(),
486 visible: true,
487 deletions: Default::default(),
488 max_undos: Default::default(),
489 };
490 insertions.push(InsertionFragment::new(&fragment), &());
491 fragments.push(fragment, &None);
492 }
493
494 Buffer {
495 snapshot: Snapshot {
496 visible_text,
497 deleted_text: Rope::new(),
498 fragments,
499 insertions,
500 version,
501 undo_map: Default::default(),
502 },
503 last_edit: clock::Local::default(),
504 history,
505 selections: Default::default(),
506 deferred_ops: OperationQueue::new(),
507 deferred_replicas: HashSet::default(),
508 replica_id,
509 remote_id,
510 local_clock,
511 lamport_clock,
512 subscriptions: Default::default(),
513 }
514 }
515
516 pub fn version(&self) -> clock::Global {
517 self.version.clone()
518 }
519
520 pub fn snapshot(&self) -> Snapshot {
521 self.snapshot.clone()
522 }
523
524 pub fn replica_id(&self) -> ReplicaId {
525 self.local_clock.replica_id
526 }
527
528 pub fn lamport_timestamp(&self) -> clock::Lamport {
529 self.lamport_clock
530 }
531
532 pub fn remote_id(&self) -> u64 {
533 self.remote_id
534 }
535
536 pub fn deferred_ops_len(&self) -> usize {
537 self.deferred_ops.len()
538 }
539
540 pub fn edit<R, I, S, T>(&mut self, ranges: R, new_text: T) -> EditOperation
541 where
542 R: IntoIterator<IntoIter = I>,
543 I: ExactSizeIterator<Item = Range<S>>,
544 S: ToOffset,
545 T: Into<String>,
546 {
547 let new_text = new_text.into();
548 let new_text_len = new_text.len();
549 let new_text = if new_text_len > 0 {
550 Some(new_text)
551 } else {
552 None
553 };
554
555 self.start_transaction(None).unwrap();
556 let timestamp = InsertionTimestamp {
557 replica_id: self.replica_id,
558 local: self.local_clock.tick().value,
559 lamport: self.lamport_clock.tick().value,
560 };
561 let edit = self.apply_local_edit(ranges.into_iter(), new_text, timestamp);
562
563 self.history.push(edit.clone());
564 self.history.push_undo(edit.timestamp.local());
565 self.last_edit = edit.timestamp.local();
566 self.snapshot.version.observe(edit.timestamp.local());
567 self.end_transaction(None);
568 edit
569 }
570
571 fn apply_local_edit<S: ToOffset>(
572 &mut self,
573 ranges: impl ExactSizeIterator<Item = Range<S>>,
574 new_text: Option<String>,
575 timestamp: InsertionTimestamp,
576 ) -> EditOperation {
577 let mut edits = Patch::default();
578 let mut edit_op = EditOperation {
579 timestamp,
580 version: self.version(),
581 ranges: Vec::with_capacity(ranges.len()),
582 new_text: None,
583 };
584 let mut new_insertions = Vec::new();
585 let mut insertion_offset = 0;
586
587 let mut ranges = ranges
588 .map(|range| range.start.to_offset(&*self)..range.end.to_offset(&*self))
589 .peekable();
590
591 let mut new_ropes =
592 RopeBuilder::new(self.visible_text.cursor(0), self.deleted_text.cursor(0));
593 let mut old_fragments = self.fragments.cursor::<FragmentTextSummary>();
594 let mut new_fragments =
595 old_fragments.slice(&ranges.peek().unwrap().start, Bias::Right, &None);
596 new_ropes.push_tree(new_fragments.summary().text);
597
598 let mut fragment_start = old_fragments.start().visible;
599 for range in ranges {
600 let fragment_end = old_fragments.end(&None).visible;
601
602 // If the current fragment ends before this range, then jump ahead to the first fragment
603 // that extends past the start of this range, reusing any intervening fragments.
604 if fragment_end < range.start {
605 // If the current fragment has been partially consumed, then consume the rest of it
606 // and advance to the next fragment before slicing.
607 if fragment_start > old_fragments.start().visible {
608 if fragment_end > fragment_start {
609 let mut suffix = old_fragments.item().unwrap().clone();
610 suffix.len = fragment_end - fragment_start;
611 suffix.insertion_offset += fragment_start - old_fragments.start().visible;
612 new_insertions.push(InsertionFragment::insert_new(&suffix));
613 new_ropes.push_fragment(&suffix, suffix.visible);
614 new_fragments.push(suffix, &None);
615 }
616 old_fragments.next(&None);
617 }
618
619 let slice = old_fragments.slice(&range.start, Bias::Right, &None);
620 new_ropes.push_tree(slice.summary().text);
621 new_fragments.push_tree(slice, &None);
622 fragment_start = old_fragments.start().visible;
623 }
624
625 let full_range_start = FullOffset(range.start + old_fragments.start().deleted);
626
627 // Preserve any portion of the current fragment that precedes this range.
628 if fragment_start < range.start {
629 let mut prefix = old_fragments.item().unwrap().clone();
630 prefix.len = range.start - fragment_start;
631 prefix.insertion_offset += fragment_start - old_fragments.start().visible;
632 prefix.id = Locator::between(&new_fragments.summary().max_id, &prefix.id);
633 new_insertions.push(InsertionFragment::insert_new(&prefix));
634 new_ropes.push_fragment(&prefix, prefix.visible);
635 new_fragments.push(prefix, &None);
636 fragment_start = range.start;
637 }
638
639 // Insert the new text before any existing fragments within the range.
640 if let Some(new_text) = new_text.as_deref() {
641 let new_start = new_fragments.summary().text.visible;
642 edits.push(Edit {
643 old: fragment_start..fragment_start,
644 new: new_start..new_start + new_text.len(),
645 });
646 let fragment = Fragment {
647 id: Locator::between(
648 &new_fragments.summary().max_id,
649 old_fragments
650 .item()
651 .map_or(&Locator::max(), |old_fragment| &old_fragment.id),
652 ),
653 insertion_timestamp: timestamp,
654 insertion_offset,
655 len: new_text.len(),
656 deletions: Default::default(),
657 max_undos: Default::default(),
658 visible: true,
659 };
660 new_insertions.push(InsertionFragment::insert_new(&fragment));
661 new_ropes.push_str(new_text);
662 new_fragments.push(fragment, &None);
663 insertion_offset += new_text.len();
664 }
665
666 // Advance through every fragment that intersects this range, marking the intersecting
667 // portions as deleted.
668 while fragment_start < range.end {
669 let fragment = old_fragments.item().unwrap();
670 let fragment_end = old_fragments.end(&None).visible;
671 let mut intersection = fragment.clone();
672 let intersection_end = cmp::min(range.end, fragment_end);
673 if fragment.visible {
674 intersection.len = intersection_end - fragment_start;
675 intersection.insertion_offset += fragment_start - old_fragments.start().visible;
676 intersection.id =
677 Locator::between(&new_fragments.summary().max_id, &intersection.id);
678 intersection.deletions.insert(timestamp.local());
679 intersection.visible = false;
680 }
681 if intersection.len > 0 {
682 if fragment.visible && !intersection.visible {
683 let new_start = new_fragments.summary().text.visible;
684 edits.push(Edit {
685 old: fragment_start..intersection_end,
686 new: new_start..new_start,
687 });
688 }
689 new_insertions.push(InsertionFragment::insert_new(&intersection));
690 new_ropes.push_fragment(&intersection, fragment.visible);
691 new_fragments.push(intersection, &None);
692 fragment_start = intersection_end;
693 }
694 if fragment_end <= range.end {
695 old_fragments.next(&None);
696 }
697 }
698
699 let full_range_end = FullOffset(range.end + old_fragments.start().deleted);
700 edit_op.ranges.push(full_range_start..full_range_end);
701 }
702
703 // If the current fragment has been partially consumed, then consume the rest of it
704 // and advance to the next fragment before slicing.
705 if fragment_start > old_fragments.start().visible {
706 let fragment_end = old_fragments.end(&None).visible;
707 if fragment_end > fragment_start {
708 let mut suffix = old_fragments.item().unwrap().clone();
709 suffix.len = fragment_end - fragment_start;
710 suffix.insertion_offset += fragment_start - old_fragments.start().visible;
711 new_insertions.push(InsertionFragment::insert_new(&suffix));
712 new_ropes.push_fragment(&suffix, suffix.visible);
713 new_fragments.push(suffix, &None);
714 }
715 old_fragments.next(&None);
716 }
717
718 let suffix = old_fragments.suffix(&None);
719 new_ropes.push_tree(suffix.summary().text);
720 new_fragments.push_tree(suffix, &None);
721 let (visible_text, deleted_text) = new_ropes.finish();
722 drop(old_fragments);
723
724 self.snapshot.fragments = new_fragments;
725 self.snapshot.insertions.edit(new_insertions, &());
726 self.snapshot.visible_text = visible_text;
727 self.snapshot.deleted_text = deleted_text;
728 self.update_subscriptions(edits);
729 edit_op.new_text = new_text;
730 edit_op
731 }
732
733 pub fn apply_ops<I: IntoIterator<Item = Operation>>(&mut self, ops: I) -> Result<()> {
734 let mut deferred_ops = Vec::new();
735 for op in ops {
736 if self.can_apply_op(&op) {
737 self.apply_op(op)?;
738 } else {
739 self.deferred_replicas.insert(op.replica_id());
740 deferred_ops.push(op);
741 }
742 }
743 self.deferred_ops.insert(deferred_ops);
744 self.flush_deferred_ops()?;
745 Ok(())
746 }
747
748 fn apply_op(&mut self, op: Operation) -> Result<()> {
749 match op {
750 Operation::Edit(edit) => {
751 if !self.version.observed(edit.timestamp.local()) {
752 self.apply_remote_edit(
753 &edit.version,
754 &edit.ranges,
755 edit.new_text.as_deref(),
756 edit.timestamp,
757 );
758 self.snapshot.version.observe(edit.timestamp.local());
759 self.history.push(edit);
760 }
761 }
762 Operation::Undo {
763 undo,
764 lamport_timestamp,
765 } => {
766 if !self.version.observed(undo.id) {
767 self.apply_undo(&undo)?;
768 self.snapshot.version.observe(undo.id);
769 self.lamport_clock.observe(lamport_timestamp);
770 }
771 }
772 Operation::UpdateSelections {
773 set_id,
774 selections,
775 lamport_timestamp,
776 } => {
777 if let Some(set) = self.selections.get_mut(&set_id) {
778 set.selections = selections;
779 } else {
780 self.selections.insert(
781 set_id,
782 SelectionSet {
783 id: set_id,
784 selections,
785 active: false,
786 },
787 );
788 }
789 self.lamport_clock.observe(lamport_timestamp);
790 }
791 Operation::RemoveSelections {
792 set_id,
793 lamport_timestamp,
794 } => {
795 self.selections.remove(&set_id);
796 self.lamport_clock.observe(lamport_timestamp);
797 }
798 Operation::SetActiveSelections {
799 set_id,
800 lamport_timestamp,
801 } => {
802 for (id, set) in &mut self.selections {
803 if id.replica_id == lamport_timestamp.replica_id {
804 if Some(*id) == set_id {
805 set.active = true;
806 } else {
807 set.active = false;
808 }
809 }
810 }
811 self.lamport_clock.observe(lamport_timestamp);
812 }
813 }
814 Ok(())
815 }
816
817 fn apply_remote_edit(
818 &mut self,
819 version: &clock::Global,
820 ranges: &[Range<FullOffset>],
821 new_text: Option<&str>,
822 timestamp: InsertionTimestamp,
823 ) {
824 if ranges.is_empty() {
825 return;
826 }
827
828 let mut edits = Patch::default();
829 let cx = Some(version.clone());
830 let mut new_insertions = Vec::new();
831 let mut insertion_offset = 0;
832 let mut new_ropes =
833 RopeBuilder::new(self.visible_text.cursor(0), self.deleted_text.cursor(0));
834 let mut old_fragments = self.fragments.cursor::<(VersionedFullOffset, usize)>();
835 let mut new_fragments = old_fragments.slice(
836 &VersionedFullOffset::Offset(ranges[0].start),
837 Bias::Left,
838 &cx,
839 );
840 new_ropes.push_tree(new_fragments.summary().text);
841
842 let mut fragment_start = old_fragments.start().0.full_offset();
843 for range in ranges {
844 let fragment_end = old_fragments.end(&cx).0.full_offset();
845
846 // If the current fragment ends before this range, then jump ahead to the first fragment
847 // that extends past the start of this range, reusing any intervening fragments.
848 if fragment_end < range.start {
849 // If the current fragment has been partially consumed, then consume the rest of it
850 // and advance to the next fragment before slicing.
851 if fragment_start > old_fragments.start().0.full_offset() {
852 if fragment_end > fragment_start {
853 let mut suffix = old_fragments.item().unwrap().clone();
854 suffix.len = fragment_end.0 - fragment_start.0;
855 suffix.insertion_offset +=
856 fragment_start - old_fragments.start().0.full_offset();
857 new_insertions.push(InsertionFragment::insert_new(&suffix));
858 new_ropes.push_fragment(&suffix, suffix.visible);
859 new_fragments.push(suffix, &None);
860 }
861 old_fragments.next(&cx);
862 }
863
864 let slice =
865 old_fragments.slice(&VersionedFullOffset::Offset(range.start), Bias::Left, &cx);
866 new_ropes.push_tree(slice.summary().text);
867 new_fragments.push_tree(slice, &None);
868 fragment_start = old_fragments.start().0.full_offset();
869 }
870
871 // If we are at the end of a non-concurrent fragment, advance to the next one.
872 let fragment_end = old_fragments.end(&cx).0.full_offset();
873 if fragment_end == range.start && fragment_end > fragment_start {
874 let mut fragment = old_fragments.item().unwrap().clone();
875 fragment.len = fragment_end.0 - fragment_start.0;
876 fragment.insertion_offset += fragment_start - old_fragments.start().0.full_offset();
877 new_insertions.push(InsertionFragment::insert_new(&fragment));
878 new_ropes.push_fragment(&fragment, fragment.visible);
879 new_fragments.push(fragment, &None);
880 old_fragments.next(&cx);
881 fragment_start = old_fragments.start().0.full_offset();
882 }
883
884 // Skip over insertions that are concurrent to this edit, but have a lower lamport
885 // timestamp.
886 while let Some(fragment) = old_fragments.item() {
887 if fragment_start == range.start
888 && fragment.insertion_timestamp.lamport() > timestamp.lamport()
889 {
890 new_ropes.push_fragment(fragment, fragment.visible);
891 new_fragments.push(fragment.clone(), &None);
892 old_fragments.next(&cx);
893 debug_assert_eq!(fragment_start, range.start);
894 } else {
895 break;
896 }
897 }
898 debug_assert!(fragment_start <= range.start);
899
900 // Preserve any portion of the current fragment that precedes this range.
901 if fragment_start < range.start {
902 let mut prefix = old_fragments.item().unwrap().clone();
903 prefix.len = range.start.0 - fragment_start.0;
904 prefix.insertion_offset += fragment_start - old_fragments.start().0.full_offset();
905 prefix.id = Locator::between(&new_fragments.summary().max_id, &prefix.id);
906 new_insertions.push(InsertionFragment::insert_new(&prefix));
907 fragment_start = range.start;
908 new_ropes.push_fragment(&prefix, prefix.visible);
909 new_fragments.push(prefix, &None);
910 }
911
912 // Insert the new text before any existing fragments within the range.
913 if let Some(new_text) = new_text {
914 let mut old_start = old_fragments.start().1;
915 if old_fragments.item().map_or(false, |f| f.visible) {
916 old_start += fragment_start.0 - old_fragments.start().0.full_offset().0;
917 }
918 let new_start = new_fragments.summary().text.visible;
919 edits.push(Edit {
920 old: old_start..old_start,
921 new: new_start..new_start + new_text.len(),
922 });
923 let fragment = Fragment {
924 id: Locator::between(
925 &new_fragments.summary().max_id,
926 old_fragments
927 .item()
928 .map_or(&Locator::max(), |old_fragment| &old_fragment.id),
929 ),
930 insertion_timestamp: timestamp,
931 insertion_offset,
932 len: new_text.len(),
933 deletions: Default::default(),
934 max_undos: Default::default(),
935 visible: true,
936 };
937 new_insertions.push(InsertionFragment::insert_new(&fragment));
938 new_ropes.push_str(new_text);
939 new_fragments.push(fragment, &None);
940 insertion_offset += new_text.len();
941 }
942
943 // Advance through every fragment that intersects this range, marking the intersecting
944 // portions as deleted.
945 while fragment_start < range.end {
946 let fragment = old_fragments.item().unwrap();
947 let fragment_end = old_fragments.end(&cx).0.full_offset();
948 let mut intersection = fragment.clone();
949 let intersection_end = cmp::min(range.end, fragment_end);
950 if fragment.was_visible(version, &self.undo_map) {
951 intersection.len = intersection_end.0 - fragment_start.0;
952 intersection.insertion_offset +=
953 fragment_start - old_fragments.start().0.full_offset();
954 intersection.id =
955 Locator::between(&new_fragments.summary().max_id, &intersection.id);
956 intersection.deletions.insert(timestamp.local());
957 intersection.visible = false;
958 }
959 if intersection.len > 0 {
960 if fragment.visible && !intersection.visible {
961 let old_start = old_fragments.start().1
962 + (fragment_start.0 - old_fragments.start().0.full_offset().0);
963 let new_start = new_fragments.summary().text.visible;
964 edits.push(Edit {
965 old: old_start..old_start + intersection.len,
966 new: new_start..new_start,
967 });
968 }
969 new_insertions.push(InsertionFragment::insert_new(&intersection));
970 new_ropes.push_fragment(&intersection, fragment.visible);
971 new_fragments.push(intersection, &None);
972 fragment_start = intersection_end;
973 }
974 if fragment_end <= range.end {
975 old_fragments.next(&cx);
976 }
977 }
978 }
979
980 // If the current fragment has been partially consumed, then consume the rest of it
981 // and advance to the next fragment before slicing.
982 if fragment_start > old_fragments.start().0.full_offset() {
983 let fragment_end = old_fragments.end(&cx).0.full_offset();
984 if fragment_end > fragment_start {
985 let mut suffix = old_fragments.item().unwrap().clone();
986 suffix.len = fragment_end.0 - fragment_start.0;
987 suffix.insertion_offset += fragment_start - old_fragments.start().0.full_offset();
988 new_insertions.push(InsertionFragment::insert_new(&suffix));
989 new_ropes.push_fragment(&suffix, suffix.visible);
990 new_fragments.push(suffix, &None);
991 }
992 old_fragments.next(&cx);
993 }
994
995 let suffix = old_fragments.suffix(&cx);
996 new_ropes.push_tree(suffix.summary().text);
997 new_fragments.push_tree(suffix, &None);
998 let (visible_text, deleted_text) = new_ropes.finish();
999 drop(old_fragments);
1000
1001 self.snapshot.fragments = new_fragments;
1002 self.snapshot.visible_text = visible_text;
1003 self.snapshot.deleted_text = deleted_text;
1004 self.snapshot.insertions.edit(new_insertions, &());
1005 self.local_clock.observe(timestamp.local());
1006 self.lamport_clock.observe(timestamp.lamport());
1007 self.update_subscriptions(edits);
1008 }
1009
1010 fn apply_undo(&mut self, undo: &UndoOperation) -> Result<()> {
1011 let mut edits = Patch::default();
1012 self.snapshot.undo_map.insert(undo);
1013
1014 let mut cx = undo.version.clone();
1015 for edit_id in undo.counts.keys().copied() {
1016 cx.observe(edit_id);
1017 }
1018 let cx = Some(cx);
1019
1020 let mut old_fragments = self.fragments.cursor::<(VersionedFullOffset, usize)>();
1021 let mut new_fragments = old_fragments.slice(
1022 &VersionedFullOffset::Offset(undo.ranges[0].start),
1023 Bias::Right,
1024 &cx,
1025 );
1026 let mut new_ropes =
1027 RopeBuilder::new(self.visible_text.cursor(0), self.deleted_text.cursor(0));
1028 new_ropes.push_tree(new_fragments.summary().text);
1029
1030 for range in &undo.ranges {
1031 let mut end_offset = old_fragments.end(&cx).0.full_offset();
1032
1033 if end_offset < range.start {
1034 let preceding_fragments = old_fragments.slice(
1035 &VersionedFullOffset::Offset(range.start),
1036 Bias::Right,
1037 &cx,
1038 );
1039 new_ropes.push_tree(preceding_fragments.summary().text);
1040 new_fragments.push_tree(preceding_fragments, &None);
1041 }
1042
1043 while end_offset <= range.end {
1044 if let Some(fragment) = old_fragments.item() {
1045 let mut fragment = fragment.clone();
1046 let fragment_was_visible = fragment.visible;
1047
1048 if fragment.was_visible(&undo.version, &self.undo_map)
1049 || undo
1050 .counts
1051 .contains_key(&fragment.insertion_timestamp.local())
1052 {
1053 fragment.visible = fragment.is_visible(&self.undo_map);
1054 fragment.max_undos.observe(undo.id);
1055 }
1056
1057 let old_start = old_fragments.start().1;
1058 let new_start = new_fragments.summary().text.visible;
1059 if fragment_was_visible && !fragment.visible {
1060 edits.push(Edit {
1061 old: old_start..old_start + fragment.len,
1062 new: new_start..new_start,
1063 });
1064 } else if !fragment_was_visible && fragment.visible {
1065 edits.push(Edit {
1066 old: old_start..old_start,
1067 new: new_start..new_start + fragment.len,
1068 });
1069 }
1070 new_ropes.push_fragment(&fragment, fragment_was_visible);
1071 new_fragments.push(fragment, &None);
1072
1073 old_fragments.next(&cx);
1074 if end_offset == old_fragments.end(&cx).0.full_offset() {
1075 let unseen_fragments = old_fragments.slice(
1076 &VersionedFullOffset::Offset(end_offset),
1077 Bias::Right,
1078 &cx,
1079 );
1080 new_ropes.push_tree(unseen_fragments.summary().text);
1081 new_fragments.push_tree(unseen_fragments, &None);
1082 }
1083 end_offset = old_fragments.end(&cx).0.full_offset();
1084 } else {
1085 break;
1086 }
1087 }
1088 }
1089
1090 let suffix = old_fragments.suffix(&cx);
1091 new_ropes.push_tree(suffix.summary().text);
1092 new_fragments.push_tree(suffix, &None);
1093
1094 drop(old_fragments);
1095 let (visible_text, deleted_text) = new_ropes.finish();
1096 self.snapshot.fragments = new_fragments;
1097 self.snapshot.visible_text = visible_text;
1098 self.snapshot.deleted_text = deleted_text;
1099 self.update_subscriptions(edits);
1100 Ok(())
1101 }
1102
1103 fn flush_deferred_ops(&mut self) -> Result<()> {
1104 self.deferred_replicas.clear();
1105 let mut deferred_ops = Vec::new();
1106 for op in self.deferred_ops.drain().iter().cloned() {
1107 if self.can_apply_op(&op) {
1108 self.apply_op(op)?;
1109 } else {
1110 self.deferred_replicas.insert(op.replica_id());
1111 deferred_ops.push(op);
1112 }
1113 }
1114 self.deferred_ops.insert(deferred_ops);
1115 Ok(())
1116 }
1117
1118 fn can_apply_op(&self, op: &Operation) -> bool {
1119 if self.deferred_replicas.contains(&op.replica_id()) {
1120 false
1121 } else {
1122 match op {
1123 Operation::Edit(edit) => self.version.ge(&edit.version),
1124 Operation::Undo { undo, .. } => self.version.ge(&undo.version),
1125 Operation::UpdateSelections { selections, .. } => selections
1126 .iter()
1127 .all(|s| self.can_resolve(&s.start) && self.can_resolve(&s.end)),
1128 Operation::RemoveSelections { .. } => true,
1129 Operation::SetActiveSelections { set_id, .. } => {
1130 set_id.map_or(true, |set_id| self.selections.contains_key(&set_id))
1131 }
1132 }
1133 }
1134 }
1135
1136 pub fn can_resolve(&self, anchor: &Anchor) -> bool {
1137 *anchor == Anchor::min()
1138 || *anchor == Anchor::max()
1139 || self.version.observed(anchor.timestamp)
1140 }
1141
1142 pub fn peek_undo_stack(&self) -> Option<&Transaction> {
1143 self.history.undo_stack.last()
1144 }
1145
1146 pub fn start_transaction(
1147 &mut self,
1148 selection_set_ids: impl IntoIterator<Item = SelectionSetId>,
1149 ) -> Result<()> {
1150 self.start_transaction_at(selection_set_ids, Instant::now())
1151 }
1152
1153 pub fn start_transaction_at(
1154 &mut self,
1155 selection_set_ids: impl IntoIterator<Item = SelectionSetId>,
1156 now: Instant,
1157 ) -> Result<()> {
1158 let selections = selection_set_ids
1159 .into_iter()
1160 .map(|set_id| {
1161 let set = self
1162 .selections
1163 .get(&set_id)
1164 .expect("invalid selection set id");
1165 (set_id, set.selections.clone())
1166 })
1167 .collect();
1168 self.history
1169 .start_transaction(self.version.clone(), selections, now);
1170 Ok(())
1171 }
1172
1173 pub fn end_transaction(&mut self, selection_set_ids: impl IntoIterator<Item = SelectionSetId>) {
1174 self.end_transaction_at(selection_set_ids, Instant::now());
1175 }
1176
1177 pub fn end_transaction_at(
1178 &mut self,
1179 selection_set_ids: impl IntoIterator<Item = SelectionSetId>,
1180 now: Instant,
1181 ) -> Option<clock::Global> {
1182 let selections = selection_set_ids
1183 .into_iter()
1184 .map(|set_id| {
1185 let set = self
1186 .selections
1187 .get(&set_id)
1188 .expect("invalid selection set id");
1189 (set_id, set.selections.clone())
1190 })
1191 .collect();
1192
1193 if let Some(transaction) = self.history.end_transaction(selections, now) {
1194 let since = transaction.start.clone();
1195 self.history.group();
1196 Some(since)
1197 } else {
1198 None
1199 }
1200 }
1201
1202 pub fn remove_peer(&mut self, replica_id: ReplicaId) {
1203 self.selections
1204 .retain(|set_id, _| set_id.replica_id != replica_id)
1205 }
1206
1207 pub fn base_text(&self) -> &Arc<str> {
1208 &self.history.base_text
1209 }
1210
1211 pub fn history(&self) -> impl Iterator<Item = &EditOperation> {
1212 self.history.ops.values()
1213 }
1214
1215 pub fn undo(&mut self) -> Vec<Operation> {
1216 let mut ops = Vec::new();
1217 if let Some(transaction) = self.history.pop_undo().cloned() {
1218 let selections = transaction.selections_before.clone();
1219 ops.push(self.undo_or_redo(transaction).unwrap());
1220 for (set_id, selections) in selections {
1221 ops.extend(self.restore_selection_set(set_id, selections));
1222 }
1223 }
1224 ops
1225 }
1226
1227 pub fn redo(&mut self) -> Vec<Operation> {
1228 let mut ops = Vec::new();
1229 if let Some(transaction) = self.history.pop_redo().cloned() {
1230 let selections = transaction.selections_after.clone();
1231 ops.push(self.undo_or_redo(transaction).unwrap());
1232 for (set_id, selections) in selections {
1233 ops.extend(self.restore_selection_set(set_id, selections));
1234 }
1235 }
1236 ops
1237 }
1238
1239 fn undo_or_redo(&mut self, transaction: Transaction) -> Result<Operation> {
1240 let mut counts = HashMap::default();
1241 for edit_id in transaction.edits {
1242 counts.insert(edit_id, self.undo_map.undo_count(edit_id) + 1);
1243 }
1244
1245 let undo = UndoOperation {
1246 id: self.local_clock.tick(),
1247 counts,
1248 ranges: transaction.ranges,
1249 version: transaction.start.clone(),
1250 };
1251 self.apply_undo(&undo)?;
1252 self.snapshot.version.observe(undo.id);
1253
1254 Ok(Operation::Undo {
1255 undo,
1256 lamport_timestamp: self.lamport_clock.tick(),
1257 })
1258 }
1259
1260 pub fn subscribe(&mut self) -> Subscription {
1261 let subscription = Subscription(Default::default());
1262 self.subscriptions.push(Arc::downgrade(&subscription.0));
1263 subscription
1264 }
1265
1266 fn update_subscriptions(&mut self, edits: Patch<usize>) {
1267 self.subscriptions.retain(|subscription| {
1268 if let Some(subscription) = subscription.upgrade() {
1269 subscription.lock().push(edits.clone());
1270 true
1271 } else {
1272 false
1273 }
1274 });
1275 }
1276
1277 pub fn selection_set(&self, set_id: SelectionSetId) -> Result<&SelectionSet> {
1278 self.selections
1279 .get(&set_id)
1280 .ok_or_else(|| anyhow!("invalid selection set id {:?}", set_id))
1281 }
1282
1283 pub fn selection_sets(&self) -> impl Iterator<Item = (&SelectionSetId, &SelectionSet)> {
1284 self.selections.iter()
1285 }
1286
1287 fn build_anchor_selection_set<T: ToOffset>(
1288 &self,
1289 selections: &[Selection<T>],
1290 ) -> Arc<[Selection<Anchor>]> {
1291 Arc::from(
1292 selections
1293 .iter()
1294 .map(|selection| Selection {
1295 id: selection.id,
1296 start: self.anchor_before(&selection.start),
1297 end: self.anchor_before(&selection.end),
1298 reversed: selection.reversed,
1299 goal: selection.goal,
1300 })
1301 .collect::<Vec<_>>(),
1302 )
1303 }
1304
1305 pub fn update_selection_set<T: ToOffset>(
1306 &mut self,
1307 set_id: SelectionSetId,
1308 selections: &[Selection<T>],
1309 ) -> Result<Operation> {
1310 let selections = self.build_anchor_selection_set(selections);
1311 let set = self
1312 .selections
1313 .get_mut(&set_id)
1314 .ok_or_else(|| anyhow!("invalid selection set id {:?}", set_id))?;
1315 set.selections = selections.clone();
1316 Ok(Operation::UpdateSelections {
1317 set_id,
1318 selections,
1319 lamport_timestamp: self.lamport_clock.tick(),
1320 })
1321 }
1322
1323 pub fn restore_selection_set(
1324 &mut self,
1325 set_id: SelectionSetId,
1326 selections: Arc<[Selection<Anchor>]>,
1327 ) -> Result<Operation> {
1328 let set = self
1329 .selections
1330 .get_mut(&set_id)
1331 .ok_or_else(|| anyhow!("invalid selection set id {:?}", set_id))?;
1332 set.selections = selections.clone();
1333 Ok(Operation::UpdateSelections {
1334 set_id,
1335 selections,
1336 lamport_timestamp: self.lamport_clock.tick(),
1337 })
1338 }
1339
1340 pub fn add_selection_set<T: ToOffset>(&mut self, selections: &[Selection<T>]) -> Operation {
1341 let selections = self.build_anchor_selection_set(selections);
1342 let set_id = self.lamport_clock.tick();
1343 self.selections.insert(
1344 set_id,
1345 SelectionSet {
1346 id: set_id,
1347 selections: selections.clone(),
1348 active: false,
1349 },
1350 );
1351 Operation::UpdateSelections {
1352 set_id,
1353 selections,
1354 lamport_timestamp: set_id,
1355 }
1356 }
1357
1358 pub fn add_raw_selection_set(&mut self, id: SelectionSetId, selections: SelectionSet) {
1359 self.selections.insert(id, selections);
1360 }
1361
1362 pub fn set_active_selection_set(
1363 &mut self,
1364 set_id: Option<SelectionSetId>,
1365 ) -> Result<Operation> {
1366 if let Some(set_id) = set_id {
1367 assert_eq!(set_id.replica_id, self.replica_id());
1368 }
1369
1370 for (id, set) in &mut self.selections {
1371 if id.replica_id == self.local_clock.replica_id {
1372 if Some(*id) == set_id {
1373 set.active = true;
1374 } else {
1375 set.active = false;
1376 }
1377 }
1378 }
1379
1380 Ok(Operation::SetActiveSelections {
1381 set_id,
1382 lamport_timestamp: self.lamport_clock.tick(),
1383 })
1384 }
1385
1386 pub fn remove_selection_set(&mut self, set_id: SelectionSetId) -> Result<Operation> {
1387 self.selections
1388 .remove(&set_id)
1389 .ok_or_else(|| anyhow!("invalid selection set id {:?}", set_id))?;
1390 Ok(Operation::RemoveSelections {
1391 set_id,
1392 lamport_timestamp: self.lamport_clock.tick(),
1393 })
1394 }
1395}
1396
1397#[cfg(any(test, feature = "test-support"))]
1398impl Buffer {
1399 fn random_byte_range(&mut self, start_offset: usize, rng: &mut impl rand::Rng) -> Range<usize> {
1400 let end = self.clip_offset(rng.gen_range(start_offset..=self.len()), Bias::Right);
1401 let start = self.clip_offset(rng.gen_range(start_offset..=end), Bias::Right);
1402 start..end
1403 }
1404
1405 pub fn randomly_edit<T>(
1406 &mut self,
1407 rng: &mut T,
1408 old_range_count: usize,
1409 ) -> (Vec<Range<usize>>, String, Operation)
1410 where
1411 T: rand::Rng,
1412 {
1413 let mut old_ranges: Vec<Range<usize>> = Vec::new();
1414 for _ in 0..old_range_count {
1415 let last_end = old_ranges.last().map_or(0, |last_range| last_range.end + 1);
1416 if last_end > self.len() {
1417 break;
1418 }
1419 old_ranges.push(self.random_byte_range(last_end, rng));
1420 }
1421 let new_text_len = rng.gen_range(0..10);
1422 let new_text: String = crate::random_char_iter::RandomCharIter::new(&mut *rng)
1423 .take(new_text_len)
1424 .collect();
1425 log::info!(
1426 "mutating buffer {} at {:?}: {:?}",
1427 self.replica_id,
1428 old_ranges,
1429 new_text
1430 );
1431 let op = self.edit(old_ranges.iter().cloned(), new_text.as_str());
1432 (old_ranges, new_text, Operation::Edit(op))
1433 }
1434
1435 pub fn randomly_mutate<T>(&mut self, rng: &mut T) -> Vec<Operation>
1436 where
1437 T: rand::Rng,
1438 {
1439 use rand::prelude::*;
1440
1441 let mut ops = vec![self.randomly_edit(rng, 5).2];
1442
1443 // Randomly add, remove or mutate selection sets.
1444 let replica_selection_sets = &self
1445 .selection_sets()
1446 .map(|(set_id, _)| *set_id)
1447 .filter(|set_id| self.replica_id == set_id.replica_id)
1448 .collect::<Vec<_>>();
1449 let set_id = replica_selection_sets.choose(rng);
1450 if set_id.is_some() && rng.gen_bool(1.0 / 6.0) {
1451 ops.push(self.remove_selection_set(*set_id.unwrap()).unwrap());
1452 } else {
1453 let mut ranges = Vec::new();
1454 for _ in 0..5 {
1455 ranges.push(self.random_byte_range(0, rng));
1456 }
1457 let new_selections = self.selections_from_ranges(ranges).unwrap();
1458
1459 let op = if set_id.is_none() || rng.gen_bool(1.0 / 5.0) {
1460 self.add_selection_set(&new_selections)
1461 } else {
1462 self.update_selection_set(*set_id.unwrap(), &new_selections)
1463 .unwrap()
1464 };
1465 ops.push(op);
1466 }
1467
1468 ops
1469 }
1470
1471 pub fn randomly_undo_redo(&mut self, rng: &mut impl rand::Rng) -> Vec<Operation> {
1472 use rand::prelude::*;
1473
1474 let mut ops = Vec::new();
1475 for _ in 0..rng.gen_range(1..=5) {
1476 if let Some(transaction) = self.history.undo_stack.choose(rng).cloned() {
1477 log::info!(
1478 "undoing buffer {} transaction {:?}",
1479 self.replica_id,
1480 transaction
1481 );
1482 ops.push(self.undo_or_redo(transaction).unwrap());
1483 }
1484 }
1485 ops
1486 }
1487
1488 fn selections_from_ranges<I>(&self, ranges: I) -> Result<Vec<Selection<usize>>>
1489 where
1490 I: IntoIterator<Item = Range<usize>>,
1491 {
1492 use std::sync::atomic::{self, AtomicUsize};
1493
1494 static NEXT_SELECTION_ID: AtomicUsize = AtomicUsize::new(0);
1495
1496 let mut ranges = ranges.into_iter().collect::<Vec<_>>();
1497 ranges.sort_unstable_by_key(|range| range.start);
1498
1499 let mut selections = Vec::<Selection<usize>>::with_capacity(ranges.len());
1500 for mut range in ranges {
1501 let mut reversed = false;
1502 if range.start > range.end {
1503 reversed = true;
1504 std::mem::swap(&mut range.start, &mut range.end);
1505 }
1506
1507 if let Some(selection) = selections.last_mut() {
1508 if selection.end >= range.start {
1509 selection.end = range.end;
1510 continue;
1511 }
1512 }
1513
1514 selections.push(Selection {
1515 id: NEXT_SELECTION_ID.fetch_add(1, atomic::Ordering::SeqCst),
1516 start: range.start,
1517 end: range.end,
1518 reversed,
1519 goal: SelectionGoal::None,
1520 });
1521 }
1522 Ok(selections)
1523 }
1524
1525 #[cfg(test)]
1526 pub fn selection_ranges<'a, D>(&'a self, set_id: SelectionSetId) -> Result<Vec<Range<D>>>
1527 where
1528 D: 'a + TextDimension<'a>,
1529 {
1530 Ok(self
1531 .selection_set(set_id)?
1532 .selections(self)
1533 .map(move |selection| {
1534 if selection.reversed {
1535 selection.end..selection.start
1536 } else {
1537 selection.start..selection.end
1538 }
1539 })
1540 .collect())
1541 }
1542
1543 #[cfg(test)]
1544 pub fn all_selection_ranges<'a, D>(
1545 &'a self,
1546 ) -> impl 'a + Iterator<Item = (SelectionSetId, Vec<Range<usize>>)>
1547 where
1548 D: 'a + TextDimension<'a>,
1549 {
1550 self.selections
1551 .keys()
1552 .map(move |set_id| (*set_id, self.selection_ranges(*set_id).unwrap()))
1553 }
1554}
1555
1556impl Deref for Buffer {
1557 type Target = Snapshot;
1558
1559 fn deref(&self) -> &Self::Target {
1560 &self.snapshot
1561 }
1562}
1563
1564impl Snapshot {
1565 pub fn as_rope(&self) -> &Rope {
1566 &self.visible_text
1567 }
1568
1569 pub fn row_count(&self) -> u32 {
1570 self.max_point().row + 1
1571 }
1572
1573 pub fn len(&self) -> usize {
1574 self.visible_text.len()
1575 }
1576
1577 pub fn chars(&self) -> impl Iterator<Item = char> + '_ {
1578 self.chars_at(0)
1579 }
1580
1581 pub fn chars_for_range<T: ToOffset>(&self, range: Range<T>) -> impl Iterator<Item = char> + '_ {
1582 self.text_for_range(range).flat_map(str::chars)
1583 }
1584
1585 pub fn contains_str_at<T>(&self, position: T, needle: &str) -> bool
1586 where
1587 T: ToOffset,
1588 {
1589 let position = position.to_offset(self);
1590 position == self.clip_offset(position, Bias::Left)
1591 && self
1592 .bytes_in_range(position..self.len())
1593 .flatten()
1594 .copied()
1595 .take(needle.len())
1596 .eq(needle.bytes())
1597 }
1598
1599 pub fn text(&self) -> String {
1600 self.text_for_range(0..self.len()).collect()
1601 }
1602
1603 pub fn text_summary(&self) -> TextSummary {
1604 self.visible_text.summary()
1605 }
1606
1607 pub fn max_point(&self) -> Point {
1608 self.visible_text.max_point()
1609 }
1610
1611 pub fn to_offset(&self, point: Point) -> usize {
1612 self.visible_text.point_to_offset(point)
1613 }
1614
1615 pub fn to_point(&self, offset: usize) -> Point {
1616 self.visible_text.offset_to_point(offset)
1617 }
1618
1619 pub fn version(&self) -> &clock::Global {
1620 &self.version
1621 }
1622
1623 pub fn chars_at<'a, T: ToOffset>(&'a self, position: T) -> impl Iterator<Item = char> + 'a {
1624 let offset = position.to_offset(self);
1625 self.visible_text.chars_at(offset)
1626 }
1627
1628 pub fn reversed_chars_at<'a, T: ToOffset>(
1629 &'a self,
1630 position: T,
1631 ) -> impl Iterator<Item = char> + 'a {
1632 let offset = position.to_offset(self);
1633 self.visible_text.reversed_chars_at(offset)
1634 }
1635
1636 pub fn bytes_in_range<'a, T: ToOffset>(&'a self, range: Range<T>) -> rope::Bytes<'a> {
1637 let start = range.start.to_offset(self);
1638 let end = range.end.to_offset(self);
1639 self.visible_text.bytes_in_range(start..end)
1640 }
1641
1642 pub fn text_for_range<'a, T: ToOffset>(&'a self, range: Range<T>) -> Chunks<'a> {
1643 let start = range.start.to_offset(self);
1644 let end = range.end.to_offset(self);
1645 self.visible_text.chunks_in_range(start..end)
1646 }
1647
1648 pub fn line_len(&self, row: u32) -> u32 {
1649 let row_start_offset = Point::new(row, 0).to_offset(self);
1650 let row_end_offset = if row >= self.max_point().row {
1651 self.len()
1652 } else {
1653 Point::new(row + 1, 0).to_offset(self) - 1
1654 };
1655 (row_end_offset - row_start_offset) as u32
1656 }
1657
1658 pub fn is_line_blank(&self, row: u32) -> bool {
1659 self.text_for_range(Point::new(row, 0)..Point::new(row, self.line_len(row)))
1660 .all(|chunk| chunk.matches(|c: char| !c.is_whitespace()).next().is_none())
1661 }
1662
1663 pub fn indent_column_for_line(&self, row: u32) -> u32 {
1664 let mut result = 0;
1665 for c in self.chars_at(Point::new(row, 0)) {
1666 if c == ' ' {
1667 result += 1;
1668 } else {
1669 break;
1670 }
1671 }
1672 result
1673 }
1674
1675 pub fn summaries_for_anchors<'a, D, A>(&'a self, anchors: A) -> impl 'a + Iterator<Item = D>
1676 where
1677 D: 'a + TextDimension<'a>,
1678 A: 'a + IntoIterator<Item = &'a Anchor>,
1679 {
1680 let anchors = anchors.into_iter();
1681 let mut insertion_cursor = self.insertions.cursor::<InsertionFragmentKey>();
1682 let mut fragment_cursor = self.fragments.cursor::<(Option<&Locator>, usize)>();
1683 let mut text_cursor = self.visible_text.cursor(0);
1684 let mut position = D::default();
1685
1686 anchors.map(move |anchor| {
1687 if *anchor == Anchor::min() {
1688 return D::default();
1689 } else if *anchor == Anchor::max() {
1690 return D::from_text_summary(&self.visible_text.summary());
1691 }
1692
1693 let anchor_key = InsertionFragmentKey {
1694 timestamp: anchor.timestamp,
1695 split_offset: anchor.offset,
1696 };
1697 insertion_cursor.seek(&anchor_key, anchor.bias, &());
1698 if let Some(insertion) = insertion_cursor.item() {
1699 let comparison = sum_tree::KeyedItem::key(insertion).cmp(&anchor_key);
1700 if comparison == Ordering::Greater
1701 || (anchor.bias == Bias::Left
1702 && comparison == Ordering::Equal
1703 && anchor.offset > 0)
1704 {
1705 insertion_cursor.prev(&());
1706 }
1707 } else {
1708 insertion_cursor.prev(&());
1709 }
1710 let insertion = insertion_cursor.item().expect("invalid insertion");
1711 debug_assert_eq!(insertion.timestamp, anchor.timestamp, "invalid insertion");
1712
1713 fragment_cursor.seek_forward(&Some(&insertion.fragment_id), Bias::Left, &None);
1714 let fragment = fragment_cursor.item().unwrap();
1715 let mut fragment_offset = fragment_cursor.start().1;
1716 if fragment.visible {
1717 fragment_offset += anchor.offset - insertion.split_offset;
1718 }
1719
1720 position.add_assign(&text_cursor.summary(fragment_offset));
1721 position.clone()
1722 })
1723 }
1724
1725 fn summary_for_anchor<'a, D>(&'a self, anchor: &Anchor) -> D
1726 where
1727 D: TextDimension<'a>,
1728 {
1729 if *anchor == Anchor::min() {
1730 D::default()
1731 } else if *anchor == Anchor::max() {
1732 D::from_text_summary(&self.visible_text.summary())
1733 } else {
1734 let anchor_key = InsertionFragmentKey {
1735 timestamp: anchor.timestamp,
1736 split_offset: anchor.offset,
1737 };
1738 let mut insertion_cursor = self.insertions.cursor::<InsertionFragmentKey>();
1739 insertion_cursor.seek(&anchor_key, anchor.bias, &());
1740 if let Some(insertion) = insertion_cursor.item() {
1741 let comparison = sum_tree::KeyedItem::key(insertion).cmp(&anchor_key);
1742 if comparison == Ordering::Greater
1743 || (anchor.bias == Bias::Left
1744 && comparison == Ordering::Equal
1745 && anchor.offset > 0)
1746 {
1747 insertion_cursor.prev(&());
1748 }
1749 } else {
1750 insertion_cursor.prev(&());
1751 }
1752 let insertion = insertion_cursor.item().expect("invalid insertion");
1753 debug_assert_eq!(insertion.timestamp, anchor.timestamp, "invalid insertion");
1754
1755 let mut fragment_cursor = self.fragments.cursor::<(Option<&Locator>, usize)>();
1756 fragment_cursor.seek(&Some(&insertion.fragment_id), Bias::Left, &None);
1757 let fragment = fragment_cursor.item().unwrap();
1758 let mut fragment_offset = fragment_cursor.start().1;
1759 if fragment.visible {
1760 fragment_offset += anchor.offset - insertion.split_offset;
1761 }
1762 self.text_summary_for_range(0..fragment_offset)
1763 }
1764 }
1765
1766 fn full_offset_for_anchor(&self, anchor: &Anchor) -> FullOffset {
1767 if *anchor == Anchor::min() {
1768 Default::default()
1769 } else if *anchor == Anchor::max() {
1770 let text = self.fragments.summary().text;
1771 FullOffset(text.visible + text.deleted)
1772 } else {
1773 let anchor_key = InsertionFragmentKey {
1774 timestamp: anchor.timestamp,
1775 split_offset: anchor.offset,
1776 };
1777 let mut insertion_cursor = self.insertions.cursor::<InsertionFragmentKey>();
1778 insertion_cursor.seek(&anchor_key, anchor.bias, &());
1779 if let Some(insertion) = insertion_cursor.item() {
1780 let comparison = sum_tree::KeyedItem::key(insertion).cmp(&anchor_key);
1781 if comparison == Ordering::Greater
1782 || (anchor.bias == Bias::Left
1783 && comparison == Ordering::Equal
1784 && anchor.offset > 0)
1785 {
1786 insertion_cursor.prev(&());
1787 }
1788 } else {
1789 insertion_cursor.prev(&());
1790 }
1791 let insertion = insertion_cursor.item().expect("invalid insertion");
1792 debug_assert_eq!(insertion.timestamp, anchor.timestamp, "invalid insertion");
1793
1794 let mut fragment_cursor = self.fragments.cursor::<(Option<&Locator>, FullOffset)>();
1795 fragment_cursor.seek(&Some(&insertion.fragment_id), Bias::Left, &None);
1796 fragment_cursor.start().1 + (anchor.offset - insertion.split_offset)
1797 }
1798 }
1799
1800 pub fn text_summary_for_range<'a, D, O: ToOffset>(&'a self, range: Range<O>) -> D
1801 where
1802 D: TextDimension<'a>,
1803 {
1804 self.visible_text
1805 .cursor(range.start.to_offset(self))
1806 .summary(range.end.to_offset(self))
1807 }
1808
1809 pub fn anchor_before<T: ToOffset>(&self, position: T) -> Anchor {
1810 self.anchor_at(position, Bias::Left)
1811 }
1812
1813 pub fn anchor_after<T: ToOffset>(&self, position: T) -> Anchor {
1814 self.anchor_at(position, Bias::Right)
1815 }
1816
1817 pub fn anchor_at<T: ToOffset>(&self, position: T, bias: Bias) -> Anchor {
1818 let offset = position.to_offset(self);
1819 if bias == Bias::Left && offset == 0 {
1820 Anchor::min()
1821 } else if bias == Bias::Right && offset == self.len() {
1822 Anchor::max()
1823 } else {
1824 let mut fragment_cursor = self.fragments.cursor::<usize>();
1825 fragment_cursor.seek(&offset, bias, &None);
1826 let fragment = fragment_cursor.item().unwrap();
1827 let overshoot = offset - *fragment_cursor.start();
1828 Anchor {
1829 timestamp: fragment.insertion_timestamp.local(),
1830 offset: fragment.insertion_offset + overshoot,
1831 bias,
1832 }
1833 }
1834 }
1835
1836 pub fn clip_offset(&self, offset: usize, bias: Bias) -> usize {
1837 self.visible_text.clip_offset(offset, bias)
1838 }
1839
1840 pub fn clip_point(&self, point: Point, bias: Bias) -> Point {
1841 self.visible_text.clip_point(point, bias)
1842 }
1843
1844 pub fn clip_point_utf16(&self, point: PointUtf16, bias: Bias) -> PointUtf16 {
1845 self.visible_text.clip_point_utf16(point, bias)
1846 }
1847
1848 pub fn point_for_offset(&self, offset: usize) -> Result<Point> {
1849 if offset <= self.len() {
1850 Ok(self.text_summary_for_range(0..offset))
1851 } else {
1852 Err(anyhow!("offset out of bounds"))
1853 }
1854 }
1855
1856 pub fn edits_since<'a, D>(
1857 &'a self,
1858 since: &'a clock::Global,
1859 ) -> impl 'a + Iterator<Item = Edit<D>>
1860 where
1861 D: 'a + TextDimension<'a> + Ord,
1862 {
1863 let fragments_cursor = if *since == self.version {
1864 None
1865 } else {
1866 Some(
1867 self.fragments
1868 .filter(move |summary| !since.ge(&summary.max_version), &None),
1869 )
1870 };
1871
1872 Edits {
1873 visible_cursor: self.visible_text.cursor(0),
1874 deleted_cursor: self.deleted_text.cursor(0),
1875 fragments_cursor,
1876 undos: &self.undo_map,
1877 since,
1878 old_end: Default::default(),
1879 new_end: Default::default(),
1880 }
1881 }
1882}
1883
1884struct RopeBuilder<'a> {
1885 old_visible_cursor: rope::Cursor<'a>,
1886 old_deleted_cursor: rope::Cursor<'a>,
1887 new_visible: Rope,
1888 new_deleted: Rope,
1889}
1890
1891impl<'a> RopeBuilder<'a> {
1892 fn new(old_visible_cursor: rope::Cursor<'a>, old_deleted_cursor: rope::Cursor<'a>) -> Self {
1893 Self {
1894 old_visible_cursor,
1895 old_deleted_cursor,
1896 new_visible: Rope::new(),
1897 new_deleted: Rope::new(),
1898 }
1899 }
1900
1901 fn push_tree(&mut self, len: FragmentTextSummary) {
1902 self.push(len.visible, true, true);
1903 self.push(len.deleted, false, false);
1904 }
1905
1906 fn push_fragment(&mut self, fragment: &Fragment, was_visible: bool) {
1907 debug_assert!(fragment.len > 0);
1908 self.push(fragment.len, was_visible, fragment.visible)
1909 }
1910
1911 fn push(&mut self, len: usize, was_visible: bool, is_visible: bool) {
1912 let text = if was_visible {
1913 self.old_visible_cursor
1914 .slice(self.old_visible_cursor.offset() + len)
1915 } else {
1916 self.old_deleted_cursor
1917 .slice(self.old_deleted_cursor.offset() + len)
1918 };
1919 if is_visible {
1920 self.new_visible.append(text);
1921 } else {
1922 self.new_deleted.append(text);
1923 }
1924 }
1925
1926 fn push_str(&mut self, text: &str) {
1927 self.new_visible.push(text);
1928 }
1929
1930 fn finish(mut self) -> (Rope, Rope) {
1931 self.new_visible.append(self.old_visible_cursor.suffix());
1932 self.new_deleted.append(self.old_deleted_cursor.suffix());
1933 (self.new_visible, self.new_deleted)
1934 }
1935}
1936
1937impl<'a, D: TextDimension<'a> + Ord, F: FnMut(&FragmentSummary) -> bool> Iterator
1938 for Edits<'a, D, F>
1939{
1940 type Item = Edit<D>;
1941
1942 fn next(&mut self) -> Option<Self::Item> {
1943 let mut pending_edit: Option<Edit<D>> = None;
1944 let cursor = self.fragments_cursor.as_mut()?;
1945
1946 while let Some(fragment) = cursor.item() {
1947 let summary = self.visible_cursor.summary(cursor.start().visible);
1948 self.old_end.add_assign(&summary);
1949 self.new_end.add_assign(&summary);
1950 if pending_edit
1951 .as_ref()
1952 .map_or(false, |change| change.new.end < self.new_end)
1953 {
1954 break;
1955 }
1956
1957 if !fragment.was_visible(&self.since, &self.undos) && fragment.visible {
1958 let fragment_summary = self.visible_cursor.summary(cursor.end(&None).visible);
1959 let mut new_end = self.new_end.clone();
1960 new_end.add_assign(&fragment_summary);
1961 if let Some(pending_edit) = pending_edit.as_mut() {
1962 pending_edit.new.end = new_end.clone();
1963 } else {
1964 pending_edit = Some(Edit {
1965 old: self.old_end.clone()..self.old_end.clone(),
1966 new: self.new_end.clone()..new_end.clone(),
1967 });
1968 }
1969
1970 self.new_end = new_end;
1971 } else if fragment.was_visible(&self.since, &self.undos) && !fragment.visible {
1972 self.deleted_cursor.seek_forward(cursor.start().deleted);
1973 let fragment_summary = self.deleted_cursor.summary(cursor.end(&None).deleted);
1974 let mut old_end = self.old_end.clone();
1975 old_end.add_assign(&fragment_summary);
1976 if let Some(pending_edit) = pending_edit.as_mut() {
1977 pending_edit.old.end = old_end.clone();
1978 } else {
1979 pending_edit = Some(Edit {
1980 old: self.old_end.clone()..old_end.clone(),
1981 new: self.new_end.clone()..self.new_end.clone(),
1982 });
1983 }
1984
1985 self.old_end = old_end;
1986 }
1987
1988 cursor.next(&None);
1989 }
1990
1991 pending_edit
1992 }
1993}
1994
1995impl Fragment {
1996 fn is_visible(&self, undos: &UndoMap) -> bool {
1997 !undos.is_undone(self.insertion_timestamp.local())
1998 && self.deletions.iter().all(|d| undos.is_undone(*d))
1999 }
2000
2001 fn was_visible(&self, version: &clock::Global, undos: &UndoMap) -> bool {
2002 (version.observed(self.insertion_timestamp.local())
2003 && !undos.was_undone(self.insertion_timestamp.local(), version))
2004 && self
2005 .deletions
2006 .iter()
2007 .all(|d| !version.observed(*d) || undos.was_undone(*d, version))
2008 }
2009}
2010
2011impl sum_tree::Item for Fragment {
2012 type Summary = FragmentSummary;
2013
2014 fn summary(&self) -> Self::Summary {
2015 let mut max_version = clock::Global::new();
2016 max_version.observe(self.insertion_timestamp.local());
2017 for deletion in &self.deletions {
2018 max_version.observe(*deletion);
2019 }
2020 max_version.join(&self.max_undos);
2021
2022 let mut min_insertion_version = clock::Global::new();
2023 min_insertion_version.observe(self.insertion_timestamp.local());
2024 let max_insertion_version = min_insertion_version.clone();
2025 if self.visible {
2026 FragmentSummary {
2027 max_id: self.id.clone(),
2028 text: FragmentTextSummary {
2029 visible: self.len,
2030 deleted: 0,
2031 },
2032 max_version,
2033 min_insertion_version,
2034 max_insertion_version,
2035 }
2036 } else {
2037 FragmentSummary {
2038 max_id: self.id.clone(),
2039 text: FragmentTextSummary {
2040 visible: 0,
2041 deleted: self.len,
2042 },
2043 max_version,
2044 min_insertion_version,
2045 max_insertion_version,
2046 }
2047 }
2048 }
2049}
2050
2051impl sum_tree::Summary for FragmentSummary {
2052 type Context = Option<clock::Global>;
2053
2054 fn add_summary(&mut self, other: &Self, _: &Self::Context) {
2055 self.max_id.assign(&other.max_id);
2056 self.text.visible += &other.text.visible;
2057 self.text.deleted += &other.text.deleted;
2058 self.max_version.join(&other.max_version);
2059 self.min_insertion_version
2060 .meet(&other.min_insertion_version);
2061 self.max_insertion_version
2062 .join(&other.max_insertion_version);
2063 }
2064}
2065
2066impl Default for FragmentSummary {
2067 fn default() -> Self {
2068 FragmentSummary {
2069 max_id: Locator::min(),
2070 text: FragmentTextSummary::default(),
2071 max_version: clock::Global::new(),
2072 min_insertion_version: clock::Global::new(),
2073 max_insertion_version: clock::Global::new(),
2074 }
2075 }
2076}
2077
2078impl<'a> sum_tree::Dimension<'a, FragmentSummary> for FragmentTextSummary {
2079 fn add_summary(&mut self, summary: &'a FragmentSummary, _: &Option<clock::Global>) {
2080 self.visible += summary.text.visible;
2081 self.deleted += summary.text.deleted;
2082 }
2083}
2084
2085impl sum_tree::Item for InsertionFragment {
2086 type Summary = InsertionFragmentKey;
2087
2088 fn summary(&self) -> Self::Summary {
2089 InsertionFragmentKey {
2090 timestamp: self.timestamp,
2091 split_offset: self.split_offset,
2092 }
2093 }
2094}
2095
2096impl sum_tree::KeyedItem for InsertionFragment {
2097 type Key = InsertionFragmentKey;
2098
2099 fn key(&self) -> Self::Key {
2100 sum_tree::Item::summary(self)
2101 }
2102}
2103
2104impl InsertionFragment {
2105 fn new(fragment: &Fragment) -> Self {
2106 Self {
2107 timestamp: fragment.insertion_timestamp.local(),
2108 split_offset: fragment.insertion_offset,
2109 fragment_id: fragment.id.clone(),
2110 }
2111 }
2112
2113 fn insert_new(fragment: &Fragment) -> sum_tree::Edit<Self> {
2114 sum_tree::Edit::Insert(Self::new(fragment))
2115 }
2116}
2117
2118impl sum_tree::Summary for InsertionFragmentKey {
2119 type Context = ();
2120
2121 fn add_summary(&mut self, summary: &Self, _: &()) {
2122 *self = *summary;
2123 }
2124}
2125
2126#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
2127pub struct FullOffset(pub usize);
2128
2129impl ops::AddAssign<usize> for FullOffset {
2130 fn add_assign(&mut self, rhs: usize) {
2131 self.0 += rhs;
2132 }
2133}
2134
2135impl ops::Add<usize> for FullOffset {
2136 type Output = Self;
2137
2138 fn add(mut self, rhs: usize) -> Self::Output {
2139 self += rhs;
2140 self
2141 }
2142}
2143
2144impl ops::Sub for FullOffset {
2145 type Output = usize;
2146
2147 fn sub(self, rhs: Self) -> Self::Output {
2148 self.0 - rhs.0
2149 }
2150}
2151
2152impl<'a> sum_tree::Dimension<'a, FragmentSummary> for usize {
2153 fn add_summary(&mut self, summary: &FragmentSummary, _: &Option<clock::Global>) {
2154 *self += summary.text.visible;
2155 }
2156}
2157
2158impl<'a> sum_tree::Dimension<'a, FragmentSummary> for FullOffset {
2159 fn add_summary(&mut self, summary: &FragmentSummary, _: &Option<clock::Global>) {
2160 self.0 += summary.text.visible + summary.text.deleted;
2161 }
2162}
2163
2164impl<'a> sum_tree::Dimension<'a, FragmentSummary> for Option<&'a Locator> {
2165 fn add_summary(&mut self, summary: &'a FragmentSummary, _: &Option<clock::Global>) {
2166 *self = Some(&summary.max_id);
2167 }
2168}
2169
2170impl<'a> sum_tree::SeekTarget<'a, FragmentSummary, FragmentTextSummary> for usize {
2171 fn cmp(
2172 &self,
2173 cursor_location: &FragmentTextSummary,
2174 _: &Option<clock::Global>,
2175 ) -> cmp::Ordering {
2176 Ord::cmp(self, &cursor_location.visible)
2177 }
2178}
2179
2180#[derive(Copy, Clone, Debug, Eq, PartialEq)]
2181enum VersionedFullOffset {
2182 Offset(FullOffset),
2183 Invalid,
2184}
2185
2186impl VersionedFullOffset {
2187 fn full_offset(&self) -> FullOffset {
2188 if let Self::Offset(position) = self {
2189 *position
2190 } else {
2191 panic!("invalid version")
2192 }
2193 }
2194}
2195
2196impl Default for VersionedFullOffset {
2197 fn default() -> Self {
2198 Self::Offset(Default::default())
2199 }
2200}
2201
2202impl<'a> sum_tree::Dimension<'a, FragmentSummary> for VersionedFullOffset {
2203 fn add_summary(&mut self, summary: &'a FragmentSummary, cx: &Option<clock::Global>) {
2204 if let Self::Offset(offset) = self {
2205 let version = cx.as_ref().unwrap();
2206 if version.ge(&summary.max_insertion_version) {
2207 *offset += summary.text.visible + summary.text.deleted;
2208 } else if version.observed_any(&summary.min_insertion_version) {
2209 *self = Self::Invalid;
2210 }
2211 }
2212 }
2213}
2214
2215impl<'a> sum_tree::SeekTarget<'a, FragmentSummary, Self> for VersionedFullOffset {
2216 fn cmp(&self, cursor_position: &Self, _: &Option<clock::Global>) -> cmp::Ordering {
2217 match (self, cursor_position) {
2218 (Self::Offset(a), Self::Offset(b)) => Ord::cmp(a, b),
2219 (Self::Offset(_), Self::Invalid) => cmp::Ordering::Less,
2220 (Self::Invalid, _) => unreachable!(),
2221 }
2222 }
2223}
2224
2225impl Operation {
2226 fn replica_id(&self) -> ReplicaId {
2227 operation_queue::Operation::lamport_timestamp(self).replica_id
2228 }
2229
2230 pub fn is_edit(&self) -> bool {
2231 match self {
2232 Operation::Edit { .. } => true,
2233 _ => false,
2234 }
2235 }
2236}
2237
2238impl operation_queue::Operation for Operation {
2239 fn lamport_timestamp(&self) -> clock::Lamport {
2240 match self {
2241 Operation::Edit(edit) => edit.timestamp.lamport(),
2242 Operation::Undo {
2243 lamport_timestamp, ..
2244 } => *lamport_timestamp,
2245 Operation::UpdateSelections {
2246 lamport_timestamp, ..
2247 } => *lamport_timestamp,
2248 Operation::RemoveSelections {
2249 lamport_timestamp, ..
2250 } => *lamport_timestamp,
2251 Operation::SetActiveSelections {
2252 lamport_timestamp, ..
2253 } => *lamport_timestamp,
2254 }
2255 }
2256}
2257
2258pub trait ToOffset {
2259 fn to_offset<'a>(&self, content: &Snapshot) -> usize;
2260
2261 fn to_full_offset<'a>(&self, content: &Snapshot, bias: Bias) -> FullOffset {
2262 let offset = self.to_offset(&content);
2263 let mut cursor = content.fragments.cursor::<FragmentTextSummary>();
2264 cursor.seek(&offset, bias, &None);
2265 FullOffset(offset + cursor.start().deleted)
2266 }
2267}
2268
2269impl ToOffset for Point {
2270 fn to_offset<'a>(&self, content: &Snapshot) -> usize {
2271 content.visible_text.point_to_offset(*self)
2272 }
2273}
2274
2275impl ToOffset for PointUtf16 {
2276 fn to_offset<'a>(&self, content: &Snapshot) -> usize {
2277 content.visible_text.point_utf16_to_offset(*self)
2278 }
2279}
2280
2281impl ToOffset for usize {
2282 fn to_offset<'a>(&self, content: &Snapshot) -> usize {
2283 assert!(*self <= content.len(), "offset is out of range");
2284 *self
2285 }
2286}
2287
2288impl ToOffset for Anchor {
2289 fn to_offset<'a>(&self, content: &Snapshot) -> usize {
2290 content.summary_for_anchor(self)
2291 }
2292}
2293
2294impl<'a, T: ToOffset> ToOffset for &'a T {
2295 fn to_offset(&self, content: &Snapshot) -> usize {
2296 (*self).to_offset(content)
2297 }
2298}
2299
2300pub trait ToPoint {
2301 fn to_point<'a>(&self, content: &Snapshot) -> Point;
2302}
2303
2304impl ToPoint for Anchor {
2305 fn to_point<'a>(&self, content: &Snapshot) -> Point {
2306 content.summary_for_anchor(self)
2307 }
2308}
2309
2310impl ToPoint for usize {
2311 fn to_point<'a>(&self, content: &Snapshot) -> Point {
2312 content.visible_text.offset_to_point(*self)
2313 }
2314}
2315
2316impl ToPoint for Point {
2317 fn to_point<'a>(&self, _: &Snapshot) -> Point {
2318 *self
2319 }
2320}
2321
2322pub trait FromAnchor {
2323 fn from_anchor(anchor: &Anchor, content: &Snapshot) -> Self;
2324}
2325
2326impl FromAnchor for Point {
2327 fn from_anchor(anchor: &Anchor, content: &Snapshot) -> Self {
2328 anchor.to_point(content)
2329 }
2330}
2331
2332impl FromAnchor for usize {
2333 fn from_anchor(anchor: &Anchor, content: &Snapshot) -> Self {
2334 anchor.to_offset(content)
2335 }
2336}