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