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