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