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