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