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
 455impl<'a> From<&'a str> for Rope {
 456    fn from(text: &'a str) -> Self {
 457        let mut rope = Self::new();
 458        rope.push(text);
 459        rope
 460    }
 461}
 462
 463impl<'a> FromIterator<&'a str> for Rope {
 464    fn from_iter<T: IntoIterator<Item = &'a str>>(iter: T) -> Self {
 465        let mut rope = Rope::new();
 466        for chunk in iter {
 467            rope.push(chunk);
 468        }
 469        rope
 470    }
 471}
 472
 473impl From<String> for Rope {
 474    fn from(text: String) -> Self {
 475        Rope::from(text.as_str())
 476    }
 477}
 478
 479impl fmt::Display for Rope {
 480    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 481        for chunk in self.chunks() {
 482            write!(f, "{}", chunk)?;
 483        }
 484        Ok(())
 485    }
 486}
 487
 488impl fmt::Debug for Rope {
 489    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 490        use std::fmt::Write as _;
 491
 492        write!(f, "\"")?;
 493        let mut format_string = String::new();
 494        for chunk in self.chunks() {
 495            write!(&mut format_string, "{:?}", chunk)?;
 496            write!(f, "{}", &format_string[1..format_string.len() - 1])?;
 497            format_string.clear();
 498        }
 499        write!(f, "\"")?;
 500        Ok(())
 501    }
 502}
 503
 504pub struct Cursor<'a> {
 505    rope: &'a Rope,
 506    chunks: sum_tree::Cursor<'a, Chunk, usize>,
 507    offset: usize,
 508}
 509
 510impl<'a> Cursor<'a> {
 511    pub fn new(rope: &'a Rope, offset: usize) -> Self {
 512        let mut chunks = rope.chunks.cursor(&());
 513        chunks.seek(&offset, Bias::Right);
 514        Self {
 515            rope,
 516            chunks,
 517            offset,
 518        }
 519    }
 520
 521    pub fn seek_forward(&mut self, end_offset: usize) {
 522        debug_assert!(end_offset >= self.offset);
 523
 524        self.chunks.seek_forward(&end_offset, Bias::Right);
 525        self.offset = end_offset;
 526    }
 527
 528    pub fn slice(&mut self, end_offset: usize) -> Rope {
 529        debug_assert!(
 530            end_offset >= self.offset,
 531            "cannot slice backwards from {} to {}",
 532            self.offset,
 533            end_offset
 534        );
 535
 536        let mut slice = Rope::new();
 537        if let Some(start_chunk) = self.chunks.item() {
 538            let start_ix = self.offset - self.chunks.start();
 539            let end_ix = cmp::min(end_offset, self.chunks.end()) - self.chunks.start();
 540            slice.push_chunk(start_chunk.slice(start_ix..end_ix));
 541        }
 542
 543        if end_offset > self.chunks.end() {
 544            self.chunks.next();
 545            slice.append(Rope {
 546                chunks: self.chunks.slice(&end_offset, Bias::Right),
 547            });
 548            if let Some(end_chunk) = self.chunks.item() {
 549                let end_ix = end_offset - self.chunks.start();
 550                slice.push_chunk(end_chunk.slice(0..end_ix));
 551            }
 552        }
 553
 554        self.offset = end_offset;
 555        slice
 556    }
 557
 558    pub fn summary<D: TextDimension>(&mut self, end_offset: usize) -> D {
 559        debug_assert!(end_offset >= self.offset);
 560
 561        let mut summary = D::zero(&());
 562        if let Some(start_chunk) = self.chunks.item() {
 563            let start_ix = self.offset - self.chunks.start();
 564            let end_ix = cmp::min(end_offset, self.chunks.end()) - self.chunks.start();
 565            summary.add_assign(&D::from_chunk(start_chunk.slice(start_ix..end_ix)));
 566        }
 567
 568        if end_offset > self.chunks.end() {
 569            self.chunks.next();
 570            summary.add_assign(&self.chunks.summary(&end_offset, Bias::Right));
 571            if let Some(end_chunk) = self.chunks.item() {
 572                let end_ix = end_offset - self.chunks.start();
 573                summary.add_assign(&D::from_chunk(end_chunk.slice(0..end_ix)));
 574            }
 575        }
 576
 577        self.offset = end_offset;
 578        summary
 579    }
 580
 581    pub fn suffix(mut self) -> Rope {
 582        self.slice(self.rope.chunks.extent(&()))
 583    }
 584
 585    pub fn offset(&self) -> usize {
 586        self.offset
 587    }
 588}
 589
 590#[derive(Clone)]
 591pub struct Chunks<'a> {
 592    chunks: sum_tree::Cursor<'a, Chunk, usize>,
 593    range: Range<usize>,
 594    offset: usize,
 595    reversed: bool,
 596}
 597
 598impl<'a> Chunks<'a> {
 599    pub fn new(rope: &'a Rope, range: Range<usize>, reversed: bool) -> Self {
 600        let mut chunks = rope.chunks.cursor(&());
 601        let offset = if reversed {
 602            chunks.seek(&range.end, Bias::Left);
 603            range.end
 604        } else {
 605            chunks.seek(&range.start, Bias::Right);
 606            range.start
 607        };
 608        Self {
 609            chunks,
 610            range,
 611            offset,
 612            reversed,
 613        }
 614    }
 615
 616    fn offset_is_valid(&self) -> bool {
 617        if self.reversed {
 618            if self.offset <= self.range.start || self.offset > self.range.end {
 619                return false;
 620            }
 621        } else if self.offset < self.range.start || self.offset >= self.range.end {
 622            return false;
 623        }
 624
 625        true
 626    }
 627
 628    pub fn offset(&self) -> usize {
 629        self.offset
 630    }
 631
 632    pub fn seek(&mut self, mut offset: usize) {
 633        offset = offset.clamp(self.range.start, self.range.end);
 634
 635        let bias = if self.reversed {
 636            Bias::Left
 637        } else {
 638            Bias::Right
 639        };
 640
 641        if offset >= self.chunks.end() {
 642            self.chunks.seek_forward(&offset, bias);
 643        } else {
 644            self.chunks.seek(&offset, bias);
 645        }
 646
 647        self.offset = offset;
 648    }
 649
 650    pub fn set_range(&mut self, range: Range<usize>) {
 651        self.range = range.clone();
 652        self.seek(range.start);
 653    }
 654
 655    /// Moves this cursor to the start of the next line in the rope.
 656    ///
 657    /// This method advances the cursor to the beginning of the next line.
 658    /// If the cursor is already at the end of the rope, this method does nothing.
 659    /// Reversed chunks iterators are not currently supported and will panic.
 660    ///
 661    /// Returns `true` if the cursor was successfully moved to the next line start,
 662    /// or `false` if the cursor was already at the end of the rope.
 663    pub fn next_line(&mut self) -> bool {
 664        assert!(!self.reversed);
 665
 666        let mut found = false;
 667        if let Some(chunk) = self.peek() {
 668            if let Some(newline_ix) = chunk.find('\n') {
 669                self.offset += newline_ix + 1;
 670                found = self.offset <= self.range.end;
 671            } else {
 672                self.chunks
 673                    .search_forward(|summary| summary.text.lines.row > 0);
 674                self.offset = *self.chunks.start();
 675
 676                if let Some(newline_ix) = self.peek().and_then(|chunk| chunk.find('\n')) {
 677                    self.offset += newline_ix + 1;
 678                    found = self.offset <= self.range.end;
 679                } else {
 680                    self.offset = self.chunks.end();
 681                }
 682            }
 683
 684            if self.offset == self.chunks.end() {
 685                self.next();
 686            }
 687        }
 688
 689        if self.offset > self.range.end {
 690            self.offset = cmp::min(self.offset, self.range.end);
 691            self.chunks.seek(&self.offset, Bias::Right);
 692        }
 693
 694        found
 695    }
 696
 697    /// Move this cursor to the preceding position in the rope that starts a new line.
 698    /// Reversed chunks iterators are not currently supported and will panic.
 699    ///
 700    /// If this cursor is not on the start of a line, it will be moved to the start of
 701    /// its current line. Otherwise it will be moved to the start of the previous line.
 702    /// It updates the cursor's position and returns true if a previous line was found,
 703    /// or false if the cursor was already at the start of the rope.
 704    pub fn prev_line(&mut self) -> bool {
 705        assert!(!self.reversed);
 706
 707        let initial_offset = self.offset;
 708
 709        if self.offset == *self.chunks.start() {
 710            self.chunks.prev();
 711        }
 712
 713        if let Some(chunk) = self.chunks.item() {
 714            let mut end_ix = self.offset - *self.chunks.start();
 715            if chunk.text.as_bytes()[end_ix - 1] == b'\n' {
 716                end_ix -= 1;
 717            }
 718
 719            if let Some(newline_ix) = chunk.text[..end_ix].rfind('\n') {
 720                self.offset = *self.chunks.start() + newline_ix + 1;
 721                if self.offset_is_valid() {
 722                    return true;
 723                }
 724            }
 725        }
 726
 727        self.chunks
 728            .search_backward(|summary| summary.text.lines.row > 0);
 729        self.offset = *self.chunks.start();
 730        if let Some(chunk) = self.chunks.item() {
 731            if let Some(newline_ix) = chunk.text.rfind('\n') {
 732                self.offset += newline_ix + 1;
 733                if self.offset_is_valid() {
 734                    if self.offset == self.chunks.end() {
 735                        self.chunks.next();
 736                    }
 737
 738                    return true;
 739                }
 740            }
 741        }
 742
 743        if !self.offset_is_valid() || self.chunks.item().is_none() {
 744            self.offset = self.range.start;
 745            self.chunks.seek(&self.offset, Bias::Right);
 746        }
 747
 748        self.offset < initial_offset && self.offset == 0
 749    }
 750
 751    pub fn peek(&self) -> Option<&'a str> {
 752        if !self.offset_is_valid() {
 753            return None;
 754        }
 755
 756        let chunk = self.chunks.item()?;
 757        let chunk_start = *self.chunks.start();
 758        let slice_range = if self.reversed {
 759            let slice_start = cmp::max(chunk_start, self.range.start) - chunk_start;
 760            let slice_end = self.offset - chunk_start;
 761            slice_start..slice_end
 762        } else {
 763            let slice_start = self.offset - chunk_start;
 764            let slice_end = cmp::min(self.chunks.end(), self.range.end) - chunk_start;
 765            slice_start..slice_end
 766        };
 767
 768        Some(&chunk.text[slice_range])
 769    }
 770
 771    pub fn lines(self) -> Lines<'a> {
 772        let reversed = self.reversed;
 773        Lines {
 774            chunks: self,
 775            current_line: String::new(),
 776            done: false,
 777            reversed,
 778        }
 779    }
 780
 781    pub fn equals_str(&self, other: &str) -> bool {
 782        let chunk = self.clone();
 783        if chunk.reversed {
 784            let mut offset = other.len();
 785            for chunk in chunk {
 786                if other[0..offset].ends_with(chunk) {
 787                    offset -= chunk.len();
 788                } else {
 789                    return false;
 790                }
 791            }
 792            if offset != 0 {
 793                return false;
 794            }
 795        } else {
 796            let mut offset = 0;
 797            for chunk in chunk {
 798                if offset >= other.len() {
 799                    return false;
 800                }
 801                if other[offset..].starts_with(chunk) {
 802                    offset += chunk.len();
 803                } else {
 804                    return false;
 805                }
 806            }
 807            if offset != other.len() {
 808                return false;
 809            }
 810        }
 811
 812        return true;
 813    }
 814}
 815
 816impl<'a> Iterator for Chunks<'a> {
 817    type Item = &'a str;
 818
 819    fn next(&mut self) -> Option<Self::Item> {
 820        let chunk = self.peek()?;
 821        if self.reversed {
 822            self.offset -= chunk.len();
 823            if self.offset <= *self.chunks.start() {
 824                self.chunks.prev();
 825            }
 826        } else {
 827            self.offset += chunk.len();
 828            if self.offset >= self.chunks.end() {
 829                self.chunks.next();
 830            }
 831        }
 832
 833        Some(chunk)
 834    }
 835}
 836
 837pub struct Bytes<'a> {
 838    chunks: sum_tree::Cursor<'a, Chunk, usize>,
 839    range: Range<usize>,
 840    reversed: bool,
 841}
 842
 843impl<'a> Bytes<'a> {
 844    pub fn new(rope: &'a Rope, range: Range<usize>, reversed: bool) -> Self {
 845        let mut chunks = rope.chunks.cursor(&());
 846        if reversed {
 847            chunks.seek(&range.end, Bias::Left);
 848        } else {
 849            chunks.seek(&range.start, Bias::Right);
 850        }
 851        Self {
 852            chunks,
 853            range,
 854            reversed,
 855        }
 856    }
 857
 858    pub fn peek(&self) -> Option<&'a [u8]> {
 859        let chunk = self.chunks.item()?;
 860        if self.reversed && self.range.start >= self.chunks.end() {
 861            return None;
 862        }
 863        let chunk_start = *self.chunks.start();
 864        if self.range.end <= chunk_start {
 865            return None;
 866        }
 867        let start = self.range.start.saturating_sub(chunk_start);
 868        let end = self.range.end - chunk_start;
 869        Some(&chunk.text.as_bytes()[start..chunk.text.len().min(end)])
 870    }
 871}
 872
 873impl<'a> Iterator for Bytes<'a> {
 874    type Item = &'a [u8];
 875
 876    fn next(&mut self) -> Option<Self::Item> {
 877        let result = self.peek();
 878        if result.is_some() {
 879            if self.reversed {
 880                self.chunks.prev();
 881            } else {
 882                self.chunks.next();
 883            }
 884        }
 885        result
 886    }
 887}
 888
 889impl io::Read for Bytes<'_> {
 890    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
 891        if let Some(chunk) = self.peek() {
 892            let len = cmp::min(buf.len(), chunk.len());
 893            if self.reversed {
 894                buf[..len].copy_from_slice(&chunk[chunk.len() - len..]);
 895                buf[..len].reverse();
 896                self.range.end -= len;
 897            } else {
 898                buf[..len].copy_from_slice(&chunk[..len]);
 899                self.range.start += len;
 900            }
 901
 902            if len == chunk.len() {
 903                if self.reversed {
 904                    self.chunks.prev();
 905                } else {
 906                    self.chunks.next();
 907                }
 908            }
 909            Ok(len)
 910        } else {
 911            Ok(0)
 912        }
 913    }
 914}
 915
 916pub struct Lines<'a> {
 917    chunks: Chunks<'a>,
 918    current_line: String,
 919    done: bool,
 920    reversed: bool,
 921}
 922
 923impl Lines<'_> {
 924    pub fn next(&mut self) -> Option<&str> {
 925        if self.done {
 926            return None;
 927        }
 928
 929        self.current_line.clear();
 930
 931        while let Some(chunk) = self.chunks.peek() {
 932            let lines = chunk.split('\n');
 933            if self.reversed {
 934                let mut lines = lines.rev().peekable();
 935                while let Some(line) = lines.next() {
 936                    self.current_line.insert_str(0, line);
 937                    if lines.peek().is_some() {
 938                        self.chunks
 939                            .seek(self.chunks.offset() - line.len() - "\n".len());
 940                        return Some(&self.current_line);
 941                    }
 942                }
 943            } else {
 944                let mut lines = lines.peekable();
 945                while let Some(line) = lines.next() {
 946                    self.current_line.push_str(line);
 947                    if lines.peek().is_some() {
 948                        self.chunks
 949                            .seek(self.chunks.offset() + line.len() + "\n".len());
 950                        return Some(&self.current_line);
 951                    }
 952                }
 953            }
 954
 955            self.chunks.next();
 956        }
 957
 958        self.done = true;
 959        Some(&self.current_line)
 960    }
 961
 962    pub fn seek(&mut self, offset: usize) {
 963        self.chunks.seek(offset);
 964        self.current_line.clear();
 965        self.done = false;
 966    }
 967
 968    pub fn offset(&self) -> usize {
 969        self.chunks.offset()
 970    }
 971}
 972
 973impl sum_tree::Item for Chunk {
 974    type Summary = ChunkSummary;
 975
 976    fn summary(&self, _cx: &()) -> Self::Summary {
 977        ChunkSummary {
 978            text: self.as_slice().text_summary(),
 979        }
 980    }
 981}
 982
 983#[derive(Clone, Debug, Default, Eq, PartialEq)]
 984pub struct ChunkSummary {
 985    text: TextSummary,
 986}
 987
 988impl sum_tree::Summary for ChunkSummary {
 989    type Context = ();
 990
 991    fn zero(_cx: &()) -> Self {
 992        Default::default()
 993    }
 994
 995    fn add_summary(&mut self, summary: &Self, _: &()) {
 996        self.text += &summary.text;
 997    }
 998}
 999
