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