rope.rs

   1mod offset_utf16;
   2mod point;
   3mod point_utf16;
   4mod unclipped;
   5
   6use arrayvec::ArrayString;
   7use bromberg_sl2::HashMatrix;
   8use smallvec::SmallVec;
   9use std::{
  10    cmp, fmt, io, mem,
  11    ops::{AddAssign, Range},
  12    str,
  13};
  14use sum_tree::{Bias, Dimension, SumTree};
  15use util::debug_panic;
  16
  17pub use offset_utf16::OffsetUtf16;
  18pub use point::Point;
  19pub use point_utf16::PointUtf16;
  20pub use unclipped::Unclipped;
  21
  22#[cfg(test)]
  23const CHUNK_BASE: usize = 6;
  24
  25#[cfg(not(test))]
  26const CHUNK_BASE: usize = 16;
  27
  28/// Type alias to [HashMatrix], an implementation of a homomorphic hash function. Two [Rope] instances
  29/// containing the same text will produce the same fingerprint. This hash function is special in that
  30/// it allows us to hash individual chunks and aggregate them up the [Rope]'s tree, with the resulting
  31/// hash being equivalent to hashing all the text contained in the [Rope] at once.
  32pub type RopeFingerprint = HashMatrix;
  33
  34#[derive(Clone, Default, Debug)]
  35pub struct Rope {
  36    chunks: SumTree<Chunk>,
  37}
  38
  39impl Rope {
  40    pub fn new() -> Self {
  41        Self::default()
  42    }
  43
  44    pub fn append(&mut self, rope: Rope) {
  45        let mut chunks = rope.chunks.cursor::<()>();
  46        chunks.next(&());
  47        if let Some(chunk) = chunks.item() {
  48            if self.chunks.last().map_or(false, |c| c.0.len() < CHUNK_BASE)
  49                || chunk.0.len() < CHUNK_BASE
  50            {
  51                self.push(&chunk.0);
  52                chunks.next(&());
  53            }
  54        }
  55
  56        self.chunks.push_tree(chunks.suffix(&()), &());
  57        self.check_invariants();
  58    }
  59
  60    pub fn replace(&mut self, range: Range<usize>, text: &str) {
  61        let mut new_rope = Rope::new();
  62        let mut cursor = self.cursor(0);
  63        new_rope.append(cursor.slice(range.start));
  64        cursor.seek_forward(range.end);
  65        new_rope.push(text);
  66        new_rope.append(cursor.suffix());
  67        *self = new_rope;
  68    }
  69
  70    pub fn slice(&self, range: Range<usize>) -> Rope {
  71        let mut cursor = self.cursor(0);
  72        cursor.seek_forward(range.start);
  73        cursor.slice(range.end)
  74    }
  75
  76    pub fn slice_rows(&self, range: Range<u32>) -> Rope {
  77        //This would be more efficient with a forward advance after the first, but it's fine
  78        let start = self.point_to_offset(Point::new(range.start, 0));
  79        let end = self.point_to_offset(Point::new(range.end, 0));
  80        self.slice(start..end)
  81    }
  82
  83    pub fn push(&mut self, text: &str) {
  84        let mut new_chunks = SmallVec::<[_; 16]>::new();
  85        let mut new_chunk = ArrayString::new();
  86        for ch in text.chars() {
  87            if new_chunk.len() + ch.len_utf8() > 2 * CHUNK_BASE {
  88                new_chunks.push(Chunk(new_chunk));
  89                new_chunk = ArrayString::new();
  90            }
  91
  92            new_chunk.push(ch);
  93        }
  94        if !new_chunk.is_empty() {
  95            new_chunks.push(Chunk(new_chunk));
  96        }
  97
  98        let mut new_chunks = new_chunks.into_iter();
  99        let mut first_new_chunk = new_chunks.next();
 100        self.chunks.update_last(
 101            |last_chunk| {
 102                if let Some(first_new_chunk_ref) = first_new_chunk.as_mut() {
 103                    if last_chunk.0.len() + first_new_chunk_ref.0.len() <= 2 * CHUNK_BASE {
 104                        last_chunk.0.push_str(&first_new_chunk.take().unwrap().0);
 105                    } else {
 106                        let mut text = ArrayString::<{ 4 * CHUNK_BASE }>::new();
 107                        text.push_str(&last_chunk.0);
 108                        text.push_str(&first_new_chunk_ref.0);
 109                        let (left, right) = text.split_at(find_split_ix(&text));
 110                        last_chunk.0.clear();
 111                        last_chunk.0.push_str(left);
 112                        first_new_chunk_ref.0.clear();
 113                        first_new_chunk_ref.0.push_str(right);
 114                    }
 115                }
 116            },
 117            &(),
 118        );
 119
 120        self.chunks
 121            .extend(first_new_chunk.into_iter().chain(new_chunks), &());
 122        self.check_invariants();
 123    }
 124
 125    pub fn push_front(&mut self, text: &str) {
 126        let suffix = mem::replace(self, Rope::from(text));
 127        self.append(suffix);
 128    }
 129
 130    fn check_invariants(&self) {
 131        #[cfg(test)]
 132        {
 133            // Ensure all chunks except maybe the last one are not underflowing.
 134            // Allow some wiggle room for multibyte characters at chunk boundaries.
 135            let mut chunks = self.chunks.cursor::<()>().peekable();
 136            while let Some(chunk) = chunks.next() {
 137                if chunks.peek().is_some() {
 138                    assert!(chunk.0.len() + 3 >= CHUNK_BASE);
 139                }
 140            }
 141        }
 142    }
 143
 144    pub fn summary(&self) -> TextSummary {
 145        self.chunks.summary().text.clone()
 146    }
 147
 148    pub fn len(&self) -> usize {
 149        self.chunks.extent(&())
 150    }
 151
 152    pub fn is_empty(&self) -> bool {
 153        self.len() == 0
 154    }
 155
 156    pub fn max_point(&self) -> Point {
 157        self.chunks.extent(&())
 158    }
 159
 160    pub fn max_point_utf16(&self) -> PointUtf16 {
 161        self.chunks.extent(&())
 162    }
 163
 164    pub fn cursor(&self, offset: usize) -> Cursor {
 165        Cursor::new(self, offset)
 166    }
 167
 168    pub fn chars(&self) -> impl Iterator<Item = char> + '_ {
 169        self.chars_at(0)
 170    }
 171
 172    pub fn chars_at(&self, start: usize) -> impl Iterator<Item = char> + '_ {
 173        self.chunks_in_range(start..self.len()).flat_map(str::chars)
 174    }
 175
 176    pub fn reversed_chars_at(&self, start: usize) -> impl Iterator<Item = char> + '_ {
 177        self.reversed_chunks_in_range(0..start)
 178            .flat_map(|chunk| chunk.chars().rev())
 179    }
 180
 181    pub fn bytes_in_range(&self, range: Range<usize>) -> Bytes {
 182        Bytes::new(self, range)
 183    }
 184
 185    pub fn chunks(&self) -> Chunks {
 186        self.chunks_in_range(0..self.len())
 187    }
 188
 189    pub fn chunks_in_range(&self, range: Range<usize>) -> Chunks {
 190        Chunks::new(self, range, false)
 191    }
 192
 193    pub fn reversed_chunks_in_range(&self, range: Range<usize>) -> Chunks {
 194        Chunks::new(self, range, true)
 195    }
 196
 197    pub fn offset_to_offset_utf16(&self, offset: usize) -> OffsetUtf16 {
 198        if offset >= self.summary().len {
 199            return self.summary().len_utf16;
 200        }
 201        let mut cursor = self.chunks.cursor::<(usize, OffsetUtf16)>();
 202        cursor.seek(&offset, Bias::Left, &());
 203        let overshoot = offset - cursor.start().0;
 204        cursor.start().1
 205            + cursor.item().map_or(Default::default(), |chunk| {
 206                chunk.offset_to_offset_utf16(overshoot)
 207            })
 208    }
 209
 210    pub fn offset_utf16_to_offset(&self, offset: OffsetUtf16) -> usize {
 211        if offset >= self.summary().len_utf16 {
 212            return self.summary().len;
 213        }
 214        let mut cursor = self.chunks.cursor::<(OffsetUtf16, usize)>();
 215        cursor.seek(&offset, Bias::Left, &());
 216        let overshoot = offset - cursor.start().0;
 217        cursor.start().1
 218            + cursor.item().map_or(Default::default(), |chunk| {
 219                chunk.offset_utf16_to_offset(overshoot)
 220            })
 221    }
 222
 223    pub fn offset_to_point(&self, offset: usize) -> Point {
 224        if offset >= self.summary().len {
 225            return self.summary().lines;
 226        }
 227        let mut cursor = self.chunks.cursor::<(usize, Point)>();
 228        cursor.seek(&offset, Bias::Left, &());
 229        let overshoot = offset - cursor.start().0;
 230        cursor.start().1
 231            + cursor
 232                .item()
 233                .map_or(Point::zero(), |chunk| chunk.offset_to_point(overshoot))
 234    }
 235
 236    pub fn offset_to_point_utf16(&self, offset: usize) -> PointUtf16 {
 237        if offset >= self.summary().len {
 238            return self.summary().lines_utf16();
 239        }
 240        let mut cursor = self.chunks.cursor::<(usize, PointUtf16)>();
 241        cursor.seek(&offset, Bias::Left, &());
 242        let overshoot = offset - cursor.start().0;
 243        cursor.start().1
 244            + cursor.item().map_or(PointUtf16::zero(), |chunk| {
 245                chunk.offset_to_point_utf16(overshoot)
 246            })
 247    }
 248
 249    pub fn point_to_point_utf16(&self, point: Point) -> PointUtf16 {
 250        if point >= self.summary().lines {
 251            return self.summary().lines_utf16();
 252        }
 253        let mut cursor = self.chunks.cursor::<(Point, PointUtf16)>();
 254        cursor.seek(&point, Bias::Left, &());
 255        let overshoot = point - cursor.start().0;
 256        cursor.start().1
 257            + cursor.item().map_or(PointUtf16::zero(), |chunk| {
 258                chunk.point_to_point_utf16(overshoot)
 259            })
 260    }
 261
 262    pub fn point_to_offset(&self, point: Point) -> usize {
 263        if point >= self.summary().lines {
 264            return self.summary().len;
 265        }
 266        let mut cursor = self.chunks.cursor::<(Point, usize)>();
 267        cursor.seek(&point, Bias::Left, &());
 268        let overshoot = point - cursor.start().0;
 269        cursor.start().1
 270            + cursor
 271                .item()
 272                .map_or(0, |chunk| chunk.point_to_offset(overshoot))
 273    }
 274
 275    pub fn point_utf16_to_offset(&self, point: PointUtf16) -> usize {
 276        self.point_utf16_to_offset_impl(point, false)
 277    }
 278
 279    pub fn unclipped_point_utf16_to_offset(&self, point: Unclipped<PointUtf16>) -> usize {
 280        self.point_utf16_to_offset_impl(point.0, true)
 281    }
 282
 283    fn point_utf16_to_offset_impl(&self, point: PointUtf16, clip: bool) -> usize {
 284        if point >= self.summary().lines_utf16() {
 285            return self.summary().len;
 286        }
 287        let mut cursor = self.chunks.cursor::<(PointUtf16, usize)>();
 288        cursor.seek(&point, Bias::Left, &());
 289        let overshoot = point - cursor.start().0;
 290        cursor.start().1
 291            + cursor
 292                .item()
 293                .map_or(0, |chunk| chunk.point_utf16_to_offset(overshoot, clip))
 294    }
 295
 296    pub fn unclipped_point_utf16_to_point(&self, point: Unclipped<PointUtf16>) -> Point {
 297        if point.0 >= self.summary().lines_utf16() {
 298            return self.summary().lines;
 299        }
 300        let mut cursor = self.chunks.cursor::<(PointUtf16, Point)>();
 301        cursor.seek(&point.0, Bias::Left, &());
 302        let overshoot = Unclipped(point.0 - cursor.start().0);
 303        cursor.start().1
 304            + cursor.item().map_or(Point::zero(), |chunk| {
 305                chunk.unclipped_point_utf16_to_point(overshoot)
 306            })
 307    }
 308
 309    pub fn clip_offset(&self, mut offset: usize, bias: Bias) -> usize {
 310        let mut cursor = self.chunks.cursor::<usize>();
 311        cursor.seek(&offset, Bias::Left, &());
 312        if let Some(chunk) = cursor.item() {
 313            let mut ix = offset - cursor.start();
 314            while !chunk.0.is_char_boundary(ix) {
 315                match bias {
 316                    Bias::Left => {
 317                        ix -= 1;
 318                        offset -= 1;
 319                    }
 320                    Bias::Right => {
 321                        ix += 1;
 322                        offset += 1;
 323                    }
 324                }
 325            }
 326            offset
 327        } else {
 328            self.summary().len
 329        }
 330    }
 331
 332    pub fn clip_offset_utf16(&self, offset: OffsetUtf16, bias: Bias) -> OffsetUtf16 {
 333        let mut cursor = self.chunks.cursor::<OffsetUtf16>();
 334        cursor.seek(&offset, Bias::Right, &());
 335        if let Some(chunk) = cursor.item() {
 336            let overshoot = offset - cursor.start();
 337            *cursor.start() + chunk.clip_offset_utf16(overshoot, bias)
 338        } else {
 339            self.summary().len_utf16
 340        }
 341    }
 342
 343    pub fn clip_point(&self, point: Point, bias: Bias) -> Point {
 344        let mut cursor = self.chunks.cursor::<Point>();
 345        cursor.seek(&point, Bias::Right, &());
 346        if let Some(chunk) = cursor.item() {
 347            let overshoot = point - cursor.start();
 348            *cursor.start() + chunk.clip_point(overshoot, bias)
 349        } else {
 350            self.summary().lines
 351        }
 352    }
 353
 354    pub fn clip_point_utf16(&self, point: Unclipped<PointUtf16>, bias: Bias) -> PointUtf16 {
 355        let mut cursor = self.chunks.cursor::<PointUtf16>();
 356        cursor.seek(&point.0, Bias::Right, &());
 357        if let Some(chunk) = cursor.item() {
 358            let overshoot = Unclipped(point.0 - cursor.start());
 359            *cursor.start() + chunk.clip_point_utf16(overshoot, bias)
 360        } else {
 361            self.summary().lines_utf16()
 362        }
 363    }
 364
 365    pub fn line_len(&self, row: u32) -> u32 {
 366        self.clip_point(Point::new(row, u32::MAX), Bias::Left)
 367            .column
 368    }
 369
 370    pub fn fingerprint(&self) -> RopeFingerprint {
 371        self.chunks.summary().fingerprint
 372    }
 373}
 374
 375impl<'a> From<&'a str> for Rope {
 376    fn from(text: &'a str) -> Self {
 377        let mut rope = Self::new();
 378        rope.push(text);
 379        rope
 380    }
 381}
 382
 383impl fmt::Display for Rope {
 384    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 385        for chunk in self.chunks() {
 386            write!(f, "{}", chunk)?;
 387        }
 388        Ok(())
 389    }
 390}
 391
 392pub struct Cursor<'a> {
 393    rope: &'a Rope,
 394    chunks: sum_tree::Cursor<'a, Chunk, usize>,
 395    offset: usize,
 396}
 397
 398impl<'a> Cursor<'a> {
 399    pub fn new(rope: &'a Rope, offset: usize) -> Self {
 400        let mut chunks = rope.chunks.cursor();
 401        chunks.seek(&offset, Bias::Right, &());
 402        Self {
 403            rope,
 404            chunks,
 405            offset,
 406        }
 407    }
 408
 409    pub fn seek_forward(&mut self, end_offset: usize) {
 410        debug_assert!(end_offset >= self.offset);
 411
 412        self.chunks.seek_forward(&end_offset, Bias::Right, &());
 413        self.offset = end_offset;
 414    }
 415
 416    pub fn slice(&mut self, end_offset: usize) -> Rope {
 417        debug_assert!(
 418            end_offset >= self.offset,
 419            "cannot slice backwards from {} to {}",
 420            self.offset,
 421            end_offset
 422        );
 423
 424        let mut slice = Rope::new();
 425        if let Some(start_chunk) = self.chunks.item() {
 426            let start_ix = self.offset - self.chunks.start();
 427            let end_ix = cmp::min(end_offset, self.chunks.end(&())) - self.chunks.start();
 428            slice.push(&start_chunk.0[start_ix..end_ix]);
 429        }
 430
 431        if end_offset > self.chunks.end(&()) {
 432            self.chunks.next(&());
 433            slice.append(Rope {
 434                chunks: self.chunks.slice(&end_offset, Bias::Right, &()),
 435            });
 436            if let Some(end_chunk) = self.chunks.item() {
 437                let end_ix = end_offset - self.chunks.start();
 438                slice.push(&end_chunk.0[..end_ix]);
 439            }
 440        }
 441
 442        self.offset = end_offset;
 443        slice
 444    }
 445
 446    pub fn summary<D: TextDimension>(&mut self, end_offset: usize) -> D {
 447        debug_assert!(end_offset >= self.offset);
 448
 449        let mut summary = D::default();
 450        if let Some(start_chunk) = self.chunks.item() {
 451            let start_ix = self.offset - self.chunks.start();
 452            let end_ix = cmp::min(end_offset, self.chunks.end(&())) - self.chunks.start();
 453            summary.add_assign(&D::from_text_summary(&TextSummary::from(
 454                &start_chunk.0[start_ix..end_ix],
 455            )));
 456        }
 457
 458        if end_offset > self.chunks.end(&()) {
 459            self.chunks.next(&());
 460            summary.add_assign(&self.chunks.summary(&end_offset, Bias::Right, &()));
 461            if let Some(end_chunk) = self.chunks.item() {
 462                let end_ix = end_offset - self.chunks.start();
 463                summary.add_assign(&D::from_text_summary(&TextSummary::from(
 464                    &end_chunk.0[..end_ix],
 465                )));
 466            }
 467        }
 468
 469        self.offset = end_offset;
 470        summary
 471    }
 472
 473    pub fn suffix(mut self) -> Rope {
 474        self.slice(self.rope.chunks.extent(&()))
 475    }
 476
 477    pub fn offset(&self) -> usize {
 478        self.offset
 479    }
 480}
 481
 482pub struct Chunks<'a> {
 483    chunks: sum_tree::Cursor<'a, Chunk, usize>,
 484    range: Range<usize>,
 485    reversed: bool,
 486}
 487
 488impl<'a> Chunks<'a> {
 489    pub fn new(rope: &'a Rope, range: Range<usize>, reversed: bool) -> Self {
 490        let mut chunks = rope.chunks.cursor();
 491        if reversed {
 492            chunks.seek(&range.end, Bias::Left, &());
 493        } else {
 494            chunks.seek(&range.start, Bias::Right, &());
 495        }
 496        Self {
 497            chunks,
 498            range,
 499            reversed,
 500        }
 501    }
 502
 503    pub fn offset(&self) -> usize {
 504        if self.reversed {
 505            self.range.end.min(self.chunks.end(&()))
 506        } else {
 507            self.range.start.max(*self.chunks.start())
 508        }
 509    }
 510
 511    pub fn seek(&mut self, offset: usize) {
 512        let bias = if self.reversed {
 513            Bias::Left
 514        } else {
 515            Bias::Right
 516        };
 517
 518        if offset >= self.chunks.end(&()) {
 519            self.chunks.seek_forward(&offset, bias, &());
 520        } else {
 521            self.chunks.seek(&offset, bias, &());
 522        }
 523
 524        if self.reversed {
 525            self.range.end = offset;
 526        } else {
 527            self.range.start = offset;
 528        }
 529    }
 530
 531    pub fn peek(&self) -> Option<&'a str> {
 532        let chunk = self.chunks.item()?;
 533        if self.reversed && self.range.start >= self.chunks.end(&()) {
 534            return None;
 535        }
 536        let chunk_start = *self.chunks.start();
 537        if self.range.end <= chunk_start {
 538            return None;
 539        }
 540
 541        let start = self.range.start.saturating_sub(chunk_start);
 542        let end = self.range.end - chunk_start;
 543        Some(&chunk.0[start..chunk.0.len().min(end)])
 544    }
 545}
 546
 547impl<'a> Iterator for Chunks<'a> {
 548    type Item = &'a str;
 549
 550    fn next(&mut self) -> Option<Self::Item> {
 551        let result = self.peek();
 552        if result.is_some() {
 553            if self.reversed {
 554                self.chunks.prev(&());
 555            } else {
 556                self.chunks.next(&());
 557            }
 558        }
 559        result
 560    }
 561}
 562
 563pub struct Bytes<'a> {
 564    chunks: sum_tree::Cursor<'a, Chunk, usize>,
 565    range: Range<usize>,
 566}
 567
 568impl<'a> Bytes<'a> {
 569    pub fn new(rope: &'a Rope, range: Range<usize>) -> Self {
 570        let mut chunks = rope.chunks.cursor();
 571        chunks.seek(&range.start, Bias::Right, &());
 572        Self { chunks, range }
 573    }
 574
 575    pub fn peek(&self) -> Option<&'a [u8]> {
 576        let chunk = self.chunks.item()?;
 577        let chunk_start = *self.chunks.start();
 578        if self.range.end <= chunk_start {
 579            return None;
 580        }
 581
 582        let start = self.range.start.saturating_sub(chunk_start);
 583        let end = self.range.end - chunk_start;
 584        Some(&chunk.0.as_bytes()[start..chunk.0.len().min(end)])
 585    }
 586}
 587
 588impl<'a> Iterator for Bytes<'a> {
 589    type Item = &'a [u8];
 590
 591    fn next(&mut self) -> Option<Self::Item> {
 592        let result = self.peek();
 593        if result.is_some() {
 594            self.chunks.next(&());
 595        }
 596        result
 597    }
 598}
 599
 600impl<'a> io::Read for Bytes<'a> {
 601    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
 602        if let Some(chunk) = self.peek() {
 603            let len = cmp::min(buf.len(), chunk.len());
 604            buf[..len].copy_from_slice(&chunk[..len]);
 605            self.range.start += len;
 606            if len == chunk.len() {
 607                self.chunks.next(&());
 608            }
 609            Ok(len)
 610        } else {
 611            Ok(0)
 612        }
 613    }
 614}
 615
 616#[derive(Clone, Debug, Default)]
 617struct Chunk(ArrayString<{ 2 * CHUNK_BASE }>);
 618
 619impl Chunk {
 620    fn offset_to_offset_utf16(&self, target: usize) -> OffsetUtf16 {
 621        let mut offset = 0;
 622        let mut offset_utf16 = OffsetUtf16(0);
 623        for ch in self.0.chars() {
 624            if offset >= target {
 625                break;
 626            }
 627
 628            offset += ch.len_utf8();
 629            offset_utf16.0 += ch.len_utf16();
 630        }
 631        offset_utf16
 632    }
 633
 634    fn offset_utf16_to_offset(&self, target: OffsetUtf16) -> usize {
 635        let mut offset_utf16 = OffsetUtf16(0);
 636        let mut offset = 0;
 637        for ch in self.0.chars() {
 638            if offset_utf16 >= target {
 639                break;
 640            }
 641
 642            offset += ch.len_utf8();
 643            offset_utf16.0 += ch.len_utf16();
 644        }
 645        offset
 646    }
 647
 648    fn offset_to_point(&self, target: usize) -> Point {
 649        let mut offset = 0;
 650        let mut point = Point::new(0, 0);
 651        for ch in self.0.chars() {
 652            if offset >= target {
 653                break;
 654            }
 655
 656            if ch == '\n' {
 657                point.row += 1;
 658                point.column = 0;
 659            } else {
 660                point.column += ch.len_utf8() as u32;
 661            }
 662            offset += ch.len_utf8();
 663        }
 664        point
 665    }
 666
 667    fn offset_to_point_utf16(&self, target: usize) -> PointUtf16 {
 668        let mut offset = 0;
 669        let mut point = PointUtf16::new(0, 0);
 670        for ch in self.0.chars() {
 671            if offset >= target {
 672                break;
 673            }
 674
 675            if ch == '\n' {
 676                point.row += 1;
 677                point.column = 0;
 678            } else {
 679                point.column += ch.len_utf16() as u32;
 680            }
 681            offset += ch.len_utf8();
 682        }
 683        point
 684    }
 685
 686    fn point_to_offset(&self, target: Point) -> usize {
 687        let mut offset = 0;
 688        let mut point = Point::new(0, 0);
 689
 690        for ch in self.0.chars() {
 691            if point >= target {
 692                if point > target {
 693                    debug_panic!("point {target:?} is inside of character {ch:?}");
 694                }
 695                break;
 696            }
 697
 698            if ch == '\n' {
 699                point.row += 1;
 700                point.column = 0;
 701
 702                if point.row > target.row {
 703                    debug_panic!(
 704                        "point {target:?} is beyond the end of a line with length {}",
 705                        point.column
 706                    );
 707                    break;
 708                }
 709            } else {
 710                point.column += ch.len_utf8() as u32;
 711            }
 712
 713            offset += ch.len_utf8();
 714        }
 715
 716        offset
 717    }
 718
 719    fn point_to_point_utf16(&self, target: Point) -> PointUtf16 {
 720        let mut point = Point::zero();
 721        let mut point_utf16 = PointUtf16::new(0, 0);
 722        for ch in self.0.chars() {
 723            if point >= target {
 724                break;
 725            }
 726
 727            if ch == '\n' {
 728                point_utf16.row += 1;
 729                point_utf16.column = 0;
 730                point.row += 1;
 731                point.column = 0;
 732            } else {
 733                point_utf16.column += ch.len_utf16() as u32;
 734                point.column += ch.len_utf8() as u32;
 735            }
 736        }
 737        point_utf16
 738    }
 739
 740    fn point_utf16_to_offset(&self, target: PointUtf16, clip: bool) -> usize {
 741        let mut offset = 0;
 742        let mut point = PointUtf16::new(0, 0);
 743
 744        for ch in self.0.chars() {
 745            if point == target {
 746                break;
 747            }
 748
 749            if ch == '\n' {
 750                point.row += 1;
 751                point.column = 0;
 752
 753                if point.row > target.row {
 754                    if !clip {
 755                        debug_panic!(
 756                            "point {target:?} is beyond the end of a line with length {}",
 757                            point.column
 758                        );
 759                    }
 760                    // Return the offset of the newline
 761                    return offset;
 762                }
 763            } else {
 764                point.column += ch.len_utf16() as u32;
 765            }
 766
 767            if point > target {
 768                if !clip {
 769                    debug_panic!("point {target:?} is inside of codepoint {ch:?}");
 770                }
 771                // Return the offset of the codepoint which we have landed within, bias left
 772                return offset;
 773            }
 774
 775            offset += ch.len_utf8();
 776        }
 777
 778        offset
 779    }
 780
 781    fn unclipped_point_utf16_to_point(&self, target: Unclipped<PointUtf16>) -> Point {
 782        let mut point = Point::zero();
 783        let mut point_utf16 = PointUtf16::zero();
 784
 785        for ch in self.0.chars() {
 786            if point_utf16 == target.0 {
 787                break;
 788            }
 789
 790            if point_utf16 > target.0 {
 791                // If the point is past the end of a line or inside of a code point,
 792                // return the last valid point before the target.
 793                return point;
 794            }
 795
 796            if ch == '\n' {
 797                point_utf16 += PointUtf16::new(1, 0);
 798                point += Point::new(1, 0);
 799            } else {
 800                point_utf16 += PointUtf16::new(0, ch.len_utf16() as u32);
 801                point += Point::new(0, ch.len_utf8() as u32);
 802            }
 803        }
 804
 805        point
 806    }
 807
 808    fn clip_point(&self, target: Point, bias: Bias) -> Point {
 809        for (row, line) in self.0.split('\n').enumerate() {
 810            if row == target.row as usize {
 811                let mut column = target.column.min(line.len() as u32);
 812                while !line.is_char_boundary(column as usize) {
 813                    match bias {
 814                        Bias::Left => column -= 1,
 815                        Bias::Right => column += 1,
 816                    }
 817                }
 818                return Point::new(row as u32, column);
 819            }
 820        }
 821        unreachable!()
 822    }
 823
 824    fn clip_point_utf16(&self, target: Unclipped<PointUtf16>, bias: Bias) -> PointUtf16 {
 825        for (row, line) in self.0.split('\n').enumerate() {
 826            if row == target.0.row as usize {
 827                let mut code_units = line.encode_utf16();
 828                let mut column = code_units.by_ref().take(target.0.column as usize).count();
 829                if char::decode_utf16(code_units).next().transpose().is_err() {
 830                    match bias {
 831                        Bias::Left => column -= 1,
 832                        Bias::Right => column += 1,
 833                    }
 834                }
 835                return PointUtf16::new(row as u32, column as u32);
 836            }
 837        }
 838        unreachable!()
 839    }
 840
 841    fn clip_offset_utf16(&self, target: OffsetUtf16, bias: Bias) -> OffsetUtf16 {
 842        let mut code_units = self.0.encode_utf16();
 843        let mut offset = code_units.by_ref().take(target.0 as usize).count();
 844        if char::decode_utf16(code_units).next().transpose().is_err() {
 845            match bias {
 846                Bias::Left => offset -= 1,
 847                Bias::Right => offset += 1,
 848            }
 849        }
 850        OffsetUtf16(offset)
 851    }
 852}
 853
 854impl sum_tree::Item for Chunk {
 855    type Summary = ChunkSummary;
 856
 857    fn summary(&self) -> Self::Summary {
 858        ChunkSummary::from(self.0.as_str())
 859    }
 860}
 861
 862#[derive(Clone, Debug, Default, Eq, PartialEq)]
 863pub struct ChunkSummary {
 864    text: TextSummary,
 865    fingerprint: RopeFingerprint,
 866}
 867
 868impl<'a> From<&'a str> for ChunkSummary {
 869    fn from(text: &'a str) -> Self {
 870        Self {
 871            text: TextSummary::from(text),
 872            fingerprint: bromberg_sl2::hash_strict(text.as_bytes()),
 873        }
 874    }
 875}
 876
 877impl sum_tree::Summary for ChunkSummary {
 878    type Context = ();
 879
 880    fn add_summary(&mut self, summary: &Self, _: &()) {
 881        self.text += &summary.text;
 882        self.fingerprint = self.fingerprint * summary.fingerprint;
 883    }
 884}
 885
 886#[derive(Clone, Debug, Default, Eq, PartialEq)]
 887pub struct TextSummary {
 888    pub len: usize,
 889    pub len_utf16: OffsetUtf16,
 890    pub lines: Point,
 891    pub first_line_chars: u32,
 892    pub last_line_chars: u32,
 893    pub last_line_len_utf16: u32,
 894    pub longest_row: u32,
 895    pub longest_row_chars: u32,
 896}
 897
 898impl TextSummary {
 899    pub fn lines_utf16(&self) -> PointUtf16 {
 900        PointUtf16 {
 901            row: self.lines.row,
 902            column: self.last_line_len_utf16,
 903        }
 904    }
 905}
 906
 907impl<'a> From<&'a str> for TextSummary {
 908    fn from(text: &'a str) -> Self {
 909        let mut len_utf16 = OffsetUtf16(0);
 910        let mut lines = Point::new(0, 0);
 911        let mut first_line_chars = 0;
 912        let mut last_line_chars = 0;
 913        let mut last_line_len_utf16 = 0;
 914        let mut longest_row = 0;
 915        let mut longest_row_chars = 0;
 916        for c in text.chars() {
 917            len_utf16.0 += c.len_utf16();
 918
 919            if c == '\n' {
 920                lines += Point::new(1, 0);
 921                last_line_len_utf16 = 0;
 922                last_line_chars = 0;
 923            } else {
 924                lines.column += c.len_utf8() as u32;
 925                last_line_len_utf16 += c.len_utf16() as u32;
 926                last_line_chars += 1;
 927            }
 928
 929            if lines.row == 0 {
 930                first_line_chars = last_line_chars;
 931            }
 932
 933            if last_line_chars > longest_row_chars {
 934                longest_row = lines.row;
 935                longest_row_chars = last_line_chars;
 936            }
 937        }
 938
 939        TextSummary {
 940            len: text.len(),
 941            len_utf16,
 942            lines,
 943            first_line_chars,
 944            last_line_chars,
 945            last_line_len_utf16,
 946            longest_row,
 947            longest_row_chars,
 948        }
 949    }
 950}
 951
 952impl sum_tree::Summary for TextSummary {
 953    type Context = ();
 954
 955    fn add_summary(&mut self, summary: &Self, _: &Self::Context) {
 956        *self += summary;
 957    }
 958}
 959
 960impl std::ops::Add<Self> for TextSummary {
 961    type Output = Self;
 962
 963    fn add(mut self, rhs: Self) -> Self::Output {
 964        AddAssign::add_assign(&mut self, &rhs);
 965        self
 966    }
 967}
 968
 969impl<'a> std::ops::AddAssign<&'a Self> for TextSummary {
 970    fn add_assign(&mut self, other: &'a Self) {
 971        let joined_chars = self.last_line_chars + other.first_line_chars;
 972        if joined_chars > self.longest_row_chars {
 973            self.longest_row = self.lines.row;
 974            self.longest_row_chars = joined_chars;
 975        }
 976        if other.longest_row_chars > self.longest_row_chars {
 977            self.longest_row = self.lines.row + other.longest_row;
 978            self.longest_row_chars = other.longest_row_chars;
 979        }
 980
 981        if self.lines.row == 0 {
 982            self.first_line_chars += other.first_line_chars;
 983        }
 984
 985        if other.lines.row == 0 {
 986            self.last_line_chars += other.first_line_chars;
 987            self.last_line_len_utf16 += other.last_line_len_utf16;
 988        } else {
 989            self.last_line_chars = other.last_line_chars;
 990            self.last_line_len_utf16 = other.last_line_len_utf16;
 991        }
 992
 993        self.len += other.len;
 994        self.len_utf16 += other.len_utf16;
 995        self.lines += other.lines;
 996    }
 997}
 998
 999impl std::ops::AddAssign<Self> for TextSummary {
1000    fn add_assign(&mut self, other: Self) {
1001        *self += &other;
1002    }
1003}
1004
1005pub trait TextDimension: 'static + for<'a> Dimension<'a, ChunkSummary> {
1006    fn from_text_summary(summary: &TextSummary) -> Self;
1007    fn add_assign(&mut self, other: &Self);
1008}
1009
1010impl<D1: TextDimension, D2: TextDimension> TextDimension for (D1, D2) {
1011    fn from_text_summary(summary: &TextSummary) -> Self {
1012        (
1013            D1::from_text_summary(summary),
1014            D2::from_text_summary(summary),
1015        )
1016    }
1017
1018    fn add_assign(&mut self, other: &Self) {
1019        self.0.add_assign(&other.0);
1020        self.1.add_assign(&other.1);
1021    }
1022}
1023
1024impl<'a> sum_tree::Dimension<'a, ChunkSummary> for TextSummary {
1025    fn add_summary(&mut self, summary: &'a ChunkSummary, _: &()) {
1026        *self += &summary.text;
1027    }
1028}
1029
1030impl TextDimension for TextSummary {
1031    fn from_text_summary(summary: &TextSummary) -> Self {
1032        summary.clone()
1033    }
1034
1035    fn add_assign(&mut self, other: &Self) {
1036        *self += other;
1037    }
1038}
1039
1040impl<'a> sum_tree::Dimension<'a, ChunkSummary> for usize {
1041    fn add_summary(&mut self, summary: &'a ChunkSummary, _: &()) {
1042        *self += summary.text.len;
1043    }
1044}
1045
1046impl TextDimension for usize {
1047    fn from_text_summary(summary: &TextSummary) -> Self {
1048        summary.len
1049    }
1050
1051    fn add_assign(&mut self, other: &Self) {
1052        *self += other;
1053    }
1054}
1055
1056impl<'a> sum_tree::Dimension<'a, ChunkSummary> for OffsetUtf16 {
1057    fn add_summary(&mut self, summary: &'a ChunkSummary, _: &()) {
1058        *self += summary.text.len_utf16;
1059    }
1060}
1061
1062impl TextDimension for OffsetUtf16 {
1063    fn from_text_summary(summary: &TextSummary) -> Self {
1064        summary.len_utf16
1065    }
1066
1067    fn add_assign(&mut self, other: &Self) {
1068        *self += other;
1069    }
1070}
1071
1072impl<'a> sum_tree::Dimension<'a, ChunkSummary> for Point {
1073    fn add_summary(&mut self, summary: &'a ChunkSummary, _: &()) {
1074        *self += summary.text.lines;
1075    }
1076}
1077
1078impl TextDimension for Point {
1079    fn from_text_summary(summary: &TextSummary) -> Self {
1080        summary.lines
1081    }
1082
1083    fn add_assign(&mut self, other: &Self) {
1084        *self += other;
1085    }
1086}
1087
1088impl<'a> sum_tree::Dimension<'a, ChunkSummary> for PointUtf16 {
1089    fn add_summary(&mut self, summary: &'a ChunkSummary, _: &()) {
1090        *self += summary.text.lines_utf16();
1091    }
1092}
1093
1094impl TextDimension for PointUtf16 {
1095    fn from_text_summary(summary: &TextSummary) -> Self {
1096        summary.lines_utf16()
1097    }
1098
1099    fn add_assign(&mut self, other: &Self) {
1100        *self += other;
1101    }
1102}
1103
1104fn find_split_ix(text: &str) -> usize {
1105    let mut ix = text.len() / 2;
1106    while !text.is_char_boundary(ix) {
1107        if ix < 2 * CHUNK_BASE {
1108            ix += 1;
1109        } else {
1110            ix = (text.len() / 2) - 1;
1111            break;
1112        }
1113    }
1114    while !text.is_char_boundary(ix) {
1115        ix -= 1;
1116    }
1117
1118    debug_assert!(ix <= 2 * CHUNK_BASE);
1119    debug_assert!(text.len() - ix <= 2 * CHUNK_BASE);
1120    ix
1121}
1122
1123#[cfg(test)]
1124mod tests {
1125    use super::*;
1126    use rand::prelude::*;
1127    use std::{cmp::Ordering, env, io::Read};
1128    use util::RandomCharIter;
1129    use Bias::{Left, Right};
1130
1131    #[test]
1132    fn test_all_4_byte_chars() {
1133        let mut rope = Rope::new();
1134        let text = "🏀".repeat(256);
1135        rope.push(&text);
1136        assert_eq!(rope.text(), text);
1137    }
1138
1139    #[test]
1140    fn test_clip() {
1141        let rope = Rope::from("🧘");
1142
1143        assert_eq!(rope.clip_offset(1, Bias::Left), 0);
1144        assert_eq!(rope.clip_offset(1, Bias::Right), 4);
1145        assert_eq!(rope.clip_offset(5, Bias::Right), 4);
1146
1147        assert_eq!(
1148            rope.clip_point(Point::new(0, 1), Bias::Left),
1149            Point::new(0, 0)
1150        );
1151        assert_eq!(
1152            rope.clip_point(Point::new(0, 1), Bias::Right),
1153            Point::new(0, 4)
1154        );
1155        assert_eq!(
1156            rope.clip_point(Point::new(0, 5), Bias::Right),
1157            Point::new(0, 4)
1158        );
1159
1160        assert_eq!(
1161            rope.clip_point_utf16(Unclipped(PointUtf16::new(0, 1)), Bias::Left),
1162            PointUtf16::new(0, 0)
1163        );
1164        assert_eq!(
1165            rope.clip_point_utf16(Unclipped(PointUtf16::new(0, 1)), Bias::Right),
1166            PointUtf16::new(0, 2)
1167        );
1168        assert_eq!(
1169            rope.clip_point_utf16(Unclipped(PointUtf16::new(0, 3)), Bias::Right),
1170            PointUtf16::new(0, 2)
1171        );
1172
1173        assert_eq!(
1174            rope.clip_offset_utf16(OffsetUtf16(1), Bias::Left),
1175            OffsetUtf16(0)
1176        );
1177        assert_eq!(
1178            rope.clip_offset_utf16(OffsetUtf16(1), Bias::Right),
1179            OffsetUtf16(2)
1180        );
1181        assert_eq!(
1182            rope.clip_offset_utf16(OffsetUtf16(3), Bias::Right),
1183            OffsetUtf16(2)
1184        );
1185    }
1186
1187    #[gpui::test(iterations = 100)]
1188    fn test_random_rope(mut rng: StdRng) {
1189        let operations = env::var("OPERATIONS")
1190            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
1191            .unwrap_or(10);
1192
1193        let mut expected = String::new();
1194        let mut actual = Rope::new();
1195        for _ in 0..operations {
1196            let end_ix = clip_offset(&expected, rng.gen_range(0..=expected.len()), Right);
1197            let start_ix = clip_offset(&expected, rng.gen_range(0..=end_ix), Left);
1198            let len = rng.gen_range(0..=64);
1199            let new_text: String = RandomCharIter::new(&mut rng).take(len).collect();
1200
1201            let mut new_actual = Rope::new();
1202            let mut cursor = actual.cursor(0);
1203            new_actual.append(cursor.slice(start_ix));
1204            new_actual.push(&new_text);
1205            cursor.seek_forward(end_ix);
1206            new_actual.append(cursor.suffix());
1207            actual = new_actual;
1208
1209            expected.replace_range(start_ix..end_ix, &new_text);
1210
1211            assert_eq!(actual.text(), expected);
1212            log::info!("text: {:?}", expected);
1213
1214            for _ in 0..5 {
1215                let end_ix = clip_offset(&expected, rng.gen_range(0..=expected.len()), Right);
1216                let start_ix = clip_offset(&expected, rng.gen_range(0..=end_ix), Left);
1217
1218                let actual_text = actual.chunks_in_range(start_ix..end_ix).collect::<String>();
1219                assert_eq!(actual_text, &expected[start_ix..end_ix]);
1220
1221                let mut actual_text = String::new();
1222                actual
1223                    .bytes_in_range(start_ix..end_ix)
1224                    .read_to_string(&mut actual_text)
1225                    .unwrap();
1226                assert_eq!(actual_text, &expected[start_ix..end_ix]);
1227
1228                assert_eq!(
1229                    actual
1230                        .reversed_chunks_in_range(start_ix..end_ix)
1231                        .collect::<Vec<&str>>()
1232                        .into_iter()
1233                        .rev()
1234                        .collect::<String>(),
1235                    &expected[start_ix..end_ix]
1236                );
1237            }
1238
1239            let mut offset_utf16 = OffsetUtf16(0);
1240            let mut point = Point::new(0, 0);
1241            let mut point_utf16 = PointUtf16::new(0, 0);
1242            for (ix, ch) in expected.char_indices().chain(Some((expected.len(), '\0'))) {
1243                assert_eq!(actual.offset_to_point(ix), point, "offset_to_point({})", ix);
1244                assert_eq!(
1245                    actual.offset_to_point_utf16(ix),
1246                    point_utf16,
1247                    "offset_to_point_utf16({})",
1248                    ix
1249                );
1250                assert_eq!(
1251                    actual.point_to_offset(point),
1252                    ix,
1253                    "point_to_offset({:?})",
1254                    point
1255                );
1256                assert_eq!(
1257                    actual.point_utf16_to_offset(point_utf16),
1258                    ix,
1259                    "point_utf16_to_offset({:?})",
1260                    point_utf16
1261                );
1262                assert_eq!(
1263                    actual.offset_to_offset_utf16(ix),
1264                    offset_utf16,
1265                    "offset_to_offset_utf16({:?})",
1266                    ix
1267                );
1268                assert_eq!(
1269                    actual.offset_utf16_to_offset(offset_utf16),
1270                    ix,
1271                    "offset_utf16_to_offset({:?})",
1272                    offset_utf16
1273                );
1274                if ch == '\n' {
1275                    point += Point::new(1, 0);
1276                    point_utf16 += PointUtf16::new(1, 0);
1277                } else {
1278                    point.column += ch.len_utf8() as u32;
1279                    point_utf16.column += ch.len_utf16() as u32;
1280                }
1281                offset_utf16.0 += ch.len_utf16();
1282            }
1283
1284            let mut offset_utf16 = OffsetUtf16(0);
1285            let mut point_utf16 = Unclipped(PointUtf16::zero());
1286            for unit in expected.encode_utf16() {
1287                let left_offset = actual.clip_offset_utf16(offset_utf16, Bias::Left);
1288                let right_offset = actual.clip_offset_utf16(offset_utf16, Bias::Right);
1289                assert!(right_offset >= left_offset);
1290                // Ensure translating UTF-16 offsets to UTF-8 offsets doesn't panic.
1291                actual.offset_utf16_to_offset(left_offset);
1292                actual.offset_utf16_to_offset(right_offset);
1293
1294                let left_point = actual.clip_point_utf16(point_utf16, Bias::Left);
1295                let right_point = actual.clip_point_utf16(point_utf16, Bias::Right);
1296                assert!(right_point >= left_point);
1297                // Ensure translating valid UTF-16 points to offsets doesn't panic.
1298                actual.point_utf16_to_offset(left_point);
1299                actual.point_utf16_to_offset(right_point);
1300
1301                offset_utf16.0 += 1;
1302                if unit == b'\n' as u16 {
1303                    point_utf16.0 += PointUtf16::new(1, 0);
1304                } else {
1305                    point_utf16.0 += PointUtf16::new(0, 1);
1306                }
1307            }
1308
1309            for _ in 0..5 {
1310                let end_ix = clip_offset(&expected, rng.gen_range(0..=expected.len()), Right);
1311                let start_ix = clip_offset(&expected, rng.gen_range(0..=end_ix), Left);
1312                assert_eq!(
1313                    actual.cursor(start_ix).summary::<TextSummary>(end_ix),
1314                    TextSummary::from(&expected[start_ix..end_ix])
1315                );
1316            }
1317
1318            let mut expected_longest_rows = Vec::new();
1319            let mut longest_line_len = -1_isize;
1320            for (row, line) in expected.split('\n').enumerate() {
1321                let row = row as u32;
1322                assert_eq!(
1323                    actual.line_len(row),
1324                    line.len() as u32,
1325                    "invalid line len for row {}",
1326                    row
1327                );
1328
1329                let line_char_count = line.chars().count() as isize;
1330                match line_char_count.cmp(&longest_line_len) {
1331                    Ordering::Less => {}
1332                    Ordering::Equal => expected_longest_rows.push(row),
1333                    Ordering::Greater => {
1334                        longest_line_len = line_char_count;
1335                        expected_longest_rows.clear();
1336                        expected_longest_rows.push(row);
1337                    }
1338                }
1339            }
1340
1341            let longest_row = actual.summary().longest_row;
1342            assert!(
1343                expected_longest_rows.contains(&longest_row),
1344                "incorrect longest row {}. expected {:?} with length {}",
1345                longest_row,
1346                expected_longest_rows,
1347                longest_line_len,
1348            );
1349        }
1350    }
1351
1352    fn clip_offset(text: &str, mut offset: usize, bias: Bias) -> usize {
1353        while !text.is_char_boundary(offset) {
1354            match bias {
1355                Bias::Left => offset -= 1,
1356                Bias::Right => offset += 1,
1357            }
1358        }
1359        offset
1360    }
1361
1362    impl Rope {
1363        fn text(&self) -> String {
1364            let mut text = String::new();
1365            for chunk in self.chunks.cursor::<()>() {
1366                text.push_str(&chunk.0);
1367            }
1368            text
1369        }
1370    }
1371}