lib.rs

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