text.rs

   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    fn summary_for_anchor<'a, D>(&'a self, anchor: &Anchor) -> D
1676    where
1677        D: TextDimension<'a>,
1678    {
1679        if *anchor == Anchor::min() {
1680            D::default()
1681        } else if *anchor == Anchor::max() {
1682            D::from_text_summary(&self.visible_text.summary())
1683        } else {
1684            let anchor_key = InsertionFragmentKey {
1685                timestamp: anchor.timestamp,
1686                split_offset: anchor.offset,
1687            };
1688            let mut insertion_cursor = self.insertions.cursor::<InsertionFragmentKey>();
1689            insertion_cursor.seek(&anchor_key, anchor.bias, &());
1690            if let Some(insertion) = insertion_cursor.item() {
1691                let comparison = sum_tree::KeyedItem::key(insertion).cmp(&anchor_key);
1692                if comparison == Ordering::Greater
1693                    || (anchor.bias == Bias::Left
1694                        && comparison == Ordering::Equal
1695                        && anchor.offset > 0)
1696                {
1697                    insertion_cursor.prev(&());
1698                }
1699            } else {
1700                insertion_cursor.prev(&());
1701            }
1702            let insertion = insertion_cursor.item().expect("invalid insertion");
1703            debug_assert_eq!(insertion.timestamp, anchor.timestamp, "invalid insertion");
1704
1705            let mut fragment_cursor = self.fragments.cursor::<(Locator, usize)>();
1706            fragment_cursor.seek(&insertion.fragment_id, Bias::Left, &None);
1707            let fragment = fragment_cursor.item().unwrap();
1708            let mut fragment_offset = fragment_cursor.start().1;
1709            if fragment.visible {
1710                fragment_offset += anchor.offset - insertion.split_offset;
1711            }
1712            self.text_summary_for_range(0..fragment_offset)
1713        }
1714    }
1715
1716    fn full_offset_for_anchor(&self, anchor: &Anchor) -> FullOffset {
1717        if *anchor == Anchor::min() {
1718            Default::default()
1719        } else if *anchor == Anchor::max() {
1720            let text = self.fragments.summary().text;
1721            FullOffset(text.visible + text.deleted)
1722        } else {
1723            let anchor_key = InsertionFragmentKey {
1724                timestamp: anchor.timestamp,
1725                split_offset: anchor.offset,
1726            };
1727            let mut insertion_cursor = self.insertions.cursor::<InsertionFragmentKey>();
1728            insertion_cursor.seek(&anchor_key, anchor.bias, &());
1729            if let Some(insertion) = insertion_cursor.item() {
1730                let comparison = sum_tree::KeyedItem::key(insertion).cmp(&anchor_key);
1731                if comparison == Ordering::Greater
1732                    || (anchor.bias == Bias::Left
1733                        && comparison == Ordering::Equal
1734                        && anchor.offset > 0)
1735                {
1736                    insertion_cursor.prev(&());
1737                }
1738            } else {
1739                insertion_cursor.prev(&());
1740            }
1741            let insertion = insertion_cursor.item().expect("invalid insertion");
1742            debug_assert_eq!(insertion.timestamp, anchor.timestamp, "invalid insertion");
1743
1744            let mut fragment_cursor = self.fragments.cursor::<(Locator, FullOffset)>();
1745            fragment_cursor.seek(&insertion.fragment_id, Bias::Left, &None);
1746            fragment_cursor.start().1 + (anchor.offset - insertion.split_offset)
1747        }
1748    }
1749
1750    pub fn text_summary_for_range<'a, D, O: ToOffset>(&'a self, range: Range<O>) -> D
1751    where
1752        D: TextDimension<'a>,
1753    {
1754        self.visible_text
1755            .cursor(range.start.to_offset(self))
1756            .summary(range.end.to_offset(self))
1757    }
1758
1759    pub fn anchor_before<T: ToOffset>(&self, position: T) -> Anchor {
1760        self.anchor_at(position, Bias::Left)
1761    }
1762
1763    pub fn anchor_after<T: ToOffset>(&self, position: T) -> Anchor {
1764        self.anchor_at(position, Bias::Right)
1765    }
1766
1767    pub fn anchor_at<T: ToOffset>(&self, position: T, bias: Bias) -> Anchor {
1768        let offset = position.to_offset(self);
1769        if bias == Bias::Left && offset == 0 {
1770            Anchor::min()
1771        } else if bias == Bias::Right && offset == self.len() {
1772            Anchor::max()
1773        } else {
1774            let mut fragment_cursor = self.fragments.cursor::<(usize, Locator)>();
1775            fragment_cursor.seek(&offset, bias, &None);
1776            let fragment = fragment_cursor.item().unwrap();
1777            let overshoot = offset - fragment_cursor.start().0;
1778            Anchor {
1779                timestamp: fragment.insertion_timestamp.local(),
1780                offset: fragment.insertion_offset + overshoot,
1781                bias,
1782            }
1783        }
1784    }
1785
1786    pub fn clip_offset(&self, offset: usize, bias: Bias) -> usize {
1787        self.visible_text.clip_offset(offset, bias)
1788    }
1789
1790    pub fn clip_point(&self, point: Point, bias: Bias) -> Point {
1791        self.visible_text.clip_point(point, bias)
1792    }
1793
1794    pub fn clip_point_utf16(&self, point: PointUtf16, bias: Bias) -> PointUtf16 {
1795        self.visible_text.clip_point_utf16(point, bias)
1796    }
1797
1798    pub fn point_for_offset(&self, offset: usize) -> Result<Point> {
1799        if offset <= self.len() {
1800            Ok(self.text_summary_for_range(0..offset))
1801        } else {
1802            Err(anyhow!("offset out of bounds"))
1803        }
1804    }
1805
1806    pub fn edits_since<'a, D>(
1807        &'a self,
1808        since: &'a clock::Global,
1809    ) -> impl 'a + Iterator<Item = Edit<D>>
1810    where
1811        D: 'a + TextDimension<'a> + Ord,
1812    {
1813        let fragments_cursor = if *since == self.version {
1814            None
1815        } else {
1816            Some(
1817                self.fragments
1818                    .filter(move |summary| !since.ge(&summary.max_version), &None),
1819            )
1820        };
1821
1822        Edits {
1823            visible_cursor: self.visible_text.cursor(0),
1824            deleted_cursor: self.deleted_text.cursor(0),
1825            fragments_cursor,
1826            undos: &self.undo_map,
1827            since,
1828            old_end: Default::default(),
1829            new_end: Default::default(),
1830        }
1831    }
1832}
1833
1834struct RopeBuilder<'a> {
1835    old_visible_cursor: rope::Cursor<'a>,
1836    old_deleted_cursor: rope::Cursor<'a>,
1837    new_visible: Rope,
1838    new_deleted: Rope,
1839}
1840
1841impl<'a> RopeBuilder<'a> {
1842    fn new(old_visible_cursor: rope::Cursor<'a>, old_deleted_cursor: rope::Cursor<'a>) -> Self {
1843        Self {
1844            old_visible_cursor,
1845            old_deleted_cursor,
1846            new_visible: Rope::new(),
1847            new_deleted: Rope::new(),
1848        }
1849    }
1850
1851    fn push_tree(&mut self, len: FragmentTextSummary) {
1852        self.push(len.visible, true, true);
1853        self.push(len.deleted, false, false);
1854    }
1855
1856    fn push_fragment(&mut self, fragment: &Fragment, was_visible: bool) {
1857        debug_assert!(fragment.len > 0);
1858        self.push(fragment.len, was_visible, fragment.visible)
1859    }
1860
1861    fn push(&mut self, len: usize, was_visible: bool, is_visible: bool) {
1862        let text = if was_visible {
1863            self.old_visible_cursor
1864                .slice(self.old_visible_cursor.offset() + len)
1865        } else {
1866            self.old_deleted_cursor
1867                .slice(self.old_deleted_cursor.offset() + len)
1868        };
1869        if is_visible {
1870            self.new_visible.append(text);
1871        } else {
1872            self.new_deleted.append(text);
1873        }
1874    }
1875
1876    fn push_str(&mut self, text: &str) {
1877        self.new_visible.push(text);
1878    }
1879
1880    fn finish(mut self) -> (Rope, Rope) {
1881        self.new_visible.append(self.old_visible_cursor.suffix());
1882        self.new_deleted.append(self.old_deleted_cursor.suffix());
1883        (self.new_visible, self.new_deleted)
1884    }
1885}
1886
1887impl<'a, D: TextDimension<'a> + Ord, F: FnMut(&FragmentSummary) -> bool> Iterator
1888    for Edits<'a, D, F>
1889{
1890    type Item = Edit<D>;
1891
1892    fn next(&mut self) -> Option<Self::Item> {
1893        let mut pending_edit: Option<Edit<D>> = None;
1894        let cursor = self.fragments_cursor.as_mut()?;
1895
1896        while let Some(fragment) = cursor.item() {
1897            let summary = self.visible_cursor.summary(cursor.start().visible);
1898            self.old_end.add_assign(&summary);
1899            self.new_end.add_assign(&summary);
1900            if pending_edit
1901                .as_ref()
1902                .map_or(false, |change| change.new.end < self.new_end)
1903            {
1904                break;
1905            }
1906
1907            if !fragment.was_visible(&self.since, &self.undos) && fragment.visible {
1908                let fragment_summary = self.visible_cursor.summary(cursor.end(&None).visible);
1909                let mut new_end = self.new_end.clone();
1910                new_end.add_assign(&fragment_summary);
1911                if let Some(pending_edit) = pending_edit.as_mut() {
1912                    pending_edit.new.end = new_end.clone();
1913                } else {
1914                    pending_edit = Some(Edit {
1915                        old: self.old_end.clone()..self.old_end.clone(),
1916                        new: self.new_end.clone()..new_end.clone(),
1917                    });
1918                }
1919
1920                self.new_end = new_end;
1921            } else if fragment.was_visible(&self.since, &self.undos) && !fragment.visible {
1922                self.deleted_cursor.seek_forward(cursor.start().deleted);
1923                let fragment_summary = self.deleted_cursor.summary(cursor.end(&None).deleted);
1924                let mut old_end = self.old_end.clone();
1925                old_end.add_assign(&fragment_summary);
1926                if let Some(pending_edit) = pending_edit.as_mut() {
1927                    pending_edit.old.end = old_end.clone();
1928                } else {
1929                    pending_edit = Some(Edit {
1930                        old: self.old_end.clone()..old_end.clone(),
1931                        new: self.new_end.clone()..self.new_end.clone(),
1932                    });
1933                }
1934
1935                self.old_end = old_end;
1936            }
1937
1938            cursor.next(&None);
1939        }
1940
1941        pending_edit
1942    }
1943}
1944
1945impl Fragment {
1946    fn is_visible(&self, undos: &UndoMap) -> bool {
1947        !undos.is_undone(self.insertion_timestamp.local())
1948            && self.deletions.iter().all(|d| undos.is_undone(*d))
1949    }
1950
1951    fn was_visible(&self, version: &clock::Global, undos: &UndoMap) -> bool {
1952        (version.observed(self.insertion_timestamp.local())
1953            && !undos.was_undone(self.insertion_timestamp.local(), version))
1954            && self
1955                .deletions
1956                .iter()
1957                .all(|d| !version.observed(*d) || undos.was_undone(*d, version))
1958    }
1959}
1960
1961impl sum_tree::Item for Fragment {
1962    type Summary = FragmentSummary;
1963
1964    fn summary(&self) -> Self::Summary {
1965        let mut max_version = clock::Global::new();
1966        max_version.observe(self.insertion_timestamp.local());
1967        for deletion in &self.deletions {
1968            max_version.observe(*deletion);
1969        }
1970        max_version.join(&self.max_undos);
1971
1972        let mut min_insertion_version = clock::Global::new();
1973        min_insertion_version.observe(self.insertion_timestamp.local());
1974        let max_insertion_version = min_insertion_version.clone();
1975        if self.visible {
1976            FragmentSummary {
1977                max_id: self.id.clone(),
1978                text: FragmentTextSummary {
1979                    visible: self.len,
1980                    deleted: 0,
1981                },
1982                max_version,
1983                min_insertion_version,
1984                max_insertion_version,
1985            }
1986        } else {
1987            FragmentSummary {
1988                max_id: self.id.clone(),
1989                text: FragmentTextSummary {
1990                    visible: 0,
1991                    deleted: self.len,
1992                },
1993                max_version,
1994                min_insertion_version,
1995                max_insertion_version,
1996            }
1997        }
1998    }
1999}
2000
2001impl sum_tree::Summary for FragmentSummary {
2002    type Context = Option<clock::Global>;
2003
2004    fn add_summary(&mut self, other: &Self, _: &Self::Context) {
2005        self.max_id = other.max_id.clone();
2006        self.text.visible += &other.text.visible;
2007        self.text.deleted += &other.text.deleted;
2008        self.max_version.join(&other.max_version);
2009        self.min_insertion_version
2010            .meet(&other.min_insertion_version);
2011        self.max_insertion_version
2012            .join(&other.max_insertion_version);
2013    }
2014}
2015
2016impl Default for FragmentSummary {
2017    fn default() -> Self {
2018        FragmentSummary {
2019            max_id: Locator::min(),
2020            text: FragmentTextSummary::default(),
2021            max_version: clock::Global::new(),
2022            min_insertion_version: clock::Global::new(),
2023            max_insertion_version: clock::Global::new(),
2024        }
2025    }
2026}
2027
2028impl<'a> sum_tree::Dimension<'a, FragmentSummary> for FragmentTextSummary {
2029    fn add_summary(&mut self, summary: &'a FragmentSummary, _: &Option<clock::Global>) {
2030        self.visible += summary.text.visible;
2031        self.deleted += summary.text.deleted;
2032    }
2033}
2034
2035impl sum_tree::Item for InsertionFragment {
2036    type Summary = InsertionFragmentKey;
2037
2038    fn summary(&self) -> Self::Summary {
2039        InsertionFragmentKey {
2040            timestamp: self.timestamp,
2041            split_offset: self.split_offset,
2042        }
2043    }
2044}
2045
2046impl sum_tree::KeyedItem for InsertionFragment {
2047    type Key = InsertionFragmentKey;
2048
2049    fn key(&self) -> Self::Key {
2050        sum_tree::Item::summary(self)
2051    }
2052}
2053
2054impl InsertionFragment {
2055    fn new(fragment: &Fragment) -> Self {
2056        Self {
2057            timestamp: fragment.insertion_timestamp.local(),
2058            split_offset: fragment.insertion_offset,
2059            fragment_id: fragment.id.clone(),
2060        }
2061    }
2062
2063    fn insert_new(fragment: &Fragment) -> sum_tree::Edit<Self> {
2064        sum_tree::Edit::Insert(Self::new(fragment))
2065    }
2066}
2067
2068impl sum_tree::Summary for InsertionFragmentKey {
2069    type Context = ();
2070
2071    fn add_summary(&mut self, summary: &Self, _: &()) {
2072        *self = *summary;
2073    }
2074}
2075
2076#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
2077pub struct FullOffset(pub usize);
2078
2079impl ops::AddAssign<usize> for FullOffset {
2080    fn add_assign(&mut self, rhs: usize) {
2081        self.0 += rhs;
2082    }
2083}
2084
2085impl ops::Add<usize> for FullOffset {
2086    type Output = Self;
2087
2088    fn add(mut self, rhs: usize) -> Self::Output {
2089        self += rhs;
2090        self
2091    }
2092}
2093
2094impl ops::Sub for FullOffset {
2095    type Output = usize;
2096
2097    fn sub(self, rhs: Self) -> Self::Output {
2098        self.0 - rhs.0
2099    }
2100}
2101
2102impl<'a> sum_tree::Dimension<'a, FragmentSummary> for usize {
2103    fn add_summary(&mut self, summary: &FragmentSummary, _: &Option<clock::Global>) {
2104        *self += summary.text.visible;
2105    }
2106}
2107
2108impl<'a> sum_tree::Dimension<'a, FragmentSummary> for FullOffset {
2109    fn add_summary(&mut self, summary: &FragmentSummary, _: &Option<clock::Global>) {
2110        self.0 += summary.text.visible + summary.text.deleted;
2111    }
2112}
2113
2114impl<'a> sum_tree::Dimension<'a, FragmentSummary> for Locator {
2115    fn add_summary(&mut self, summary: &FragmentSummary, _: &Option<clock::Global>) {
2116        *self = summary.max_id.clone();
2117    }
2118}
2119
2120impl<'a> sum_tree::SeekTarget<'a, FragmentSummary, FragmentTextSummary> for usize {
2121    fn cmp(
2122        &self,
2123        cursor_location: &FragmentTextSummary,
2124        _: &Option<clock::Global>,
2125    ) -> cmp::Ordering {
2126        Ord::cmp(self, &cursor_location.visible)
2127    }
2128}
2129
2130#[derive(Copy, Clone, Debug, Eq, PartialEq)]
2131enum VersionedFullOffset {
2132    Offset(FullOffset),
2133    Invalid,
2134}
2135
2136impl VersionedFullOffset {
2137    fn full_offset(&self) -> FullOffset {
2138        if let Self::Offset(position) = self {
2139            *position
2140        } else {
2141            panic!("invalid version")
2142        }
2143    }
2144}
2145
2146impl Default for VersionedFullOffset {
2147    fn default() -> Self {
2148        Self::Offset(Default::default())
2149    }
2150}
2151
2152impl<'a> sum_tree::Dimension<'a, FragmentSummary> for VersionedFullOffset {
2153    fn add_summary(&mut self, summary: &'a FragmentSummary, cx: &Option<clock::Global>) {
2154        if let Self::Offset(offset) = self {
2155            let version = cx.as_ref().unwrap();
2156            if version.ge(&summary.max_insertion_version) {
2157                *offset += summary.text.visible + summary.text.deleted;
2158            } else if version.observed_any(&summary.min_insertion_version) {
2159                *self = Self::Invalid;
2160            }
2161        }
2162    }
2163}
2164
2165impl<'a> sum_tree::SeekTarget<'a, FragmentSummary, Self> for VersionedFullOffset {
2166    fn cmp(&self, cursor_position: &Self, _: &Option<clock::Global>) -> cmp::Ordering {
2167        match (self, cursor_position) {
2168            (Self::Offset(a), Self::Offset(b)) => Ord::cmp(a, b),
2169            (Self::Offset(_), Self::Invalid) => cmp::Ordering::Less,
2170            (Self::Invalid, _) => unreachable!(),
2171        }
2172    }
2173}
2174
2175impl Operation {
2176    fn replica_id(&self) -> ReplicaId {
2177        operation_queue::Operation::lamport_timestamp(self).replica_id
2178    }
2179
2180    pub fn is_edit(&self) -> bool {
2181        match self {
2182            Operation::Edit { .. } => true,
2183            _ => false,
2184        }
2185    }
2186}
2187
2188impl operation_queue::Operation for Operation {
2189    fn lamport_timestamp(&self) -> clock::Lamport {
2190        match self {
2191            Operation::Edit(edit) => edit.timestamp.lamport(),
2192            Operation::Undo {
2193                lamport_timestamp, ..
2194            } => *lamport_timestamp,
2195            Operation::UpdateSelections {
2196                lamport_timestamp, ..
2197            } => *lamport_timestamp,
2198            Operation::RemoveSelections {
2199                lamport_timestamp, ..
2200            } => *lamport_timestamp,
2201            Operation::SetActiveSelections {
2202                lamport_timestamp, ..
2203            } => *lamport_timestamp,
2204        }
2205    }
2206}
2207
2208pub trait ToOffset {
2209    fn to_offset<'a>(&self, content: &Snapshot) -> usize;
2210
2211    fn to_full_offset<'a>(&self, content: &Snapshot, bias: Bias) -> FullOffset {
2212        let offset = self.to_offset(&content);
2213        let mut cursor = content.fragments.cursor::<FragmentTextSummary>();
2214        cursor.seek(&offset, bias, &None);
2215        FullOffset(offset + cursor.start().deleted)
2216    }
2217}
2218
2219impl ToOffset for Point {
2220    fn to_offset<'a>(&self, content: &Snapshot) -> usize {
2221        content.visible_text.point_to_offset(*self)
2222    }
2223}
2224
2225impl ToOffset for PointUtf16 {
2226    fn to_offset<'a>(&self, content: &Snapshot) -> usize {
2227        content.visible_text.point_utf16_to_offset(*self)
2228    }
2229}
2230
2231impl ToOffset for usize {
2232    fn to_offset<'a>(&self, content: &Snapshot) -> usize {
2233        assert!(*self <= content.len(), "offset is out of range");
2234        *self
2235    }
2236}
2237
2238impl ToOffset for Anchor {
2239    fn to_offset<'a>(&self, content: &Snapshot) -> usize {
2240        content.summary_for_anchor(self)
2241    }
2242}
2243
2244impl<'a, T: ToOffset> ToOffset for &'a T {
2245    fn to_offset(&self, content: &Snapshot) -> usize {
2246        (*self).to_offset(content)
2247    }
2248}
2249
2250pub trait ToPoint {
2251    fn to_point<'a>(&self, content: &Snapshot) -> Point;
2252}
2253
2254impl ToPoint for Anchor {
2255    fn to_point<'a>(&self, content: &Snapshot) -> Point {
2256        content.summary_for_anchor(self)
2257    }
2258}
2259
2260impl ToPoint for usize {
2261    fn to_point<'a>(&self, content: &Snapshot) -> Point {
2262        content.visible_text.offset_to_point(*self)
2263    }
2264}
2265
2266impl ToPoint for Point {
2267    fn to_point<'a>(&self, _: &Snapshot) -> Point {
2268        *self
2269    }
2270}
2271
2272pub trait FromAnchor {
2273    fn from_anchor(anchor: &Anchor, content: &Snapshot) -> Self;
2274}
2275
2276impl FromAnchor for Point {
2277    fn from_anchor(anchor: &Anchor, content: &Snapshot) -> Self {
2278        anchor.to_point(content)
2279    }
2280}
2281
2282impl FromAnchor for usize {
2283    fn from_anchor(anchor: &Anchor, content: &Snapshot) -> Self {
2284        anchor.to_offset(content)
2285    }
2286}