1000/// Summary of a string of text.
1001#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
1002pub struct TextSummary {
1003    /// Length in bytes.
1004    pub len: usize,
1005    /// Length in UTF-8.
1006    pub chars: usize,
1007    /// Length in UTF-16 code units
1008    pub len_utf16: OffsetUtf16,
1009    /// A point representing the number of lines and the length of the last line.
1010    ///
1011    /// In other words, it marks the point after the last byte in the text, (if
1012    /// EOF was a character, this would be its position).
1013    pub lines: Point,
1014    /// How many `char`s are in the first line
1015    pub first_line_chars: u32,
1016    /// How many `char`s are in the last line
1017    pub last_line_chars: u32,
1018    /// How many UTF-16 code units are in the last line
1019    pub last_line_len_utf16: u32,
1020    /// The row idx of the longest row
1021    pub longest_row: u32,
1022    /// How many `char`s are in the longest row
1023    pub longest_row_chars: u32,
1024}
1025
1026impl TextSummary {
1027    pub fn lines_utf16(&self) -> PointUtf16 {
1028        PointUtf16 {
1029            row: self.lines.row,
1030            column: self.last_line_len_utf16,
1031        }
1032    }
1033
1034    pub fn newline() -> Self {
1035        Self {
1036            len: 1,
1037            chars: 1,
1038            len_utf16: OffsetUtf16(1),
1039            first_line_chars: 0,
1040            last_line_chars: 0,
1041            last_line_len_utf16: 0,
1042            lines: Point::new(1, 0),
1043            longest_row: 0,
1044            longest_row_chars: 0,
1045        }
1046    }
1047
1048    pub fn add_newline(&mut self) {
1049        self.len += 1;
1050        self.len_utf16 += OffsetUtf16(self.len_utf16.0 + 1);
1051        self.last_line_chars = 0;
1052        self.last_line_len_utf16 = 0;
1053        self.lines += Point::new(1, 0);
1054    }
1055}
1056
1057impl<'a> From<&'a str> for TextSummary {
1058    fn from(text: &'a str) -> Self {
1059        let mut len_utf16 = OffsetUtf16(0);
1060        let mut lines = Point::new(0, 0);
1061        let mut first_line_chars = 0;
1062        let mut last_line_chars = 0;
1063        let mut last_line_len_utf16 = 0;
1064        let mut longest_row = 0;
1065        let mut longest_row_chars = 0;
1066        let mut chars = 0;
1067        for c in text.chars() {
1068            chars += 1;
1069            len_utf16.0 += c.len_utf16();
1070
1071            if c == '\n' {
1072                lines += Point::new(1, 0);
1073                last_line_len_utf16 = 0;
1074                last_line_chars = 0;
1075            } else {
1076                lines.column += c.len_utf8() as u32;
1077                last_line_len_utf16 += c.len_utf16() as u32;
1078                last_line_chars += 1;
1079            }
1080
1081            if lines.row == 0 {
1082                first_line_chars = last_line_chars;
1083            }
1084
1085            if last_line_chars > longest_row_chars {
1086                longest_row = lines.row;
1087                longest_row_chars = last_line_chars;
1088            }
1089        }
1090
1091        TextSummary {
1092            len: text.len(),
1093            chars,
1094            len_utf16,
1095            lines,
1096            first_line_chars,
1097            last_line_chars,
1098            last_line_len_utf16,
1099            longest_row,
1100            longest_row_chars,
1101        }
1102    }
1103}
1104
1105impl sum_tree::Summary for TextSummary {
1106    type Context = ();
1107
1108    fn zero(_cx: &()) -> Self {
1109        Default::default()
1110    }
1111
1112    fn add_summary(&mut self, summary: &Self, _: &Self::Context) {
1113        *self += summary;
1114    }
1115}
1116
1117impl ops::Add<Self> for TextSummary {
1118    type Output = Self;
1119
1120    fn add(mut self, rhs: Self) -> Self::Output {
1121        AddAssign::add_assign(&mut self, &rhs);
1122        self
1123    }
1124}
1125
1126impl<'a> ops::AddAssign<&'a Self> for TextSummary {
1127    fn add_assign(&mut self, other: &'a Self) {
1128        let joined_chars = self.last_line_chars + other.first_line_chars;
1129        if joined_chars > self.longest_row_chars {
1130            self.longest_row = self.lines.row;
1131            self.longest_row_chars = joined_chars;
1132        }
1133        if other.longest_row_chars > self.longest_row_chars {
1134            self.longest_row = self.lines.row + other.longest_row;
1135            self.longest_row_chars = other.longest_row_chars;
1136        }
1137
1138        if self.lines.row == 0 {
1139            self.first_line_chars += other.first_line_chars;
1140        }
1141
1142        if other.lines.row == 0 {
1143            self.last_line_chars += other.first_line_chars;
1144            self.last_line_len_utf16 += other.last_line_len_utf16;
1145        } else {
1146            self.last_line_chars = other.last_line_chars;
1147            self.last_line_len_utf16 = other.last_line_len_utf16;
1148        }
1149
1150        self.chars += other.chars;
1151        self.len += other.len;
1152        self.len_utf16 += other.len_utf16;
1153        self.lines += other.lines;
1154    }
1155}
1156
1157impl ops::AddAssign<Self> for TextSummary {
1158    fn add_assign(&mut self, other: Self) {
1159        *self += &other;
1160    }
1161}
1162
1163pub trait TextDimension:
1164    'static + Clone + Copy + Default + for<'a> Dimension<'a, ChunkSummary> + std::fmt::Debug
1165{
1166    fn from_text_summary(summary: &TextSummary) -> Self;
1167    fn from_chunk(chunk: ChunkSlice) -> Self;
1168    fn add_assign(&mut self, other: &Self);
1169}
1170
1171impl<D1: TextDimension, D2: TextDimension> TextDimension for (D1, D2) {
1172    fn from_text_summary(summary: &TextSummary) -> Self {
1173        (
1174            D1::from_text_summary(summary),
1175            D2::from_text_summary(summary),
1176        )
1177    }
1178
1179    fn from_chunk(chunk: ChunkSlice) -> Self {
1180        (D1::from_chunk(chunk), D2::from_chunk(chunk))
1181    }
1182
1183    fn add_assign(&mut self, other: &Self) {
1184        self.0.add_assign(&other.0);
1185        self.1.add_assign(&other.1);
1186    }
1187}
1188
1189impl<'a> sum_tree::Dimension<'a, ChunkSummary> for TextSummary {
1190    fn zero(_cx: &()) -> Self {
1191        Default::default()
1192    }
1193
1194    fn add_summary(&mut self, summary: &'a ChunkSummary, _: &()) {
1195        *self += &summary.text;
1196    }
1197}
1198
1199impl TextDimension for TextSummary {
1200    fn from_text_summary(summary: &TextSummary) -> Self {
1201        *summary
1202    }
1203
1204    fn from_chunk(chunk: ChunkSlice) -> Self {
1205        chunk.text_summary()
1206    }
1207
1208    fn add_assign(&mut self, other: &Self) {
1209        *self += other;
1210    }
1211}
1212
1213impl<'a> sum_tree::Dimension<'a, ChunkSummary> for usize {
1214    fn zero(_cx: &()) -> Self {
1215        Default::default()
1216    }
1217
1218    fn add_summary(&mut self, summary: &'a ChunkSummary, _: &()) {
1219        *self += summary.text.len;
1220    }
1221}
1222
1223impl TextDimension for usize {
1224    fn from_text_summary(summary: &TextSummary) -> Self {
1225        summary.len
1226    }
1227
1228    fn from_chunk(chunk: ChunkSlice) -> Self {
1229        chunk.len()
1230    }
1231
1232    fn add_assign(&mut self, other: &Self) {
1233        *self += other;
1234    }
1235}
1236
1237impl<'a> sum_tree::Dimension<'a, ChunkSummary> for OffsetUtf16 {
1238    fn zero(_cx: &()) -> Self {
1239        Default::default()
1240    }
1241
1242    fn add_summary(&mut self, summary: &'a ChunkSummary, _: &()) {
1243        *self += summary.text.len_utf16;
1244    }
1245}
1246
1247impl TextDimension for OffsetUtf16 {
1248    fn from_text_summary(summary: &TextSummary) -> Self {
1249        summary.len_utf16
1250    }
1251
1252    fn from_chunk(chunk: ChunkSlice) -> Self {
1253        chunk.len_utf16()
1254    }
1255
1256    fn add_assign(&mut self, other: &Self) {
1257        *self += other;
1258    }
1259}
1260
1261impl<'a> sum_tree::Dimension<'a, ChunkSummary> for Point {
1262    fn zero(_cx: &()) -> Self {
1263        Default::default()
1264    }
1265
1266    fn add_summary(&mut self, summary: &'a ChunkSummary, _: &()) {
1267        *self += summary.text.lines;
1268    }
1269}
1270
1271impl TextDimension for Point {
1272    fn from_text_summary(summary: &TextSummary) -> Self {
1273        summary.lines
1274    }
1275
1276    fn from_chunk(chunk: ChunkSlice) -> Self {
1277        chunk.lines()
1278    }
1279
1280    fn add_assign(&mut self, other: &Self) {
1281        *self += other;
1282    }
1283}
1284
1285impl<'a> sum_tree::Dimension<'a, ChunkSummary> for PointUtf16 {
1286    fn zero(_cx: &()) -> Self {
1287        Default::default()
1288    }
1289
1290    fn add_summary(&mut self, summary: &'a ChunkSummary, _: &()) {
1291        *self += summary.text.lines_utf16();
1292    }
1293}
1294
1295impl TextDimension for PointUtf16 {
1296    fn from_text_summary(summary: &TextSummary) -> Self {
1297        summary.lines_utf16()
1298    }
1299
1300    fn from_chunk(chunk: ChunkSlice) -> Self {
1301        PointUtf16 {
1302            row: chunk.lines().row,
1303            column: chunk.last_line_len_utf16(),
1304        }
1305    }
1306
1307    fn add_assign(&mut self, other: &Self) {
1308        *self += other;
1309    }
1310}
1311
1312/// A pair of text dimensions in which only the first dimension is used for comparison,
1313/// but both dimensions are updated during addition and subtraction.
1314#[derive(Clone, Copy, Debug)]
1315pub struct DimensionPair<K, V> {
1316    pub key: K,
1317    pub value: Option<V>,
1318}
1319
1320impl<K: Default, V: Default> Default for DimensionPair<K, V> {
1321    fn default() -> Self {
1322        Self {
1323            key: Default::default(),
1324            value: Some(Default::default()),
1325        }
1326    }
1327}
1328
1329impl<K, V> cmp::Ord for DimensionPair<K, V>
1330where
1331    K: cmp::Ord,
1332{
1333    fn cmp(&self, other: &Self) -> cmp::Ordering {
1334        self.key.cmp(&other.key)
1335    }
1336}
1337
1338impl<K, V> cmp::PartialOrd for DimensionPair<K, V>
1339where
1340    K: cmp::PartialOrd,
1341{
1342    fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
1343        self.key.partial_cmp(&other.key)
1344    }
1345}
1346
1347impl<K, V> cmp::PartialEq for DimensionPair<K, V>
1348where
1349    K: cmp::PartialEq,
1350{
1351    fn eq(&self, other: &Self) -> bool {
1352        self.key.eq(&other.key)
1353    }
1354}
1355
1356impl<K, V> ops::Sub for DimensionPair<K, V>
1357where
1358    K: ops::Sub<K, Output = K>,
1359    V: ops::Sub<V, Output = V>,
1360{
1361    type Output = Self;
1362
1363    fn sub(self, rhs: Self) -> Self::Output {
1364        Self {
1365            key: self.key - rhs.key,
1366            value: self.value.zip(rhs.value).map(|(a, b)| a - b),
1367        }
1368    }
1369}
1370
1371impl<K, V> cmp::Eq for DimensionPair<K, V> where K: cmp::Eq {}
1372
1373impl<'a, K, V> sum_tree::Dimension<'a, ChunkSummary> for DimensionPair<K, V>
1374where
1375    K: sum_tree::Dimension<'a, ChunkSummary>,
1376    V: sum_tree::Dimension<'a, ChunkSummary>,
1377{
1378    fn zero(_cx: &()) -> Self {
1379        Self {
1380            key: K::zero(_cx),
1381            value: Some(V::zero(_cx)),
1382        }
1383    }
1384
1385    fn add_summary(&mut self, summary: &'a ChunkSummary, _cx: &()) {
1386        self.key.add_summary(summary, _cx);
1387        if let Some(value) = &mut self.value {
1388            value.add_summary(summary, _cx);
1389        }
1390    }
1391}
1392
1393impl<K, V> TextDimension for DimensionPair<K, V>
1394where
1395    K: TextDimension,
1396    V: TextDimension,
1397{
1398    fn add_assign(&mut self, other: &Self) {
1399        self.key.add_assign(&other.key);
1400        if let Some(value) = &mut self.value {
1401            if let Some(other_value) = other.value.as_ref() {
1402                value.add_assign(other_value);
1403            } else {
1404                self.value.take();
1405            }
1406        }
1407    }
1408
1409    fn from_chunk(chunk: ChunkSlice) -> Self {
1410        Self {
1411            key: K::from_chunk(chunk),
1412            value: Some(V::from_chunk(chunk)),
1413        }
1414    }
1415
1416    fn from_text_summary(summary: &TextSummary) -> Self {
1417        Self {
1418            key: K::from_text_summary(summary),
1419            value: Some(V::from_text_summary(summary)),
1420        }
1421    }
1422}
1423
1424#[cfg(test)]
1425mod tests {
1426    use super::*;
1427    use Bias::{Left, Right};
1428    use rand::prelude::*;
1429    use std::{cmp::Ordering, env, io::Read};
1430    use util::RandomCharIter;
1431
1432    #[ctor::ctor]
1433    fn init_logger() {
1434        zlog::init_test();
1435    }
1436
1437    #[test]
1438    fn test_all_4_byte_chars() {
1439        let mut rope = Rope::new();
1440        let text = "🏀".repeat(256);
1441        rope.push(&text);
1442        assert_eq!(rope.text(), text);
1443    }
1444
1445    #[test]
1446    fn test_clip() {
1447        let rope = Rope::from("🧘");
1448
1449        assert_eq!(rope.clip_offset(1, Bias::Left), 0);
1450        assert_eq!(rope.clip_offset(1, Bias::Right), 4);
1451        assert_eq!(rope.clip_offset(5, Bias::Right), 4);
1452
1453        assert_eq!(
1454            rope.clip_point(Point::new(0, 1), Bias::Left),
1455            Point::new(0, 0)
1456        );
1457        assert_eq!(
1458            rope.clip_point(Point::new(0, 1), Bias::Right),
1459            Point::new(0, 4)
1460        );
1461        assert_eq!(
1462            rope.clip_point(Point::new(0, 5), Bias::Right),
1463            Point::new(0, 4)
1464        );
1465
1466        assert_eq!(
1467            rope.clip_point_utf16(Unclipped(PointUtf16::new(0, 1)), Bias::Left),
1468            PointUtf16::new(0, 0)
1469        );
1470        assert_eq!(
1471            rope.clip_point_utf16(Unclipped(PointUtf16::new(0, 1)), Bias::Right),
1472            PointUtf16::new(0, 2)
1473        );
1474        assert_eq!(
1475            rope.clip_point_utf16(Unclipped(PointUtf16::new(0, 3)), Bias::Right),
1476            PointUtf16::new(0, 2)
1477        );
1478
1479        assert_eq!(
1480            rope.clip_offset_utf16(OffsetUtf16(1), Bias::Left),
1481            OffsetUtf16(0)
1482        );
1483        assert_eq!(
1484            rope.clip_offset_utf16(OffsetUtf16(1), Bias::Right),
1485            OffsetUtf16(2)
1486        );
1487        assert_eq!(
1488            rope.clip_offset_utf16(OffsetUtf16(3), Bias::Right),
1489            OffsetUtf16(2)
1490        );
1491    }
1492
1493    #[test]
1494    fn test_prev_next_line() {
1495        let rope = Rope::from("abc\ndef\nghi\njkl");
1496
1497        let mut chunks = rope.chunks();
1498        assert_eq!(chunks.peek().unwrap().chars().next().unwrap(), 'a');
1499
1500        assert!(chunks.next_line());
1501        assert_eq!(chunks.peek().unwrap().chars().next().unwrap(), 'd');
1502
1503        assert!(chunks.next_line());
1504        assert_eq!(chunks.peek().unwrap().chars().next().unwrap(), 'g');
1505
1506        assert!(chunks.next_line());
1507        assert_eq!(chunks.peek().unwrap().chars().next().unwrap(), 'j');
1508
1509        assert!(!chunks.next_line());
1510        assert_eq!(chunks.peek(), None);
1511
1512        assert!(chunks.prev_line());
1513        assert_eq!(chunks.peek().unwrap().chars().next().unwrap(), 'j');
1514
1515        assert!(chunks.prev_line());
1516        assert_eq!(chunks.peek().unwrap().chars().next().unwrap(), 'g');
1517
1518        assert!(chunks.prev_line());
1519        assert_eq!(chunks.peek().unwrap().chars().next().unwrap(), 'd');
1520
1521        assert!(chunks.prev_line());
1522        assert_eq!(chunks.peek().unwrap().chars().next().unwrap(), 'a');
1523
1524        assert!(!chunks.prev_line());
1525        assert_eq!(chunks.peek().unwrap().chars().next().unwrap(), 'a');
1526
1527        // Only return true when the cursor has moved to the start of a line
1528        let mut chunks = rope.chunks_in_range(5..7);
1529        chunks.seek(6);
1530        assert!(!chunks.prev_line());
1531        assert_eq!(chunks.peek().unwrap().chars().next().unwrap(), 'e');
1532
1533        assert!(!chunks.next_line());
1534        assert_eq!(chunks.peek(), None);
1535    }
1536
1537    #[test]
1538    fn test_lines() {
1539        let rope = Rope::from("abc\ndefg\nhi");
1540        let mut lines = rope.chunks().lines();
1541        assert_eq!(lines.next(), Some("abc"));
1542        assert_eq!(lines.next(), Some("defg"));
1543        assert_eq!(lines.next(), Some("hi"));
1544        assert_eq!(lines.next(), None);
1545
1546        let rope = Rope::from("abc\ndefg\nhi\n");
1547        let mut lines = rope.chunks().lines();
1548        assert_eq!(lines.next(), Some("abc"));
1549        assert_eq!(lines.next(), Some("defg"));
1550        assert_eq!(lines.next(), Some("hi"));
1551        assert_eq!(lines.next(), Some(""));
1552        assert_eq!(lines.next(), None);
1553
1554        let rope = Rope::from("abc\ndefg\nhi");
1555        let mut lines = rope.reversed_chunks_in_range(0..rope.len()).lines();
1556        assert_eq!(lines.next(), Some("hi"));
1557        assert_eq!(lines.next(), Some("defg"));
1558        assert_eq!(lines.next(), Some("abc"));
1559        assert_eq!(lines.next(), None);
1560
1561        let rope = Rope::from("abc\ndefg\nhi\n");
1562        let mut lines = rope.reversed_chunks_in_range(0..rope.len()).lines();
1563        assert_eq!(lines.next(), Some(""));
1564        assert_eq!(lines.next(), Some("hi"));
1565        assert_eq!(lines.next(), Some("defg"));
1566        assert_eq!(lines.next(), Some("abc"));
1567        assert_eq!(lines.next(), None);
1568    }
1569
1570    #[gpui::test(iterations = 100)]
1571    fn test_random_rope(mut rng: StdRng) {
1572        let operations = env::var("OPERATIONS")
1573            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
1574            .unwrap_or(10);
1575
1576        let mut expected = String::new();
1577        let mut actual = Rope::new();
1578        for _ in 0..operations {
1579            let end_ix = clip_offset(&expected, rng.gen_range(0..=expected.len()), Right);
1580            let start_ix = clip_offset(&expected, rng.gen_range(0..=end_ix), Left);
1581            let len = rng.gen_range(0..=64);
1582            let new_text: String = RandomCharIter::new(&mut rng).take(len).collect();
1583
1584            let mut new_actual = Rope::new();
1585            let mut cursor = actual.cursor(0);
1586            new_actual.append(cursor.slice(start_ix));
1587            new_actual.push(&new_text);
1588            cursor.seek_forward(end_ix);
1589            new_actual.append(cursor.suffix());
1590            actual = new_actual;
1591
1592            expected.replace_range(start_ix..end_ix, &new_text);
1593
1594            assert_eq!(actual.text(), expected);
1595            log::info!("text: {:?}", expected);
1596
1597            for _ in 0..5 {
1598                let end_ix = clip_offset(&expected, rng.gen_range(0..=expected.len()), Right);
1599                let start_ix = clip_offset(&expected, rng.gen_range(0..=end_ix), Left);
1600
1601                let actual_text = actual.chunks_in_range(start_ix..end_ix).collect::<String>();
1602                assert_eq!(actual_text, &expected[start_ix..end_ix]);
1603
1604                let mut actual_text = String::new();
1605                actual
1606                    .bytes_in_range(start_ix..end_ix)
1607                    .read_to_string(&mut actual_text)
1608                    .unwrap();
1609                assert_eq!(actual_text, &expected[start_ix..end_ix]);
1610
1611                assert_eq!(
1612                    actual
1613                        .reversed_chunks_in_range(start_ix..end_ix)
1614                        .collect::<Vec<&str>>()
1615                        .into_iter()
1616                        .rev()
1617                        .collect::<String>(),
1618                    &expected[start_ix..end_ix]
1619                );
1620
1621                let mut expected_line_starts: Vec<_> = expected[start_ix..end_ix]
1622                    .match_indices('\n')
1623                    .map(|(index, _)| start_ix + index + 1)
1624                    .collect();
1625
1626                let mut chunks = actual.chunks_in_range(start_ix..end_ix);
1627
1628                let mut actual_line_starts = Vec::new();
1629                while chunks.next_line() {
1630                    actual_line_starts.push(chunks.offset());
1631                }
1632                assert_eq!(
1633                    actual_line_starts,
1634                    expected_line_starts,
1635                    "actual line starts != expected line starts when using next_line() for {:?} ({:?})",
1636                    &expected[start_ix..end_ix],
1637                    start_ix..end_ix
1638                );
1639
1640                if start_ix < end_ix
1641                    && (start_ix == 0 || expected.as_bytes()[start_ix - 1] == b'\n')
1642                {
1643                    expected_line_starts.insert(0, start_ix);
1644                }
1645                // Remove the last index if it starts at the end of the range.
1646                if expected_line_starts.last() == Some(&end_ix) {
1647                    expected_line_starts.pop();
1648                }
1649
1650                let mut actual_line_starts = Vec::new();
1651                while chunks.prev_line() {
1652                    actual_line_starts.push(chunks.offset());
1653                }
1654                actual_line_starts.reverse();
1655                assert_eq!(
1656                    actual_line_starts,
1657                    expected_line_starts,
1658                    "actual line starts != expected line starts when using prev_line() for {:?} ({:?})",
1659                    &expected[start_ix..end_ix],
1660                    start_ix..end_ix
1661                );
1662
1663                // Check that next_line/prev_line work correctly from random positions
1664                let mut offset = rng.gen_range(start_ix..=end_ix);
1665                while !expected.is_char_boundary(offset) {
1666                    offset -= 1;
1667                }
1668                chunks.seek(offset);
1669
1670                for _ in 0..5 {
1671                    if rng.r#gen() {
1672                        let expected_next_line_start = expected[offset..end_ix]
1673                            .find('\n')
1674                            .map(|newline_ix| offset + newline_ix + 1);
1675
1676                        let moved = chunks.next_line();
1677                        assert_eq!(
1678                            moved,
1679                            expected_next_line_start.is_some(),
1680                            "unexpected result from next_line after seeking to {} in range {:?} ({:?})",
1681                            offset,
1682                            start_ix..end_ix,
1683                            &expected[start_ix..end_ix]
1684                        );
1685                        if let Some(expected_next_line_start) = expected_next_line_start {
1686                            assert_eq!(
1687                                chunks.offset(),
1688                                expected_next_line_start,
1689                                "invalid position after seeking to {} in range {:?} ({:?})",
1690                                offset,
1691                                start_ix..end_ix,
1692                                &expected[start_ix..end_ix]
1693                            );
1694                        } else {
1695                            assert_eq!(
1696                                chunks.offset(),
1697                                end_ix,
1698                                "invalid position after seeking to {} in range {:?} ({:?})",
1699                                offset,
1700                                start_ix..end_ix,
1701                                &expected[start_ix..end_ix]
1702                            );
1703                        }
1704                    } else {
1705                        let search_end = if offset > 0 && expected.as_bytes()[offset - 1] == b'\n' {
1706                            offset - 1
1707                        } else {
1708                            offset
1709                        };
1710
1711                        let expected_prev_line_start = expected[..search_end]
1712                            .rfind('\n')
1713                            .and_then(|newline_ix| {
1714                                let line_start_ix = newline_ix + 1;
1715                                if line_start_ix >= start_ix {
1716                                    Some(line_start_ix)
1717                                } else {
1718                                    None
1719                                }
1720                            })
1721                            .or({
1722                                if offset > 0 && start_ix == 0 {
1723                                    Some(0)
1724                                } else {
1725                                    None
1726                                }
1727                            });
1728
1729                        let moved = chunks.prev_line();
1730                        assert_eq!(
1731                            moved,
1732                            expected_prev_line_start.is_some(),
1733                            "unexpected result from prev_line after seeking to {} in range {:?} ({:?})",
1734                            offset,
1735                            start_ix..end_ix,
1736                            &expected[start_ix..end_ix]
1737                        );
1738                        if let Some(expected_prev_line_start) = expected_prev_line_start {
1739                            assert_eq!(
1740                                chunks.offset(),
1741                                expected_prev_line_start,
1742                                "invalid position after seeking to {} in range {:?} ({:?})",
1743                                offset,
1744                                start_ix..end_ix,
1745                                &expected[start_ix..end_ix]
1746                            );
1747                        } else {
1748                            assert_eq!(
1749                                chunks.offset(),
1750                                start_ix,
1751                                "invalid position after seeking to {} in range {:?} ({:?})",
1752                                offset,
1753                                start_ix..end_ix,
1754                                &expected[start_ix..end_ix]
1755                            );
1756                        }
1757                    }
1758
1759                    assert!((start_ix..=end_ix).contains(&chunks.offset()));
1760                    if rng.r#gen() {
1761                        offset = rng.gen_range(start_ix..=end_ix);
1762                        while !expected.is_char_boundary(offset) {
1763                            offset -= 1;
1764                        }
1765                        chunks.seek(offset);
1766                    } else {
1767                        chunks.next();
1768                        offset = chunks.offset();
1769                        assert!((start_ix..=end_ix).contains(&chunks.offset()));
1770                    }
1771                }
1772            }
1773
1774            let mut offset_utf16 = OffsetUtf16(0);
1775            let mut point = Point::new(0, 0);
1776            let mut point_utf16 = PointUtf16::new(0, 0);
1777            for (ix, ch) in expected.char_indices().chain(Some((expected.len(), '\0'))) {
1778                assert_eq!(actual.offset_to_point(ix), point, "offset_to_point({})", ix);
1779                assert_eq!(
1780                    actual.offset_to_point_utf16(ix),
1781                    point_utf16,
1782                    "offset_to_point_utf16({})",
1783                    ix
1784                );
1785                assert_eq!(
1786                    actual.point_to_offset(point),
1787                    ix,
1788                    "point_to_offset({:?})",
1789                    point
1790                );
1791                assert_eq!(
1792                    actual.point_utf16_to_offset(point_utf16),
1793                    ix,
1794                    "point_utf16_to_offset({:?})",
1795                    point_utf16
1796                );
1797                assert_eq!(
1798                    actual.offset_to_offset_utf16(ix),
1799                    offset_utf16,
1800                    "offset_to_offset_utf16({:?})",
1801                    ix
1802                );
1803                assert_eq!(
1804                    actual.offset_utf16_to_offset(offset_utf16),
1805                    ix,
1806                    "offset_utf16_to_offset({:?})",
1807                    offset_utf16
1808                );
1809                if ch == '\n' {
1810                    point += Point::new(1, 0);
1811                    point_utf16 += PointUtf16::new(1, 0);
1812                } else {
1813                    point.column += ch.len_utf8() as u32;
1814                    point_utf16.column += ch.len_utf16() as u32;
1815                }
1816                offset_utf16.0 += ch.len_utf16();
1817            }
1818
1819            let mut offset_utf16 = OffsetUtf16(0);
1820            let mut point_utf16 = Unclipped(PointUtf16::zero());
1821            for unit in expected.encode_utf16() {
1822                let left_offset = actual.clip_offset_utf16(offset_utf16, Bias::Left);
1823                let right_offset = actual.clip_offset_utf16(offset_utf16, Bias::Right);
1824                assert!(right_offset >= left_offset);
1825                // Ensure translating UTF-16 offsets to UTF-8 offsets doesn't panic.
1826                actual.offset_utf16_to_offset(left_offset);
1827                actual.offset_utf16_to_offset(right_offset);
1828
1829                let left_point = actual.clip_point_utf16(point_utf16, Bias::Left);
1830                let right_point = actual.clip_point_utf16(point_utf16, Bias::Right);
1831                assert!(right_point >= left_point);
1832                // Ensure translating valid UTF-16 points to offsets doesn't panic.
1833                actual.point_utf16_to_offset(left_point);
1834                actual.point_utf16_to_offset(right_point);
1835
1836                offset_utf16.0 += 1;
1837                if unit == b'\n' as u16 {
1838                    point_utf16.0 += PointUtf16::new(1, 0);
1839                } else {
1840                    point_utf16.0 += PointUtf16::new(0, 1);
1841                }
1842            }
1843
1844            for _ in 0..5 {
1845                let end_ix = clip_offset(&expected, rng.gen_range(0..=expected.len()), Right);
1846                let start_ix = clip_offset(&expected, rng.gen_range(0..=end_ix), Left);
1847                assert_eq!(
1848                    actual.cursor(start_ix).summary::<TextSummary>(end_ix),
1849                    TextSummary::from(&expected[start_ix..end_ix])
1850                );
1851            }
1852
1853            let mut expected_longest_rows = Vec::new();
1854            let mut longest_line_len = -1_isize;
1855            for (row, line) in expected.split('\n').enumerate() {
1856                let row = row as u32;
1857                assert_eq!(
1858                    actual.line_len(row),
1859                    line.len() as u32,
1860                    "invalid line len for row {}",
1861                    row
1862                );
1863
1864                let line_char_count = line.chars().count() as isize;
1865                match line_char_count.cmp(&longest_line_len) {
1866                    Ordering::Less => {}
1867                    Ordering::Equal => expected_longest_rows.push(row),
1868                    Ordering::Greater => {
1869                        longest_line_len = line_char_count;
1870                        expected_longest_rows.clear();
1871                        expected_longest_rows.push(row);
1872                    }
1873                }
1874            }
1875
1876            let longest_row = actual.summary().longest_row;
1877            assert!(
1878                expected_longest_rows.contains(&longest_row),
1879                "incorrect longest row {}. expected {:?} with length {}",
1880                longest_row,
1881                expected_longest_rows,
1882                longest_line_len,
1883            );
1884        }
1885    }
1886
1887    #[test]
1888    fn test_chunks_equals_str() {
1889        let text = "This is a multi-chunk\n& multi-line test string!";
1890        let rope = Rope::from(text);
1891        for start in 0..text.len() {
1892            for end in start..text.len() {
1893                let range = start..end;
1894                let correct_substring = &text[start..end];
1895
1896                // Test that correct range returns true
1897                assert!(
1898                    rope.chunks_in_range(range.clone())
1899                        .equals_str(correct_substring)
1900                );
1901                assert!(
1902                    rope.reversed_chunks_in_range(range.clone())
1903                        .equals_str(correct_substring)
1904                );
1905
1906                // Test that all other ranges return false (unless they happen to match)
1907                for other_start in 0..text.len() {
1908                    for other_end in other_start..text.len() {
1909                        if other_start == start && other_end == end {
1910                            continue;
1911                        }
1912                        let other_substring = &text[other_start..other_end];
1913
1914                        // Only assert false if the substrings are actually different
1915                        if other_substring == correct_substring {
1916                            continue;
1917                        }
1918                        assert!(
1919                            !rope
1920                                .chunks_in_range(range.clone())
1921                                .equals_str(other_substring)
1922                        );
1923                        assert!(
1924                            !rope
1925                                .reversed_chunks_in_range(range.clone())
1926                                .equals_str(other_substring)
1927                        );
1928                    }
1929                }
1930            }
1931        }
1932
1933        let rope = Rope::from("");
1934        assert!(rope.chunks_in_range(0..0).equals_str(""));
1935        assert!(rope.reversed_chunks_in_range(0..0).equals_str(""));
1936        assert!(!rope.chunks_in_range(0..0).equals_str("foo"));
1937        assert!(!rope.reversed_chunks_in_range(0..0).equals_str("foo"));
1938    }
1939
1940    fn clip_offset(text: &str, mut offset: usize, bias: Bias) -> usize {
1941        while !text.is_char_boundary(offset) {
1942            match bias {
1943                Bias::Left => offset -= 1,
1944                Bias::Right => offset += 1,
1945            }
1946        }
1947        offset
1948    }
1949
1950    impl Rope {
1951        fn text(&self) -> String {
1952            let mut text = String::new();
1953            for chunk in self.chunks.cursor::<()>(&()) {
1954                text.push_str(&chunk.text);
1955            }
1956            text
1957        }
1958    }
1959}