rope.rs

   1mod chunk;
   2mod offset_utf16;
   3mod point;
   4mod point_utf16;
   5mod unclipped;
   6
   7use chunk::Chunk;
   8use rayon::iter::{IntoParallelIterator, ParallelIterator as _};
   9use smallvec::SmallVec;
  10use std::{
  11    cmp, fmt, io, mem,
  12    ops::{self, AddAssign, Range},
  13    str,
  14};
  15use sum_tree::{Bias, Dimension, Dimensions, SumTree};
  16
  17pub use chunk::ChunkSlice;
  18pub use offset_utf16::OffsetUtf16;
  19pub use point::Point;
  20pub use point_utf16::PointUtf16;
  21pub use unclipped::Unclipped;
  22
  23#[derive(Clone, Default)]
  24pub struct Rope {
  25    chunks: SumTree<Chunk>,
  26}
  27
  28impl Rope {
  29    pub fn new() -> Self {
  30        Self::default()
  31    }
  32
  33    pub fn append(&mut self, rope: Rope) {
  34        if let Some(chunk) = rope.chunks.first()
  35            && (self
  36                .chunks
  37                .last()
  38                .is_some_and(|c| c.text.len() < chunk::MIN_BASE)
  39                || chunk.text.len() < chunk::MIN_BASE)
  40        {
  41            self.push_chunk(chunk.as_slice());
  42
  43            let mut chunks = rope.chunks.cursor::<()>(&());
  44            chunks.next();
  45            chunks.next();
  46            self.chunks.append(chunks.suffix(), &());
  47            self.check_invariants();
  48            return;
  49        }
  50
  51        self.chunks.append(rope.chunks.clone(), &());
  52        self.check_invariants();
  53    }
  54
  55    pub fn replace(&mut self, range: Range<usize>, text: &str) {
  56        let mut new_rope = Rope::new();
  57        let mut cursor = self.cursor(0);
  58        new_rope.append(cursor.slice(range.start));
  59        cursor.seek_forward(range.end);
  60        new_rope.push(text);
  61        new_rope.append(cursor.suffix());
  62        *self = new_rope;
  63    }
  64
  65    pub fn slice(&self, range: Range<usize>) -> Rope {
  66        let mut cursor = self.cursor(0);
  67        cursor.seek_forward(range.start);
  68        cursor.slice(range.end)
  69    }
  70
  71    pub fn slice_rows(&self, range: Range<u32>) -> Rope {
  72        // This would be more efficient with a forward advance after the first, but it's fine.
  73        let start = self.point_to_offset(Point::new(range.start, 0));
  74        let end = self.point_to_offset(Point::new(range.end, 0));
  75        self.slice(start..end)
  76    }
  77
  78    pub fn push(&mut self, mut text: &str) {
  79        self.chunks.update_last(
  80            |last_chunk| {
  81                let split_ix = if last_chunk.text.len() + text.len() <= chunk::MAX_BASE {
  82                    text.len()
  83                } else {
  84                    let mut split_ix = cmp::min(
  85                        chunk::MIN_BASE.saturating_sub(last_chunk.text.len()),
  86                        text.len(),
  87                    );
  88                    while !text.is_char_boundary(split_ix) {
  89                        split_ix += 1;
  90                    }
  91                    split_ix
  92                };
  93
  94                let (suffix, remainder) = text.split_at(split_ix);
  95                last_chunk.push_str(suffix);
  96                text = remainder;
  97            },
  98            &(),
  99        );
 100
 101        if text.len() > 2048 {
 102            return self.push_large(text);
 103        }
 104        let mut new_chunks = SmallVec::<[_; 16]>::new();
 105
 106        while !text.is_empty() {
 107            let mut split_ix = cmp::min(chunk::MAX_BASE, text.len());
 108            while !text.is_char_boundary(split_ix) {
 109                split_ix -= 1;
 110            }
 111            let (chunk, remainder) = text.split_at(split_ix);
 112            new_chunks.push(chunk);
 113            text = remainder;
 114        }
 115
 116        #[cfg(test)]
 117        const PARALLEL_THRESHOLD: usize = 4;
 118        #[cfg(not(test))]
 119        const PARALLEL_THRESHOLD: usize = 4 * (2 * sum_tree::TREE_BASE);
 120
 121        if new_chunks.len() >= PARALLEL_THRESHOLD {
 122            self.chunks
 123                .par_extend(new_chunks.into_vec().into_par_iter().map(Chunk::new), &());
 124        } else {
 125            self.chunks
 126                .extend(new_chunks.into_iter().map(Chunk::new), &());
 127        }
 128
 129        self.check_invariants();
 130    }
 131
 132    /// A copy of `push` specialized for working with large quantities of text.
 133    fn push_large(&mut self, mut text: &str) {
 134        // To avoid frequent reallocs when loading large swaths of file contents,
 135        // we estimate worst-case `new_chunks` capacity;
 136        // Chunk is a fixed-capacity buffer. If a character falls on
 137        // chunk boundary, we push it off to the following chunk (thus leaving a small bit of capacity unfilled in current chunk).
 138        // Worst-case chunk count when loading a file is then a case where every chunk ends up with that unused capacity.
 139        // Since we're working with UTF-8, each character is at most 4 bytes wide. It follows then that the worst case is where
 140        // a chunk ends with 3 bytes of a 4-byte character. These 3 bytes end up being stored in the following chunk, thus wasting
 141        // 3 bytes of storage in current chunk.
 142        // For example, a 1024-byte string can occupy between 32 (full ASCII, 1024/32) and 36 (full 4-byte UTF-8, 1024 / 29 rounded up) chunks.
 143        const MIN_CHUNK_SIZE: usize = chunk::MAX_BASE - 3;
 144
 145        // We also round up the capacity up by one, for a good measure; we *really* don't want to realloc here, as we assume that the # of characters
 146        // we're working with there is large.
 147        let capacity = text.len().div_ceil(MIN_CHUNK_SIZE);
 148        let mut new_chunks = Vec::with_capacity(capacity);
 149
 150        while !text.is_empty() {
 151            let mut split_ix = cmp::min(chunk::MAX_BASE, text.len());
 152            while !text.is_char_boundary(split_ix) {
 153                split_ix -= 1;
 154            }
 155            let (chunk, remainder) = text.split_at(split_ix);
 156            new_chunks.push(chunk);
 157            text = remainder;
 158        }
 159
 160        #[cfg(test)]
 161        const PARALLEL_THRESHOLD: usize = 4;
 162        #[cfg(not(test))]
 163        const PARALLEL_THRESHOLD: usize = 4 * (2 * sum_tree::TREE_BASE);
 164
 165        if new_chunks.len() >= PARALLEL_THRESHOLD {
 166            self.chunks
 167                .par_extend(new_chunks.into_par_iter().map(Chunk::new), &());
 168        } else {
 169            self.chunks
 170                .extend(new_chunks.into_iter().map(Chunk::new), &());
 171        }
 172
 173        self.check_invariants();
 174    }
 175
 176    fn push_chunk(&mut self, mut chunk: ChunkSlice) {
 177        self.chunks.update_last(
 178            |last_chunk| {
 179                let split_ix = if last_chunk.text.len() + chunk.len() <= chunk::MAX_BASE {
 180                    chunk.len()
 181                } else {
 182                    let mut split_ix = cmp::min(
 183                        chunk::MIN_BASE.saturating_sub(last_chunk.text.len()),
 184                        chunk.len(),
 185                    );
 186                    while !chunk.is_char_boundary(split_ix) {
 187                        split_ix += 1;
 188                    }
 189                    split_ix
 190                };
 191
 192                let (suffix, remainder) = chunk.split_at(split_ix);
 193                last_chunk.append(suffix);
 194                chunk = remainder;
 195            },
 196            &(),
 197        );
 198
 199        if !chunk.is_empty() {
 200            self.chunks.push(chunk.into(), &());
 201        }
 202    }
 203
 204    pub fn push_front(&mut self, text: &str) {
 205        let suffix = mem::replace(self, Rope::from(text));
 206        self.append(suffix);
 207    }
 208
 209    fn check_invariants(&self) {
 210        #[cfg(test)]
 211        {
 212            // Ensure all chunks except maybe the last one are not underflowing.
 213            // Allow some wiggle room for multibyte characters at chunk boundaries.
 214            let mut chunks = self.chunks.cursor::<()>(&()).peekable();
 215            while let Some(chunk) = chunks.next() {
 216                if chunks.peek().is_some() {
 217                    assert!(chunk.text.len() + 3 >= chunk::MIN_BASE);
 218                }
 219            }
 220        }
 221    }
 222
 223    pub fn summary(&self) -> TextSummary {
 224        self.chunks.summary().text
 225    }
 226
 227    pub fn len(&self) -> usize {
 228        self.chunks.extent(&())
 229    }
 230
 231    pub fn is_empty(&self) -> bool {
 232        self.len() == 0
 233    }
 234
 235    pub fn max_point(&self) -> Point {
 236        self.chunks.extent(&())
 237    }
 238
 239    pub fn max_point_utf16(&self) -> PointUtf16 {
 240        self.chunks.extent(&())
 241    }
 242
 243    pub fn cursor(&self, offset: usize) -> Cursor<'_> {
 244        Cursor::new(self, offset)
 245    }
 246
 247    pub fn chars(&self) -> impl Iterator<Item = char> + '_ {
 248        self.chars_at(0)
 249    }
 250
 251    pub fn chars_at(&self, start: usize) -> impl Iterator<Item = char> + '_ {
 252        self.chunks_in_range(start..self.len()).flat_map(str::chars)
 253    }
 254
 255    pub fn reversed_chars_at(&self, start: usize) -> impl Iterator<Item = char> + '_ {
 256        self.reversed_chunks_in_range(0..start)
 257            .flat_map(|chunk| chunk.chars().rev())
 258    }
 259
 260    pub fn bytes_in_range(&self, range: Range<usize>) -> Bytes<'_> {
 261        Bytes::new(self, range, false)
 262    }
 263
 264    pub fn reversed_bytes_in_range(&self, range: Range<usize>) -> Bytes<'_> {
 265        Bytes::new(self, range, true)
 266    }
 267
 268    pub fn chunks(&self) -> Chunks<'_> {
 269        self.chunks_in_range(0..self.len())
 270    }
 271
 272    pub fn chunks_in_range(&self, range: Range<usize>) -> Chunks<'_> {
 273        Chunks::new(self, range, false)
 274    }
 275
 276    pub fn reversed_chunks_in_range(&self, range: Range<usize>) -> Chunks<'_> {
 277        Chunks::new(self, range, true)
 278    }
 279
 280    pub fn offset_to_offset_utf16(&self, offset: usize) -> OffsetUtf16 {
 281        if offset >= self.summary().len {
 282            return self.summary().len_utf16;
 283        }
 284        let mut cursor = self.chunks.cursor::<Dimensions<usize, OffsetUtf16>>(&());
 285        cursor.seek(&offset, Bias::Left);
 286        let overshoot = offset - cursor.start().0;
 287        cursor.start().1
 288            + cursor.item().map_or(Default::default(), |chunk| {
 289                chunk.as_slice().offset_to_offset_utf16(overshoot)
 290            })
 291    }
 292
 293    pub fn offset_utf16_to_offset(&self, offset: OffsetUtf16) -> usize {
 294        if offset >= self.summary().len_utf16 {
 295            return self.summary().len;
 296        }
 297        let mut cursor = self.chunks.cursor::<Dimensions<OffsetUtf16, usize>>(&());
 298        cursor.seek(&offset, Bias::Left);
 299        let overshoot = offset - cursor.start().0;
 300        cursor.start().1
 301            + cursor.item().map_or(Default::default(), |chunk| {
 302                chunk.as_slice().offset_utf16_to_offset(overshoot)
 303            })
 304    }
 305
 306    pub fn offset_to_point(&self, offset: usize) -> Point {
 307        if offset >= self.summary().len {
 308            return self.summary().lines;
 309        }
 310        let mut cursor = self.chunks.cursor::<Dimensions<usize, Point>>(&());
 311        cursor.seek(&offset, Bias::Left);
 312        let overshoot = offset - cursor.start().0;
 313        cursor.start().1
 314            + cursor.item().map_or(Point::zero(), |chunk| {
 315                chunk.as_slice().offset_to_point(overshoot)
 316            })
 317    }
 318
 319    pub fn offset_to_point_utf16(&self, offset: usize) -> PointUtf16 {
 320        if offset >= self.summary().len {
 321            return self.summary().lines_utf16();
 322        }
 323        let mut cursor = self.chunks.cursor::<Dimensions<usize, PointUtf16>>(&());
 324        cursor.seek(&offset, Bias::Left);
 325        let overshoot = offset - cursor.start().0;
 326        cursor.start().1
 327            + cursor.item().map_or(PointUtf16::zero(), |chunk| {
 328                chunk.as_slice().offset_to_point_utf16(overshoot)
 329            })
 330    }
 331
 332    pub fn point_to_point_utf16(&self, point: Point) -> PointUtf16 {
 333        if point >= self.summary().lines {
 334            return self.summary().lines_utf16();
 335        }
 336        let mut cursor = self.chunks.cursor::<Dimensions<Point, PointUtf16>>(&());
 337        cursor.seek(&point, Bias::Left);
 338        let overshoot = point - cursor.start().0;
 339        cursor.start().1
 340            + cursor.item().map_or(PointUtf16::zero(), |chunk| {
 341                chunk.as_slice().point_to_point_utf16(overshoot)
 342            })
 343    }
 344
 345    pub fn point_to_offset(&self, point: Point) -> usize {
 346        if point >= self.summary().lines {
 347            return self.summary().len;
 348        }
 349        let mut cursor = self.chunks.cursor::<Dimensions<Point, usize>>(&());
 350        cursor.seek(&point, Bias::Left);
 351        let overshoot = point - cursor.start().0;
 352        cursor.start().1
 353            + cursor
 354                .item()
 355                .map_or(0, |chunk| chunk.as_slice().point_to_offset(overshoot))
 356    }
 357
 358    pub fn point_utf16_to_offset(&self, point: PointUtf16) -> usize {
 359        self.point_utf16_to_offset_impl(point, false)
 360    }
 361
 362    pub fn unclipped_point_utf16_to_offset(&self, point: Unclipped<PointUtf16>) -> usize {
 363        self.point_utf16_to_offset_impl(point.0, true)
 364    }
 365
 366    fn point_utf16_to_offset_impl(&self, point: PointUtf16, clip: bool) -> usize {
 367        if point >= self.summary().lines_utf16() {
 368            return self.summary().len;
 369        }
 370        let mut cursor = self.chunks.cursor::<Dimensions<PointUtf16, usize>>(&());
 371        cursor.seek(&point, Bias::Left);
 372        let overshoot = point - cursor.start().0;
 373        cursor.start().1
 374            + cursor.item().map_or(0, |chunk| {
 375                chunk.as_slice().point_utf16_to_offset(overshoot, clip)
 376            })
 377    }
 378
 379    pub fn unclipped_point_utf16_to_point(&self, point: Unclipped<PointUtf16>) -> Point {
 380        if point.0 >= self.summary().lines_utf16() {
 381            return self.summary().lines;
 382        }
 383        let mut cursor = self.chunks.cursor::<Dimensions<PointUtf16, Point>>(&());
 384        cursor.seek(&point.0, Bias::Left);
 385        let overshoot = Unclipped(point.0 - cursor.start().0);
 386        cursor.start().1
 387            + cursor.item().map_or(Point::zero(), |chunk| {
 388                chunk.as_slice().unclipped_point_utf16_to_point(overshoot)
 389            })
 390    }
 391
 392    pub fn clip_offset(&self, mut offset: usize, bias: Bias) -> usize {
 393        let mut cursor = self.chunks.cursor::<usize>(&());
 394        cursor.seek(&offset, Bias::Left);
 395        if let Some(chunk) = cursor.item() {
 396            let mut ix = offset - cursor.start();
 397            while !chunk.text.is_char_boundary(ix) {
 398                match bias {
 399                    Bias::Left => {
 400                        ix -= 1;
 401                        offset -= 1;
 402                    }
 403                    Bias::Right => {
 404                        ix += 1;
 405                        offset += 1;
 406                    }
 407                }
 408            }
 409            offset
 410        } else {
 411            self.summary().len
 412        }
 413    }
 414
 415    pub fn clip_offset_utf16(&self, offset: OffsetUtf16, bias: Bias) -> OffsetUtf16 {
 416        let mut cursor = self.chunks.cursor::<OffsetUtf16>(&());
 417        cursor.seek(&offset, Bias::Right);
 418        if let Some(chunk) = cursor.item() {
 419            let overshoot = offset - cursor.start();
 420            *cursor.start() + chunk.as_slice().clip_offset_utf16(overshoot, bias)
 421        } else {
 422            self.summary().len_utf16
 423        }
 424    }
 425
 426    pub fn clip_point(&self, point: Point, bias: Bias) -> Point {
 427        let mut cursor = self.chunks.cursor::<Point>(&());
 428        cursor.seek(&point, Bias::Right);
 429        if let Some(chunk) = cursor.item() {
 430            let overshoot = point - cursor.start();
 431            *cursor.start() + chunk.as_slice().clip_point(overshoot, bias)
 432        } else {
 433            self.summary().lines
 434        }
 435    }
 436
 437    pub fn clip_point_utf16(&self, point: Unclipped<PointUtf16>, bias: Bias) -> PointUtf16 {
 438        let mut cursor = self.chunks.cursor::<PointUtf16>(&());
 439        cursor.seek(&point.0, Bias::Right);
 440        if let Some(chunk) = cursor.item() {
 441            let overshoot = Unclipped(point.0 - cursor.start());
 442            *cursor.start() + chunk.as_slice().clip_point_utf16(overshoot, bias)
 443        } else {
 444            self.summary().lines_utf16()
 445        }
 446    }
 447
 448    pub fn line_len(&self, row: u32) -> u32 {
 449        self.clip_point(Point::new(row, u32::MAX), Bias::Left)
 450            .column
 451    }
 452}
 453
 454impl<'a> From<&'a str> for Rope {
 455    fn from(text: &'a str) -> Self {
 456        let mut rope = Self::new();
 457        rope.push(text);
 458        rope
 459    }
 460}
 461
 462impl<'a> FromIterator<&'a str> for Rope {
 463    fn from_iter<T: IntoIterator<Item = &'a str>>(iter: T) -> Self {
 464        let mut rope = Rope::new();
 465        for chunk in iter {
 466            rope.push(chunk);
 467        }
 468        rope
 469    }
 470}
 471
 472impl From<String> for Rope {
 473    #[inline(always)]
 474    fn from(text: String) -> Self {
 475        Rope::from(text.as_str())
 476    }
 477}
 478
 479impl From<&String> for Rope {
 480    #[inline(always)]
 481    fn from(text: &String) -> Self {
 482        Rope::from(text.as_str())
 483    }
 484}
 485
 486impl fmt::Display for Rope {
 487    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 488        for chunk in self.chunks() {
 489            write!(f, "{}", chunk)?;
 490        }
 491        Ok(())
 492    }
 493}
 494
 495impl fmt::Debug for Rope {
 496    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 497        use std::fmt::Write as _;
 498
 499        write!(f, "\"")?;
 500        let mut format_string = String::new();
 501        for chunk in self.chunks() {
 502            write!(&mut format_string, "{:?}", chunk)?;
 503            write!(f, "{}", &format_string[1..format_string.len() - 1])?;
 504            format_string.clear();
 505        }
 506        write!(f, "\"")?;
 507        Ok(())
 508    }
 509}
 510
 511pub struct Cursor<'a> {
 512    rope: &'a Rope,
 513    chunks: sum_tree::Cursor<'a, Chunk, usize>,
 514    offset: usize,
 515}
 516
 517impl<'a> Cursor<'a> {
 518    pub fn new(rope: &'a Rope, offset: usize) -> Self {
 519        let mut chunks = rope.chunks.cursor(&());
 520        chunks.seek(&offset, Bias::Right);
 521        Self {
 522            rope,
 523            chunks,
 524            offset,
 525        }
 526    }
 527
 528    pub fn seek_forward(&mut self, end_offset: usize) {
 529        debug_assert!(end_offset >= self.offset);
 530
 531        self.chunks.seek_forward(&end_offset, Bias::Right);
 532        self.offset = end_offset;
 533    }
 534
 535    pub fn slice(&mut self, end_offset: usize) -> Rope {
 536        debug_assert!(
 537            end_offset >= self.offset,
 538            "cannot slice backwards from {} to {}",
 539            self.offset,
 540            end_offset
 541        );
 542
 543        let mut slice = Rope::new();
 544        if let Some(start_chunk) = self.chunks.item() {
 545            let start_ix = self.offset - self.chunks.start();
 546            let end_ix = cmp::min(end_offset, self.chunks.end()) - self.chunks.start();
 547            slice.push_chunk(start_chunk.slice(start_ix..end_ix));
 548        }
 549
 550        if end_offset > self.chunks.end() {
 551            self.chunks.next();
 552            slice.append(Rope {
 553                chunks: self.chunks.slice(&end_offset, Bias::Right),
 554            });
 555            if let Some(end_chunk) = self.chunks.item() {
 556                let end_ix = end_offset - self.chunks.start();
 557                slice.push_chunk(end_chunk.slice(0..end_ix));
 558            }
 559        }
 560
 561        self.offset = end_offset;
 562        slice
 563    }
 564
 565    pub fn summary<D: TextDimension>(&mut self, end_offset: usize) -> D {
 566        debug_assert!(end_offset >= self.offset);
 567
 568        let mut summary = D::zero(&());
 569        if let Some(start_chunk) = self.chunks.item() {
 570            let start_ix = self.offset - self.chunks.start();
 571            let end_ix = cmp::min(end_offset, self.chunks.end()) - self.chunks.start();
 572            summary.add_assign(&D::from_chunk(start_chunk.slice(start_ix..end_ix)));
 573        }
 574
 575        if end_offset > self.chunks.end() {
 576            self.chunks.next();
 577            summary.add_assign(&self.chunks.summary(&end_offset, Bias::Right));
 578            if let Some(end_chunk) = self.chunks.item() {
 579                let end_ix = end_offset - self.chunks.start();
 580                summary.add_assign(&D::from_chunk(end_chunk.slice(0..end_ix)));
 581            }
 582        }
 583
 584        self.offset = end_offset;
 585        summary
 586    }
 587
 588    pub fn suffix(mut self) -> Rope {
 589        self.slice(self.rope.chunks.extent(&()))
 590    }
 591
 592    pub fn offset(&self) -> usize {
 593        self.offset
 594    }
 595}
 596
 597#[derive(Clone)]
 598pub struct Chunks<'a> {
 599    chunks: sum_tree::Cursor<'a, Chunk, usize>,
 600    range: Range<usize>,
 601    offset: usize,
 602    reversed: bool,
 603}
 604
 605impl<'a> Chunks<'a> {
 606    pub fn new(rope: &'a Rope, range: Range<usize>, reversed: bool) -> Self {
 607        let mut chunks = rope.chunks.cursor(&());
 608        let offset = if reversed {
 609            chunks.seek(&range.end, Bias::Left);
 610            range.end
 611        } else {
 612            chunks.seek(&range.start, Bias::Right);
 613            range.start
 614        };
 615        Self {
 616            chunks,
 617            range,
 618            offset,
 619            reversed,
 620        }
 621    }
 622
 623    fn offset_is_valid(&self) -> bool {
 624        if self.reversed {
 625            if self.offset <= self.range.start || self.offset > self.range.end {
 626                return false;
 627            }
 628        } else if self.offset < self.range.start || self.offset >= self.range.end {
 629            return false;
 630        }
 631
 632        true
 633    }
 634
 635    pub fn offset(&self) -> usize {
 636        self.offset
 637    }
 638
 639    pub fn seek(&mut self, mut offset: usize) {
 640        offset = offset.clamp(self.range.start, self.range.end);
 641
 642        if self.reversed {
 643            if offset > self.chunks.end() {
 644                self.chunks.seek_forward(&offset, Bias::Left);
 645            } else if offset <= *self.chunks.start() {
 646                self.chunks.seek(&offset, Bias::Left);
 647            }
 648        } else {
 649            if offset >= self.chunks.end() {
 650                self.chunks.seek_forward(&offset, Bias::Right);
 651            } else if offset < *self.chunks.start() {
 652                self.chunks.seek(&offset, Bias::Right);
 653            }
 654        };
 655
 656        self.offset = offset;
 657    }
 658
 659    pub fn set_range(&mut self, range: Range<usize>) {
 660        self.range = range.clone();
 661        self.seek(range.start);
 662    }
 663
 664    /// Moves this cursor to the start of the next line in the rope.
 665    ///
 666    /// This method advances the cursor to the beginning of the next line.
 667    /// If the cursor is already at the end of the rope, this method does nothing.
 668    /// Reversed chunks iterators are not currently supported and will panic.
 669    ///
 670    /// Returns `true` if the cursor was successfully moved to the next line start,
 671    /// or `false` if the cursor was already at the end of the rope.
 672    pub fn next_line(&mut self) -> bool {
 673        assert!(!self.reversed);
 674
 675        let mut found = false;
 676        if let Some(chunk) = self.peek() {
 677            if let Some(newline_ix) = chunk.find('\n') {
 678                self.offset += newline_ix + 1;
 679                found = self.offset <= self.range.end;
 680            } else {
 681                self.chunks
 682                    .search_forward(|summary| summary.text.lines.row > 0);
 683                self.offset = *self.chunks.start();
 684
 685                if let Some(newline_ix) = self.peek().and_then(|chunk| chunk.find('\n')) {
 686                    self.offset += newline_ix + 1;
 687                    found = self.offset <= self.range.end;
 688                } else {
 689                    self.offset = self.chunks.end();
 690                }
 691            }
 692
 693            if self.offset == self.chunks.end() {
 694                self.next();
 695            }
 696        }
 697
 698        if self.offset > self.range.end {
 699            self.offset = cmp::min(self.offset, self.range.end);
 700            self.chunks.seek(&self.offset, Bias::Right);
 701        }
 702
 703        found
 704    }
 705
 706    /// Move this cursor to the preceding position in the rope that starts a new line.
 707    /// Reversed chunks iterators are not currently supported and will panic.
 708    ///
 709    /// If this cursor is not on the start of a line, it will be moved to the start of
 710    /// its current line. Otherwise it will be moved to the start of the previous line.
 711    /// It updates the cursor's position and returns true if a previous line was found,
 712    /// or false if the cursor was already at the start of the rope.
 713    pub fn prev_line(&mut self) -> bool {
 714        assert!(!self.reversed);
 715
 716        let initial_offset = self.offset;
 717
 718        if self.offset == *self.chunks.start() {
 719            self.chunks.prev();
 720        }
 721
 722        if let Some(chunk) = self.chunks.item() {
 723            let mut end_ix = self.offset - *self.chunks.start();
 724            if chunk.text.as_bytes()[end_ix - 1] == b'\n' {
 725                end_ix -= 1;
 726            }
 727
 728            if let Some(newline_ix) = chunk.text[..end_ix].rfind('\n') {
 729                self.offset = *self.chunks.start() + newline_ix + 1;
 730                if self.offset_is_valid() {
 731                    return true;
 732                }
 733            }
 734        }
 735
 736        self.chunks
 737            .search_backward(|summary| summary.text.lines.row > 0);
 738        self.offset = *self.chunks.start();
 739        if let Some(chunk) = self.chunks.item()
 740            && let Some(newline_ix) = chunk.text.rfind('\n')
 741        {
 742            self.offset += newline_ix + 1;
 743            if self.offset_is_valid() {
 744                if self.offset == self.chunks.end() {
 745                    self.chunks.next();
 746                }
 747
 748                return true;
 749            }
 750        }
 751
 752        if !self.offset_is_valid() || self.chunks.item().is_none() {
 753            self.offset = self.range.start;
 754            self.chunks.seek(&self.offset, Bias::Right);
 755        }
 756
 757        self.offset < initial_offset && self.offset == 0
 758    }
 759
 760    pub fn peek(&self) -> Option<&'a str> {
 761        if !self.offset_is_valid() {
 762            return None;
 763        }
 764
 765        let chunk = self.chunks.item()?;
 766        let chunk_start = *self.chunks.start();
 767        let slice_range = if self.reversed {
 768            let slice_start = cmp::max(chunk_start, self.range.start) - chunk_start;
 769            let slice_end = self.offset - chunk_start;
 770            slice_start..slice_end
 771        } else {
 772            let slice_start = self.offset - chunk_start;
 773            let slice_end = cmp::min(self.chunks.end(), self.range.end) - chunk_start;
 774            slice_start..slice_end
 775        };
 776
 777        Some(&chunk.text[slice_range])
 778    }
 779
 780    pub fn lines(self) -> Lines<'a> {
 781        let reversed = self.reversed;
 782        Lines {
 783            chunks: self,
 784            current_line: String::new(),
 785            done: false,
 786            reversed,
 787        }
 788    }
 789
 790    pub fn equals_str(&self, other: &str) -> bool {
 791        let chunk = self.clone();
 792        if chunk.reversed {
 793            let mut offset = other.len();
 794            for chunk in chunk {
 795                if other[0..offset].ends_with(chunk) {
 796                    offset -= chunk.len();
 797                } else {
 798                    return false;
 799                }
 800            }
 801            if offset != 0 {
 802                return false;
 803            }
 804        } else {
 805            let mut offset = 0;
 806            for chunk in chunk {
 807                if offset >= other.len() {
 808                    return false;
 809                }
 810                if other[offset..].starts_with(chunk) {
 811                    offset += chunk.len();
 812                } else {
 813                    return false;
 814                }
 815            }
 816            if offset != other.len() {
 817                return false;
 818            }
 819        }
 820
 821        true
 822    }
 823}
 824
 825impl<'a> Iterator for Chunks<'a> {
 826    type Item = &'a str;
 827
 828    fn next(&mut self) -> Option<Self::Item> {
 829        let chunk = self.peek()?;
 830        if self.reversed {
 831            self.offset -= chunk.len();
 832            if self.offset <= *self.chunks.start() {
 833                self.chunks.prev();
 834            }
 835        } else {
 836            self.offset += chunk.len();
 837            if self.offset >= self.chunks.end() {
 838                self.chunks.next();
 839            }
 840        }
 841
 842        Some(chunk)
 843    }
 844}
 845
 846pub struct Bytes<'a> {
 847    chunks: sum_tree::Cursor<'a, Chunk, usize>,
 848    range: Range<usize>,
 849    reversed: bool,
 850}
 851
 852impl<'a> Bytes<'a> {
 853    pub fn new(rope: &'a Rope, range: Range<usize>, reversed: bool) -> Self {
 854        let mut chunks = rope.chunks.cursor(&());
 855        if reversed {
 856            chunks.seek(&range.end, Bias::Left);
 857        } else {
 858            chunks.seek(&range.start, Bias::Right);
 859        }
 860        Self {
 861            chunks,
 862            range,
 863            reversed,
 864        }
 865    }
 866
 867    pub fn peek(&self) -> Option<&'a [u8]> {
 868        let chunk = self.chunks.item()?;
 869        if self.reversed && self.range.start >= self.chunks.end() {
 870            return None;
 871        }
 872        let chunk_start = *self.chunks.start();
 873        if self.range.end <= chunk_start {
 874            return None;
 875        }
 876        let start = self.range.start.saturating_sub(chunk_start);
 877        let end = self.range.end - chunk_start;
 878        Some(&chunk.text.as_bytes()[start..chunk.text.len().min(end)])
 879    }
 880}
 881
 882impl<'a> Iterator for Bytes<'a> {
 883    type Item = &'a [u8];
 884
 885    fn next(&mut self) -> Option<Self::Item> {
 886        let result = self.peek();
 887        if result.is_some() {
 888            if self.reversed {
 889                self.chunks.prev();
 890            } else {
 891                self.chunks.next();
 892            }
 893        }
 894        result
 895    }
 896}
 897
 898impl io::Read for Bytes<'_> {
 899    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
 900        if let Some(chunk) = self.peek() {
 901            let len = cmp::min(buf.len(), chunk.len());
 902            if self.reversed {
 903                buf[..len].copy_from_slice(&chunk[chunk.len() - len..]);
 904                buf[..len].reverse();
 905                self.range.end -= len;
 906            } else {
 907                buf[..len].copy_from_slice(&chunk[..len]);
 908                self.range.start += len;
 909            }
 910
 911            if len == chunk.len() {
 912                if self.reversed {
 913                    self.chunks.prev();
 914                } else {
 915                    self.chunks.next();
 916                }
 917            }
 918            Ok(len)
 919        } else {
 920            Ok(0)
 921        }
 922    }
 923}
 924
 925pub struct Lines<'a> {
 926    chunks: Chunks<'a>,
 927    current_line: String,
 928    done: bool,
 929    reversed: bool,
 930}
 931
 932impl Lines<'_> {
 933    pub fn next(&mut self) -> Option<&str> {
 934        if self.done {
 935            return None;
 936        }
 937
 938        self.current_line.clear();
 939
 940        while let Some(chunk) = self.chunks.peek() {
 941            let chunk_lines = chunk.split('\n');
 942            if self.reversed {
 943                let mut chunk_lines = chunk_lines.rev().peekable();
 944                if let Some(chunk_line) = chunk_lines.next() {
 945                    let done = chunk_lines.peek().is_some();
 946                    if done {
 947                        self.chunks
 948                            .seek(self.chunks.offset() - chunk_line.len() - "\n".len());
 949                        if self.current_line.is_empty() {
 950                            return Some(chunk_line);
 951                        }
 952                    }
 953                    self.current_line.insert_str(0, chunk_line);
 954                    if done {
 955                        return Some(&self.current_line);
 956                    }
 957                }
 958            } else {
 959                let mut chunk_lines = chunk_lines.peekable();
 960                if let Some(chunk_line) = chunk_lines.next() {
 961                    let done = chunk_lines.peek().is_some();
 962                    if done {
 963                        self.chunks
 964                            .seek(self.chunks.offset() + chunk_line.len() + "\n".len());
 965                        if self.current_line.is_empty() {
 966                            return Some(chunk_line);
 967                        }
 968                    }
 969                    self.current_line.push_str(chunk_line);
 970                    if done {
 971                        return Some(&self.current_line);
 972                    }
 973                }
 974            }
 975
 976            self.chunks.next();
 977        }
 978
 979        self.done = true;
 980        Some(&self.current_line)
 981    }
 982
 983    pub fn seek(&mut self, offset: usize) {
 984        self.chunks.seek(offset);
 985        self.current_line.clear();
 986        self.done = false;
 987    }
 988
 989    pub fn offset(&self) -> usize {
 990        self.chunks.offset()
 991    }
 992}
 993
 994impl sum_tree::Item for Chunk {
 995    type Summary = ChunkSummary;
 996
 997    fn summary(&self, _cx: &()) -> Self::Summary {
 998        ChunkSummary {
 999            text: self.as_slice().text_summary(),
1000        }
1001    }
1002}
1003
1004#[derive(Clone, Debug, Default, Eq, PartialEq)]
1005pub struct ChunkSummary {
1006    text: TextSummary,
1007}
1008
1009impl sum_tree::Summary for ChunkSummary {
1010    type Context = ();
1011
1012    fn zero(_cx: &()) -> Self {
1013        Default::default()
1014    }
1015
1016    fn add_summary(&mut self, summary: &Self, _: &()) {
1017        self.text += &summary.text;
1018    }
1019}
1020
1021/// Summary of a string of text.
1022#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
1023pub struct TextSummary {
1024    /// Length in bytes.
1025    pub len: usize,
1026    /// Length in UTF-8.
1027    pub chars: usize,
1028    /// Length in UTF-16 code units
1029    pub len_utf16: OffsetUtf16,
1030    /// A point representing the number of lines and the length of the last line.
1031    ///
1032    /// In other words, it marks the point after the last byte in the text, (if
1033    /// EOF was a character, this would be its position).
1034    pub lines: Point,
1035    /// How many `char`s are in the first line
1036    pub first_line_chars: u32,
1037    /// How many `char`s are in the last line
1038    pub last_line_chars: u32,
1039    /// How many UTF-16 code units are in the last line
1040    pub last_line_len_utf16: u32,
1041    /// The row idx of the longest row
1042    pub longest_row: u32,
1043    /// How many `char`s are in the longest row
1044    pub longest_row_chars: u32,
1045}
1046
1047impl TextSummary {
1048    pub fn lines_utf16(&self) -> PointUtf16 {
1049        PointUtf16 {
1050            row: self.lines.row,
1051            column: self.last_line_len_utf16,
1052        }
1053    }
1054
1055    pub fn newline() -> Self {
1056        Self {
1057            len: 1,
1058            chars: 1,
1059            len_utf16: OffsetUtf16(1),
1060            first_line_chars: 0,
1061            last_line_chars: 0,
1062            last_line_len_utf16: 0,
1063            lines: Point::new(1, 0),
1064            longest_row: 0,
1065            longest_row_chars: 0,
1066        }
1067    }
1068
1069    pub fn add_newline(&mut self) {
1070        self.len += 1;
1071        self.len_utf16 += OffsetUtf16(self.len_utf16.0 + 1);
1072        self.last_line_chars = 0;
1073        self.last_line_len_utf16 = 0;
1074        self.lines += Point::new(1, 0);
1075    }
1076}
1077
1078impl<'a> From<&'a str> for TextSummary {
1079    fn from(text: &'a str) -> Self {
1080        let mut len_utf16 = OffsetUtf16(0);
1081        let mut lines = Point::new(0, 0);
1082        let mut first_line_chars = 0;
1083        let mut last_line_chars = 0;
1084        let mut last_line_len_utf16 = 0;
1085        let mut longest_row = 0;
1086        let mut longest_row_chars = 0;
1087        let mut chars = 0;
1088        for c in text.chars() {
1089            chars += 1;
1090            len_utf16.0 += c.len_utf16();
1091
1092            if c == '\n' {
1093                lines += Point::new(1, 0);
1094                last_line_len_utf16 = 0;
1095                last_line_chars = 0;
1096            } else {
1097                lines.column += c.len_utf8() as u32;
1098                last_line_len_utf16 += c.len_utf16() as u32;
1099                last_line_chars += 1;
1100            }
1101
1102            if lines.row == 0 {
1103                first_line_chars = last_line_chars;
1104            }
1105
1106            if last_line_chars > longest_row_chars {
1107                longest_row = lines.row;
1108                longest_row_chars = last_line_chars;
1109            }
1110        }
1111
1112        TextSummary {
1113            len: text.len(),
1114            chars,
1115            len_utf16,
1116            lines,
1117            first_line_chars,
1118            last_line_chars,
1119            last_line_len_utf16,
1120            longest_row,
1121            longest_row_chars,
1122        }
1123    }
1124}
1125
1126impl sum_tree::Summary for TextSummary {
1127    type Context = ();
1128
1129    fn zero(_cx: &()) -> Self {
1130        Default::default()
1131    }
1132
1133    fn add_summary(&mut self, summary: &Self, _: &Self::Context) {
1134        *self += summary;
1135    }
1136}
1137
1138impl ops::Add<Self> for TextSummary {
1139    type Output = Self;
1140
1141    fn add(mut self, rhs: Self) -> Self::Output {
1142        AddAssign::add_assign(&mut self, &rhs);
1143        self
1144    }
1145}
1146
1147impl<'a> ops::AddAssign<&'a Self> for TextSummary {
1148    fn add_assign(&mut self, other: &'a Self) {
1149        let joined_chars = self.last_line_chars + other.first_line_chars;
1150        if joined_chars > self.longest_row_chars {
1151            self.longest_row = self.lines.row;
1152            self.longest_row_chars = joined_chars;
1153        }
1154        if other.longest_row_chars > self.longest_row_chars {
1155            self.longest_row = self.lines.row + other.longest_row;
1156            self.longest_row_chars = other.longest_row_chars;
1157        }
1158
1159        if self.lines.row == 0 {
1160            self.first_line_chars += other.first_line_chars;
1161        }
1162
1163        if other.lines.row == 0 {
1164            self.last_line_chars += other.first_line_chars;
1165            self.last_line_len_utf16 += other.last_line_len_utf16;
1166        } else {
1167            self.last_line_chars = other.last_line_chars;
1168            self.last_line_len_utf16 = other.last_line_len_utf16;
1169        }
1170
1171        self.chars += other.chars;
1172        self.len += other.len;
1173        self.len_utf16 += other.len_utf16;
1174        self.lines += other.lines;
1175    }
1176}
1177
1178impl ops::AddAssign<Self> for TextSummary {
1179    fn add_assign(&mut self, other: Self) {
1180        *self += &other;
1181    }
1182}
1183
1184pub trait TextDimension:
1185    'static + Clone + Copy + Default + for<'a> Dimension<'a, ChunkSummary> + std::fmt::Debug
1186{
1187    fn from_text_summary(summary: &TextSummary) -> Self;
1188    fn from_chunk(chunk: ChunkSlice) -> Self;
1189    fn add_assign(&mut self, other: &Self);
1190}
1191
1192impl<D1: TextDimension, D2: TextDimension> TextDimension for Dimensions<D1, D2, ()> {
1193    fn from_text_summary(summary: &TextSummary) -> Self {
1194        Dimensions(
1195            D1::from_text_summary(summary),
1196            D2::from_text_summary(summary),
1197            (),
1198        )
1199    }
1200
1201    fn from_chunk(chunk: ChunkSlice) -> Self {
1202        Dimensions(D1::from_chunk(chunk), D2::from_chunk(chunk), ())
1203    }
1204
1205    fn add_assign(&mut self, other: &Self) {
1206        self.0.add_assign(&other.0);
1207        self.1.add_assign(&other.1);
1208    }
1209}
1210
1211impl<'a> sum_tree::Dimension<'a, ChunkSummary> for TextSummary {
1212    fn zero(_cx: &()) -> Self {
1213        Default::default()
1214    }
1215
1216    fn add_summary(&mut self, summary: &'a ChunkSummary, _: &()) {
1217        *self += &summary.text;
1218    }
1219}
1220
1221impl TextDimension for TextSummary {
1222    fn from_text_summary(summary: &TextSummary) -> Self {
1223        *summary
1224    }
1225
1226    fn from_chunk(chunk: ChunkSlice) -> Self {
1227        chunk.text_summary()
1228    }
1229
1230    fn add_assign(&mut self, other: &Self) {
1231        *self += other;
1232    }
1233}
1234
1235impl<'a> sum_tree::Dimension<'a, ChunkSummary> for usize {
1236    fn zero(_cx: &()) -> Self {
1237        Default::default()
1238    }
1239
1240    fn add_summary(&mut self, summary: &'a ChunkSummary, _: &()) {
1241        *self += summary.text.len;
1242    }
1243}
1244
1245impl TextDimension for usize {
1246    fn from_text_summary(summary: &TextSummary) -> Self {
1247        summary.len
1248    }
1249
1250    fn from_chunk(chunk: ChunkSlice) -> Self {
1251        chunk.len()
1252    }
1253
1254    fn add_assign(&mut self, other: &Self) {
1255        *self += other;
1256    }
1257}
1258
1259impl<'a> sum_tree::Dimension<'a, ChunkSummary> for OffsetUtf16 {
1260    fn zero(_cx: &()) -> Self {
1261        Default::default()
1262    }
1263
1264    fn add_summary(&mut self, summary: &'a ChunkSummary, _: &()) {
1265        *self += summary.text.len_utf16;
1266    }
1267}
1268
1269impl TextDimension for OffsetUtf16 {
1270    fn from_text_summary(summary: &TextSummary) -> Self {
1271        summary.len_utf16
1272    }
1273
1274    fn from_chunk(chunk: ChunkSlice) -> Self {
1275        chunk.len_utf16()
1276    }
1277
1278    fn add_assign(&mut self, other: &Self) {
1279        *self += other;
1280    }
1281}
1282
1283impl<'a> sum_tree::Dimension<'a, ChunkSummary> for Point {
1284    fn zero(_cx: &()) -> Self {
1285        Default::default()
1286    }
1287
1288    fn add_summary(&mut self, summary: &'a ChunkSummary, _: &()) {
1289        *self += summary.text.lines;
1290    }
1291}
1292
1293impl TextDimension for Point {
1294    fn from_text_summary(summary: &TextSummary) -> Self {
1295        summary.lines
1296    }
1297
1298    fn from_chunk(chunk: ChunkSlice) -> Self {
1299        chunk.lines()
1300    }
1301
1302    fn add_assign(&mut self, other: &Self) {
1303        *self += other;
1304    }
1305}
1306
1307impl<'a> sum_tree::Dimension<'a, ChunkSummary> for PointUtf16 {
1308    fn zero(_cx: &()) -> Self {
1309        Default::default()
1310    }
1311
1312    fn add_summary(&mut self, summary: &'a ChunkSummary, _: &()) {
1313        *self += summary.text.lines_utf16();
1314    }
1315}
1316
1317impl TextDimension for PointUtf16 {
1318    fn from_text_summary(summary: &TextSummary) -> Self {
1319        summary.lines_utf16()
1320    }
1321
1322    fn from_chunk(chunk: ChunkSlice) -> Self {
1323        PointUtf16 {
1324            row: chunk.lines().row,
1325            column: chunk.last_line_len_utf16(),
1326        }
1327    }
1328
1329    fn add_assign(&mut self, other: &Self) {
1330        *self += other;
1331    }
1332}
1333
1334/// A pair of text dimensions in which only the first dimension is used for comparison,
1335/// but both dimensions are updated during addition and subtraction.
1336#[derive(Clone, Copy, Debug)]
1337pub struct DimensionPair<K, V> {
1338    pub key: K,
1339    pub value: Option<V>,
1340}
1341
1342impl<K: Default, V: Default> Default for DimensionPair<K, V> {
1343    fn default() -> Self {
1344        Self {
1345            key: Default::default(),
1346            value: Some(Default::default()),
1347        }
1348    }
1349}
1350
1351impl<K, V> cmp::Ord for DimensionPair<K, V>
1352where
1353    K: cmp::Ord,
1354{
1355    fn cmp(&self, other: &Self) -> cmp::Ordering {
1356        self.key.cmp(&other.key)
1357    }
1358}
1359
1360impl<K, V> cmp::PartialOrd for DimensionPair<K, V>
1361where
1362    K: cmp::PartialOrd,
1363{
1364    fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
1365        self.key.partial_cmp(&other.key)
1366    }
1367}
1368
1369impl<K, V> cmp::PartialEq for DimensionPair<K, V>
1370where
1371    K: cmp::PartialEq,
1372{
1373    fn eq(&self, other: &Self) -> bool {
1374        self.key.eq(&other.key)
1375    }
1376}
1377
1378impl<K, V> ops::Sub for DimensionPair<K, V>
1379where
1380    K: ops::Sub<K, Output = K>,
1381    V: ops::Sub<V, Output = V>,
1382{
1383    type Output = Self;
1384
1385    fn sub(self, rhs: Self) -> Self::Output {
1386        Self {
1387            key: self.key - rhs.key,
1388            value: self.value.zip(rhs.value).map(|(a, b)| a - b),
1389        }
1390    }
1391}
1392
1393impl<K, V> cmp::Eq for DimensionPair<K, V> where K: cmp::Eq {}
1394
1395impl<'a, K, V> sum_tree::Dimension<'a, ChunkSummary> for DimensionPair<K, V>
1396where
1397    K: sum_tree::Dimension<'a, ChunkSummary>,
1398    V: sum_tree::Dimension<'a, ChunkSummary>,
1399{
1400    fn zero(_cx: &()) -> Self {
1401        Self {
1402            key: K::zero(_cx),
1403            value: Some(V::zero(_cx)),
1404        }
1405    }
1406
1407    fn add_summary(&mut self, summary: &'a ChunkSummary, _cx: &()) {
1408        self.key.add_summary(summary, _cx);
1409        if let Some(value) = &mut self.value {
1410            value.add_summary(summary, _cx);
1411        }
1412    }
1413}
1414
1415impl<K, V> TextDimension for DimensionPair<K, V>
1416where
1417    K: TextDimension,
1418    V: TextDimension,
1419{
1420    fn add_assign(&mut self, other: &Self) {
1421        self.key.add_assign(&other.key);
1422        if let Some(value) = &mut self.value {
1423            if let Some(other_value) = other.value.as_ref() {
1424                value.add_assign(other_value);
1425            } else {
1426                self.value.take();
1427            }
1428        }
1429    }
1430
1431    fn from_chunk(chunk: ChunkSlice) -> Self {
1432        Self {
1433            key: K::from_chunk(chunk),
1434            value: Some(V::from_chunk(chunk)),
1435        }
1436    }
1437
1438    fn from_text_summary(summary: &TextSummary) -> Self {
1439        Self {
1440            key: K::from_text_summary(summary),
1441            value: Some(V::from_text_summary(summary)),
1442        }
1443    }
1444}
1445
1446#[cfg(test)]
1447mod tests {
1448    use super::*;
1449    use Bias::{Left, Right};
1450    use rand::prelude::*;
1451    use std::{cmp::Ordering, env, io::Read};
1452    use util::RandomCharIter;
1453
1454    #[ctor::ctor]
1455    fn init_logger() {
1456        zlog::init_test();
1457    }
1458
1459    #[test]
1460    fn test_all_4_byte_chars() {
1461        let mut rope = Rope::new();
1462        let text = "🏀".repeat(256);
1463        rope.push(&text);
1464        assert_eq!(rope.text(), text);
1465    }
1466
1467    #[test]
1468    fn test_clip() {
1469        let rope = Rope::from("🧘");
1470
1471        assert_eq!(rope.clip_offset(1, Bias::Left), 0);
1472        assert_eq!(rope.clip_offset(1, Bias::Right), 4);
1473        assert_eq!(rope.clip_offset(5, Bias::Right), 4);
1474
1475        assert_eq!(
1476            rope.clip_point(Point::new(0, 1), Bias::Left),
1477            Point::new(0, 0)
1478        );
1479        assert_eq!(
1480            rope.clip_point(Point::new(0, 1), Bias::Right),
1481            Point::new(0, 4)
1482        );
1483        assert_eq!(
1484            rope.clip_point(Point::new(0, 5), Bias::Right),
1485            Point::new(0, 4)
1486        );
1487
1488        assert_eq!(
1489            rope.clip_point_utf16(Unclipped(PointUtf16::new(0, 1)), Bias::Left),
1490            PointUtf16::new(0, 0)
1491        );
1492        assert_eq!(
1493            rope.clip_point_utf16(Unclipped(PointUtf16::new(0, 1)), Bias::Right),
1494            PointUtf16::new(0, 2)
1495        );
1496        assert_eq!(
1497            rope.clip_point_utf16(Unclipped(PointUtf16::new(0, 3)), Bias::Right),
1498            PointUtf16::new(0, 2)
1499        );
1500
1501        assert_eq!(
1502            rope.clip_offset_utf16(OffsetUtf16(1), Bias::Left),
1503            OffsetUtf16(0)
1504        );
1505        assert_eq!(
1506            rope.clip_offset_utf16(OffsetUtf16(1), Bias::Right),
1507            OffsetUtf16(2)
1508        );
1509        assert_eq!(
1510            rope.clip_offset_utf16(OffsetUtf16(3), Bias::Right),
1511            OffsetUtf16(2)
1512        );
1513    }
1514
1515    #[test]
1516    fn test_prev_next_line() {
1517        let rope = Rope::from("abc\ndef\nghi\njkl");
1518
1519        let mut chunks = rope.chunks();
1520        assert_eq!(chunks.peek().unwrap().chars().next().unwrap(), 'a');
1521
1522        assert!(chunks.next_line());
1523        assert_eq!(chunks.peek().unwrap().chars().next().unwrap(), 'd');
1524
1525        assert!(chunks.next_line());
1526        assert_eq!(chunks.peek().unwrap().chars().next().unwrap(), 'g');
1527
1528        assert!(chunks.next_line());
1529        assert_eq!(chunks.peek().unwrap().chars().next().unwrap(), 'j');
1530
1531        assert!(!chunks.next_line());
1532        assert_eq!(chunks.peek(), None);
1533
1534        assert!(chunks.prev_line());
1535        assert_eq!(chunks.peek().unwrap().chars().next().unwrap(), 'j');
1536
1537        assert!(chunks.prev_line());
1538        assert_eq!(chunks.peek().unwrap().chars().next().unwrap(), 'g');
1539
1540        assert!(chunks.prev_line());
1541        assert_eq!(chunks.peek().unwrap().chars().next().unwrap(), 'd');
1542
1543        assert!(chunks.prev_line());
1544        assert_eq!(chunks.peek().unwrap().chars().next().unwrap(), 'a');
1545
1546        assert!(!chunks.prev_line());
1547        assert_eq!(chunks.peek().unwrap().chars().next().unwrap(), 'a');
1548
1549        // Only return true when the cursor has moved to the start of a line
1550        let mut chunks = rope.chunks_in_range(5..7);
1551        chunks.seek(6);
1552        assert!(!chunks.prev_line());
1553        assert_eq!(chunks.peek().unwrap().chars().next().unwrap(), 'e');
1554
1555        assert!(!chunks.next_line());
1556        assert_eq!(chunks.peek(), None);
1557    }
1558
1559    #[test]
1560    fn test_lines() {
1561        let rope = Rope::from("abc\ndefg\nhi");
1562        let mut lines = rope.chunks().lines();
1563        assert_eq!(lines.next(), Some("abc"));
1564        assert_eq!(lines.next(), Some("defg"));
1565        assert_eq!(lines.next(), Some("hi"));
1566        assert_eq!(lines.next(), None);
1567
1568        let rope = Rope::from("abc\ndefg\nhi\n");
1569        let mut lines = rope.chunks().lines();
1570        assert_eq!(lines.next(), Some("abc"));
1571        assert_eq!(lines.next(), Some("defg"));
1572        assert_eq!(lines.next(), Some("hi"));
1573        assert_eq!(lines.next(), Some(""));
1574        assert_eq!(lines.next(), None);
1575
1576        let rope = Rope::from("abc\ndefg\nhi");
1577        let mut lines = rope.reversed_chunks_in_range(0..rope.len()).lines();
1578        assert_eq!(lines.next(), Some("hi"));
1579        assert_eq!(lines.next(), Some("defg"));
1580        assert_eq!(lines.next(), Some("abc"));
1581        assert_eq!(lines.next(), None);
1582
1583        let rope = Rope::from("abc\ndefg\nhi\n");
1584        let mut lines = rope.reversed_chunks_in_range(0..rope.len()).lines();
1585        assert_eq!(lines.next(), Some(""));
1586        assert_eq!(lines.next(), Some("hi"));
1587        assert_eq!(lines.next(), Some("defg"));
1588        assert_eq!(lines.next(), Some("abc"));
1589        assert_eq!(lines.next(), None);
1590
1591        let rope = Rope::from("abc\nlonger line test\nhi");
1592        let mut lines = rope.chunks().lines();
1593        assert_eq!(lines.next(), Some("abc"));
1594        assert_eq!(lines.next(), Some("longer line test"));
1595        assert_eq!(lines.next(), Some("hi"));
1596        assert_eq!(lines.next(), None);
1597
1598        let rope = Rope::from("abc\nlonger line test\nhi");
1599        let mut lines = rope.reversed_chunks_in_range(0..rope.len()).lines();
1600        assert_eq!(lines.next(), Some("hi"));
1601        assert_eq!(lines.next(), Some("longer line test"));
1602        assert_eq!(lines.next(), Some("abc"));
1603        assert_eq!(lines.next(), None);
1604    }
1605
1606    #[gpui::test(iterations = 100)]
1607    fn test_random_rope(mut rng: StdRng) {
1608        let operations = env::var("OPERATIONS")
1609            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
1610            .unwrap_or(10);
1611
1612        let mut expected = String::new();
1613        let mut actual = Rope::new();
1614        for _ in 0..operations {
1615            let end_ix = clip_offset(&expected, rng.random_range(0..=expected.len()), Right);
1616            let start_ix = clip_offset(&expected, rng.random_range(0..=end_ix), Left);
1617            let len = rng.random_range(0..=64);
1618            let new_text: String = RandomCharIter::new(&mut rng).take(len).collect();
1619
1620            let mut new_actual = Rope::new();
1621            let mut cursor = actual.cursor(0);
1622            new_actual.append(cursor.slice(start_ix));
1623            new_actual.push(&new_text);
1624            cursor.seek_forward(end_ix);
1625            new_actual.append(cursor.suffix());
1626            actual = new_actual;
1627
1628            expected.replace_range(start_ix..end_ix, &new_text);
1629
1630            assert_eq!(actual.text(), expected);
1631            log::info!("text: {:?}", expected);
1632
1633            for _ in 0..5 {
1634                let end_ix = clip_offset(&expected, rng.random_range(0..=expected.len()), Right);
1635                let start_ix = clip_offset(&expected, rng.random_range(0..=end_ix), Left);
1636
1637                let actual_text = actual.chunks_in_range(start_ix..end_ix).collect::<String>();
1638                assert_eq!(actual_text, &expected[start_ix..end_ix]);
1639
1640                let mut actual_text = String::new();
1641                actual
1642                    .bytes_in_range(start_ix..end_ix)
1643                    .read_to_string(&mut actual_text)
1644                    .unwrap();
1645                assert_eq!(actual_text, &expected[start_ix..end_ix]);
1646
1647                assert_eq!(
1648                    actual
1649                        .reversed_chunks_in_range(start_ix..end_ix)
1650                        .collect::<Vec<&str>>()
1651                        .into_iter()
1652                        .rev()
1653                        .collect::<String>(),
1654                    &expected[start_ix..end_ix]
1655                );
1656
1657                let mut expected_line_starts: Vec<_> = expected[start_ix..end_ix]
1658                    .match_indices('\n')
1659                    .map(|(index, _)| start_ix + index + 1)
1660                    .collect();
1661
1662                let mut chunks = actual.chunks_in_range(start_ix..end_ix);
1663
1664                let mut actual_line_starts = Vec::new();
1665                while chunks.next_line() {
1666                    actual_line_starts.push(chunks.offset());
1667                }
1668                assert_eq!(
1669                    actual_line_starts,
1670                    expected_line_starts,
1671                    "actual line starts != expected line starts when using next_line() for {:?} ({:?})",
1672                    &expected[start_ix..end_ix],
1673                    start_ix..end_ix
1674                );
1675
1676                if start_ix < end_ix
1677                    && (start_ix == 0 || expected.as_bytes()[start_ix - 1] == b'\n')
1678                {
1679                    expected_line_starts.insert(0, start_ix);
1680                }
1681                // Remove the last index if it starts at the end of the range.
1682                if expected_line_starts.last() == Some(&end_ix) {
1683                    expected_line_starts.pop();
1684                }
1685
1686                let mut actual_line_starts = Vec::new();
1687                while chunks.prev_line() {
1688                    actual_line_starts.push(chunks.offset());
1689                }
1690                actual_line_starts.reverse();
1691                assert_eq!(
1692                    actual_line_starts,
1693                    expected_line_starts,
1694                    "actual line starts != expected line starts when using prev_line() for {:?} ({:?})",
1695                    &expected[start_ix..end_ix],
1696                    start_ix..end_ix
1697                );
1698
1699                // Check that next_line/prev_line work correctly from random positions
1700                let mut offset = rng.random_range(start_ix..=end_ix);
1701                while !expected.is_char_boundary(offset) {
1702                    offset -= 1;
1703                }
1704                chunks.seek(offset);
1705
1706                for _ in 0..5 {
1707                    if rng.random() {
1708                        let expected_next_line_start = expected[offset..end_ix]
1709                            .find('\n')
1710                            .map(|newline_ix| offset + newline_ix + 1);
1711
1712                        let moved = chunks.next_line();
1713                        assert_eq!(
1714                            moved,
1715                            expected_next_line_start.is_some(),
1716                            "unexpected result from next_line after seeking to {} in range {:?} ({:?})",
1717                            offset,
1718                            start_ix..end_ix,
1719                            &expected[start_ix..end_ix]
1720                        );
1721                        if let Some(expected_next_line_start) = expected_next_line_start {
1722                            assert_eq!(
1723                                chunks.offset(),
1724                                expected_next_line_start,
1725                                "invalid position after seeking to {} in range {:?} ({:?})",
1726                                offset,
1727                                start_ix..end_ix,
1728                                &expected[start_ix..end_ix]
1729                            );
1730                        } else {
1731                            assert_eq!(
1732                                chunks.offset(),
1733                                end_ix,
1734                                "invalid position after seeking to {} in range {:?} ({:?})",
1735                                offset,
1736                                start_ix..end_ix,
1737                                &expected[start_ix..end_ix]
1738                            );
1739                        }
1740                    } else {
1741                        let search_end = if offset > 0 && expected.as_bytes()[offset - 1] == b'\n' {
1742                            offset - 1
1743                        } else {
1744                            offset
1745                        };
1746
1747                        let expected_prev_line_start = expected[..search_end]
1748                            .rfind('\n')
1749                            .and_then(|newline_ix| {
1750                                let line_start_ix = newline_ix + 1;
1751                                if line_start_ix >= start_ix {
1752                                    Some(line_start_ix)
1753                                } else {
1754                                    None
1755                                }
1756                            })
1757                            .or({
1758                                if offset > 0 && start_ix == 0 {
1759                                    Some(0)
1760                                } else {
1761                                    None
1762                                }
1763                            });
1764
1765                        let moved = chunks.prev_line();
1766                        assert_eq!(
1767                            moved,
1768                            expected_prev_line_start.is_some(),
1769                            "unexpected result from prev_line after seeking to {} in range {:?} ({:?})",
1770                            offset,
1771                            start_ix..end_ix,
1772                            &expected[start_ix..end_ix]
1773                        );
1774                        if let Some(expected_prev_line_start) = expected_prev_line_start {
1775                            assert_eq!(
1776                                chunks.offset(),
1777                                expected_prev_line_start,
1778                                "invalid position after seeking to {} in range {:?} ({:?})",
1779                                offset,
1780                                start_ix..end_ix,
1781                                &expected[start_ix..end_ix]
1782                            );
1783                        } else {
1784                            assert_eq!(
1785                                chunks.offset(),
1786                                start_ix,
1787                                "invalid position after seeking to {} in range {:?} ({:?})",
1788                                offset,
1789                                start_ix..end_ix,
1790                                &expected[start_ix..end_ix]
1791                            );
1792                        }
1793                    }
1794
1795                    assert!((start_ix..=end_ix).contains(&chunks.offset()));
1796                    if rng.random() {
1797                        offset = rng.random_range(start_ix..=end_ix);
1798                        while !expected.is_char_boundary(offset) {
1799                            offset -= 1;
1800                        }
1801                        chunks.seek(offset);
1802                    } else {
1803                        chunks.next();
1804                        offset = chunks.offset();
1805                        assert!((start_ix..=end_ix).contains(&chunks.offset()));
1806                    }
1807                }
1808            }
1809
1810            let mut offset_utf16 = OffsetUtf16(0);
1811            let mut point = Point::new(0, 0);
1812            let mut point_utf16 = PointUtf16::new(0, 0);
1813            for (ix, ch) in expected.char_indices().chain(Some((expected.len(), '\0'))) {
1814                assert_eq!(actual.offset_to_point(ix), point, "offset_to_point({})", ix);
1815                assert_eq!(
1816                    actual.offset_to_point_utf16(ix),
1817                    point_utf16,
1818                    "offset_to_point_utf16({})",
1819                    ix
1820                );
1821                assert_eq!(
1822                    actual.point_to_offset(point),
1823                    ix,
1824                    "point_to_offset({:?})",
1825                    point
1826                );
1827                assert_eq!(
1828                    actual.point_utf16_to_offset(point_utf16),
1829                    ix,
1830                    "point_utf16_to_offset({:?})",
1831                    point_utf16
1832                );
1833                assert_eq!(
1834                    actual.offset_to_offset_utf16(ix),
1835                    offset_utf16,
1836                    "offset_to_offset_utf16({:?})",
1837                    ix
1838                );
1839                assert_eq!(
1840                    actual.offset_utf16_to_offset(offset_utf16),
1841                    ix,
1842                    "offset_utf16_to_offset({:?})",
1843                    offset_utf16
1844                );
1845                if ch == '\n' {
1846                    point += Point::new(1, 0);
1847                    point_utf16 += PointUtf16::new(1, 0);
1848                } else {
1849                    point.column += ch.len_utf8() as u32;
1850                    point_utf16.column += ch.len_utf16() as u32;
1851                }
1852                offset_utf16.0 += ch.len_utf16();
1853            }
1854
1855            let mut offset_utf16 = OffsetUtf16(0);
1856            let mut point_utf16 = Unclipped(PointUtf16::zero());
1857            for unit in expected.encode_utf16() {
1858                let left_offset = actual.clip_offset_utf16(offset_utf16, Bias::Left);
1859                let right_offset = actual.clip_offset_utf16(offset_utf16, Bias::Right);
1860                assert!(right_offset >= left_offset);
1861                // Ensure translating UTF-16 offsets to UTF-8 offsets doesn't panic.
1862                actual.offset_utf16_to_offset(left_offset);
1863                actual.offset_utf16_to_offset(right_offset);
1864
1865                let left_point = actual.clip_point_utf16(point_utf16, Bias::Left);
1866                let right_point = actual.clip_point_utf16(point_utf16, Bias::Right);
1867                assert!(right_point >= left_point);
1868                // Ensure translating valid UTF-16 points to offsets doesn't panic.
1869                actual.point_utf16_to_offset(left_point);
1870                actual.point_utf16_to_offset(right_point);
1871
1872                offset_utf16.0 += 1;
1873                if unit == b'\n' as u16 {
1874                    point_utf16.0 += PointUtf16::new(1, 0);
1875                } else {
1876                    point_utf16.0 += PointUtf16::new(0, 1);
1877                }
1878            }
1879
1880            for _ in 0..5 {
1881                let end_ix = clip_offset(&expected, rng.random_range(0..=expected.len()), Right);
1882                let start_ix = clip_offset(&expected, rng.random_range(0..=end_ix), Left);
1883                assert_eq!(
1884                    actual.cursor(start_ix).summary::<TextSummary>(end_ix),
1885                    TextSummary::from(&expected[start_ix..end_ix])
1886                );
1887            }
1888
1889            let mut expected_longest_rows = Vec::new();
1890            let mut longest_line_len = -1_isize;
1891            for (row, line) in expected.split('\n').enumerate() {
1892                let row = row as u32;
1893                assert_eq!(
1894                    actual.line_len(row),
1895                    line.len() as u32,
1896                    "invalid line len for row {}",
1897                    row
1898                );
1899
1900                let line_char_count = line.chars().count() as isize;
1901                match line_char_count.cmp(&longest_line_len) {
1902                    Ordering::Less => {}
1903                    Ordering::Equal => expected_longest_rows.push(row),
1904                    Ordering::Greater => {
1905                        longest_line_len = line_char_count;
1906                        expected_longest_rows.clear();
1907                        expected_longest_rows.push(row);
1908                    }
1909                }
1910            }
1911
1912            let longest_row = actual.summary().longest_row;
1913            assert!(
1914                expected_longest_rows.contains(&longest_row),
1915                "incorrect longest row {}. expected {:?} with length {}",
1916                longest_row,
1917                expected_longest_rows,
1918                longest_line_len,
1919            );
1920        }
1921    }
1922
1923    #[test]
1924    fn test_chunks_equals_str() {
1925        let text = "This is a multi-chunk\n& multi-line test string!";
1926        let rope = Rope::from(text);
1927        for start in 0..text.len() {
1928            for end in start..text.len() {
1929                let range = start..end;
1930                let correct_substring = &text[start..end];
1931
1932                // Test that correct range returns true
1933                assert!(
1934                    rope.chunks_in_range(range.clone())
1935                        .equals_str(correct_substring)
1936                );
1937                assert!(
1938                    rope.reversed_chunks_in_range(range.clone())
1939                        .equals_str(correct_substring)
1940                );
1941
1942                // Test that all other ranges return false (unless they happen to match)
1943                for other_start in 0..text.len() {
1944                    for other_end in other_start..text.len() {
1945                        if other_start == start && other_end == end {
1946                            continue;
1947                        }
1948                        let other_substring = &text[other_start..other_end];
1949
1950                        // Only assert false if the substrings are actually different
1951                        if other_substring == correct_substring {
1952                            continue;
1953                        }
1954                        assert!(
1955                            !rope
1956                                .chunks_in_range(range.clone())
1957                                .equals_str(other_substring)
1958                        );
1959                        assert!(
1960                            !rope
1961                                .reversed_chunks_in_range(range.clone())
1962                                .equals_str(other_substring)
1963                        );
1964                    }
1965                }
1966            }
1967        }
1968
1969        let rope = Rope::from("");
1970        assert!(rope.chunks_in_range(0..0).equals_str(""));
1971        assert!(rope.reversed_chunks_in_range(0..0).equals_str(""));
1972        assert!(!rope.chunks_in_range(0..0).equals_str("foo"));
1973        assert!(!rope.reversed_chunks_in_range(0..0).equals_str("foo"));
1974    }
1975
1976    fn clip_offset(text: &str, mut offset: usize, bias: Bias) -> usize {
1977        while !text.is_char_boundary(offset) {
1978            match bias {
1979                Bias::Left => offset -= 1,
1980                Bias::Right => offset += 1,
1981            }
1982        }
1983        offset
1984    }
1985
1986    impl Rope {
1987        fn text(&self) -> String {
1988            let mut text = String::new();
1989            for chunk in self.chunks.cursor::<()>(&()) {
1990                text.push_str(&chunk.text);
1991            }
1992            text
1993        }
1994    }
1995}