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