1mod chunk;
2mod offset_utf16;
3mod point;
4mod point_utf16;
5mod unclipped;
6
7use chunk::Chunk;
8use rayon::iter::{IntoParallelIterator, ParallelIterator as _};
9use smallvec::SmallVec;
10use std::{
11 cmp, fmt, io, mem,
12 ops::{self, AddAssign, Range},
13 str,
14};
15use sum_tree::{Bias, Dimension, Dimensions, SumTree};
16
17pub use chunk::ChunkSlice;
18pub use offset_utf16::OffsetUtf16;
19pub use point::Point;
20pub use point_utf16::PointUtf16;
21pub use unclipped::Unclipped;
22
23#[derive(Clone, Default)]
24pub struct Rope {
25 chunks: SumTree<Chunk>,
26}
27
28impl Rope {
29 pub fn new() -> Self {
30 Self::default()
31 }
32
33 pub fn append(&mut self, rope: Rope) {
34 if let Some(chunk) = rope.chunks.first()
35 && (self
36 .chunks
37 .last()
38 .is_some_and(|c| c.text.len() < chunk::MIN_BASE)
39 || chunk.text.len() < chunk::MIN_BASE)
40 {
41 self.push_chunk(chunk.as_slice());
42
43 let mut chunks = rope.chunks.cursor::<()>(&());
44 chunks.next();
45 chunks.next();
46 self.chunks.append(chunks.suffix(), &());
47 self.check_invariants();
48 return;
49 }
50
51 self.chunks.append(rope.chunks.clone(), &());
52 self.check_invariants();
53 }
54
55 pub fn replace(&mut self, range: Range<usize>, text: &str) {
56 let mut new_rope = Rope::new();
57 let mut cursor = self.cursor(0);
58 new_rope.append(cursor.slice(range.start));
59 cursor.seek_forward(range.end);
60 new_rope.push(text);
61 new_rope.append(cursor.suffix());
62 *self = new_rope;
63 }
64
65 pub fn slice(&self, range: Range<usize>) -> Rope {
66 let mut cursor = self.cursor(0);
67 cursor.seek_forward(range.start);
68 cursor.slice(range.end)
69 }
70
71 pub fn slice_rows(&self, range: Range<u32>) -> Rope {
72 // This would be more efficient with a forward advance after the first, but it's fine.
73 let start = self.point_to_offset(Point::new(range.start, 0));
74 let end = self.point_to_offset(Point::new(range.end, 0));
75 self.slice(start..end)
76 }
77
78 pub fn push(&mut self, mut text: &str) {
79 self.chunks.update_last(
80 |last_chunk| {
81 let split_ix = if last_chunk.text.len() + text.len() <= chunk::MAX_BASE {
82 text.len()
83 } else {
84 let mut split_ix = cmp::min(
85 chunk::MIN_BASE.saturating_sub(last_chunk.text.len()),
86 text.len(),
87 );
88 while !text.is_char_boundary(split_ix) {
89 split_ix += 1;
90 }
91 split_ix
92 };
93
94 let (suffix, remainder) = text.split_at(split_ix);
95 last_chunk.push_str(suffix);
96 text = remainder;
97 },
98 &(),
99 );
100
101 if text.len() > 2048 {
102 return self.push_large(text);
103 }
104 let mut new_chunks = SmallVec::<[_; 16]>::new();
105
106 while !text.is_empty() {
107 let mut split_ix = cmp::min(chunk::MAX_BASE, text.len());
108 while !text.is_char_boundary(split_ix) {
109 split_ix -= 1;
110 }
111 let (chunk, remainder) = text.split_at(split_ix);
112 new_chunks.push(chunk);
113 text = remainder;
114 }
115
116 #[cfg(test)]
117 const PARALLEL_THRESHOLD: usize = 4;
118 #[cfg(not(test))]
119 const PARALLEL_THRESHOLD: usize = 4 * (2 * sum_tree::TREE_BASE);
120
121 if new_chunks.len() >= PARALLEL_THRESHOLD {
122 self.chunks
123 .par_extend(new_chunks.into_vec().into_par_iter().map(Chunk::new), &());
124 } else {
125 self.chunks
126 .extend(new_chunks.into_iter().map(Chunk::new), &());
127 }
128
129 self.check_invariants();
130 }
131
132 /// A copy of `push` specialized for working with large quantities of text.
133 fn push_large(&mut self, mut text: &str) {
134 // To avoid frequent reallocs when loading large swaths of file contents,
135 // we estimate worst-case `new_chunks` capacity;
136 // Chunk is a fixed-capacity buffer. If a character falls on
137 // chunk boundary, we push it off to the following chunk (thus leaving a small bit of capacity unfilled in current chunk).
138 // Worst-case chunk count when loading a file is then a case where every chunk ends up with that unused capacity.
139 // Since we're working with UTF-8, each character is at most 4 bytes wide. It follows then that the worst case is where
140 // a chunk ends with 3 bytes of a 4-byte character. These 3 bytes end up being stored in the following chunk, thus wasting
141 // 3 bytes of storage in current chunk.
142 // 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.
143 const MIN_CHUNK_SIZE: usize = chunk::MAX_BASE - 3;
144
145 // 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
146 // we're working with there is large.
147 let capacity = text.len().div_ceil(MIN_CHUNK_SIZE);
148 let mut new_chunks = Vec::with_capacity(capacity);
149
150 while !text.is_empty() {
151 let mut split_ix = cmp::min(chunk::MAX_BASE, text.len());
152 while !text.is_char_boundary(split_ix) {
153 split_ix -= 1;
154 }
155 let (chunk, remainder) = text.split_at(split_ix);
156 new_chunks.push(chunk);
157 text = remainder;
158 }
159
160 #[cfg(test)]
161 const PARALLEL_THRESHOLD: usize = 4;
162 #[cfg(not(test))]
163 const PARALLEL_THRESHOLD: usize = 4 * (2 * sum_tree::TREE_BASE);
164
165 if new_chunks.len() >= PARALLEL_THRESHOLD {
166 self.chunks
167 .par_extend(new_chunks.into_par_iter().map(Chunk::new), &());
168 } else {
169 self.chunks
170 .extend(new_chunks.into_iter().map(Chunk::new), &());
171 }
172
173 self.check_invariants();
174 }
175
176 fn push_chunk(&mut self, mut chunk: ChunkSlice) {
177 self.chunks.update_last(
178 |last_chunk| {
179 let split_ix = if last_chunk.text.len() + chunk.len() <= chunk::MAX_BASE {
180 chunk.len()
181 } else {
182 let mut split_ix = cmp::min(
183 chunk::MIN_BASE.saturating_sub(last_chunk.text.len()),
184 chunk.len(),
185 );
186 while !chunk.is_char_boundary(split_ix) {
187 split_ix += 1;
188 }
189 split_ix
190 };
191
192 let (suffix, remainder) = chunk.split_at(split_ix);
193 last_chunk.append(suffix);
194 chunk = remainder;
195 },
196 &(),
197 );
198
199 if !chunk.is_empty() {
200 self.chunks.push(chunk.into(), &());
201 }
202 }
203
204 pub fn push_front(&mut self, text: &str) {
205 let suffix = mem::replace(self, Rope::from(text));
206 self.append(suffix);
207 }
208
209 fn check_invariants(&self) {
210 #[cfg(test)]
211 {
212 // Ensure all chunks except maybe the last one are not underflowing.
213 // Allow some wiggle room for multibyte characters at chunk boundaries.
214 let mut chunks = self.chunks.cursor::<()>(&()).peekable();
215 while let Some(chunk) = chunks.next() {
216 if chunks.peek().is_some() {
217 assert!(chunk.text.len() + 3 >= chunk::MIN_BASE);
218 }
219 }
220 }
221 }
222
223 pub fn summary(&self) -> TextSummary {
224 self.chunks.summary().text
225 }
226
227 pub fn len(&self) -> usize {
228 self.chunks.extent(&())
229 }
230
231 pub fn is_empty(&self) -> bool {
232 self.len() == 0
233 }
234
235 pub fn max_point(&self) -> Point {
236 self.chunks.extent(&())
237 }
238
239 pub fn max_point_utf16(&self) -> PointUtf16 {
240 self.chunks.extent(&())
241 }
242
243 pub fn cursor(&self, offset: usize) -> Cursor<'_> {
244 Cursor::new(self, offset)
245 }
246
247 pub fn chars(&self) -> impl Iterator<Item = char> + '_ {
248 self.chars_at(0)
249 }
250
251 pub fn chars_at(&self, start: usize) -> impl Iterator<Item = char> + '_ {
252 self.chunks_in_range(start..self.len()).flat_map(str::chars)
253 }
254
255 pub fn reversed_chars_at(&self, start: usize) -> impl Iterator<Item = char> + '_ {
256 self.reversed_chunks_in_range(0..start)
257 .flat_map(|chunk| chunk.chars().rev())
258 }
259
260 pub fn bytes_in_range(&self, range: Range<usize>) -> Bytes<'_> {
261 Bytes::new(self, range, false)
262 }
263
264 pub fn reversed_bytes_in_range(&self, range: Range<usize>) -> Bytes<'_> {
265 Bytes::new(self, range, true)
266 }
267
268 pub fn chunks(&self) -> Chunks<'_> {
269 self.chunks_in_range(0..self.len())
270 }
271
272 pub fn chunks_in_range(&self, range: Range<usize>) -> Chunks<'_> {
273 Chunks::new(self, range, false)
274 }
275
276 pub fn reversed_chunks_in_range(&self, range: Range<usize>) -> Chunks<'_> {
277 Chunks::new(self, range, true)
278 }
279
280 pub fn offset_to_offset_utf16(&self, offset: usize) -> OffsetUtf16 {
281 if offset >= self.summary().len {
282 return self.summary().len_utf16;
283 }
284 let mut cursor = self.chunks.cursor::<Dimensions<usize, OffsetUtf16>>(&());
285 cursor.seek(&offset, Bias::Left);
286 let overshoot = offset - cursor.start().0;
287 cursor.start().1
288 + cursor.item().map_or(Default::default(), |chunk| {
289 chunk.as_slice().offset_to_offset_utf16(overshoot)
290 })
291 }
292
293 pub fn offset_utf16_to_offset(&self, offset: OffsetUtf16) -> usize {
294 if offset >= self.summary().len_utf16 {
295 return self.summary().len;
296 }
297 let mut cursor = self.chunks.cursor::<Dimensions<OffsetUtf16, usize>>(&());
298 cursor.seek(&offset, Bias::Left);
299 let overshoot = offset - cursor.start().0;
300 cursor.start().1
301 + cursor.item().map_or(Default::default(), |chunk| {
302 chunk.as_slice().offset_utf16_to_offset(overshoot)
303 })
304 }
305
306 pub fn offset_to_point(&self, offset: usize) -> Point {
307 if offset >= self.summary().len {
308 return self.summary().lines;
309 }
310 let mut cursor = self.chunks.cursor::<Dimensions<usize, Point>>(&());
311 cursor.seek(&offset, Bias::Left);
312 let overshoot = offset - cursor.start().0;
313 cursor.start().1
314 + cursor.item().map_or(Point::zero(), |chunk| {
315 chunk.as_slice().offset_to_point(overshoot)
316 })
317 }
318
319 pub fn offset_to_point_utf16(&self, offset: usize) -> PointUtf16 {
320 if offset >= self.summary().len {
321 return self.summary().lines_utf16();
322 }
323 let mut cursor = self.chunks.cursor::<Dimensions<usize, PointUtf16>>(&());
324 cursor.seek(&offset, Bias::Left);
325 let overshoot = offset - cursor.start().0;
326 cursor.start().1
327 + cursor.item().map_or(PointUtf16::zero(), |chunk| {
328 chunk.as_slice().offset_to_point_utf16(overshoot)
329 })
330 }
331
332 pub fn point_to_point_utf16(&self, point: Point) -> PointUtf16 {
333 if point >= self.summary().lines {
334 return self.summary().lines_utf16();
335 }
336 let mut cursor = self.chunks.cursor::<Dimensions<Point, PointUtf16>>(&());
337 cursor.seek(&point, Bias::Left);
338 let overshoot = point - cursor.start().0;
339 cursor.start().1
340 + cursor.item().map_or(PointUtf16::zero(), |chunk| {
341 chunk.as_slice().point_to_point_utf16(overshoot)
342 })
343 }
344
345 pub fn point_to_offset(&self, point: Point) -> usize {
346 if point >= self.summary().lines {
347 return self.summary().len;
348 }
349 let mut cursor = self.chunks.cursor::<Dimensions<Point, usize>>(&());
350 cursor.seek(&point, Bias::Left);
351 let overshoot = point - cursor.start().0;
352 cursor.start().1
353 + cursor
354 .item()
355 .map_or(0, |chunk| chunk.as_slice().point_to_offset(overshoot))
356 }
357
358 pub fn point_utf16_to_offset(&self, point: PointUtf16) -> usize {
359 self.point_utf16_to_offset_impl(point, false)
360 }
361
362 pub fn unclipped_point_utf16_to_offset(&self, point: Unclipped<PointUtf16>) -> usize {
363 self.point_utf16_to_offset_impl(point.0, true)
364 }
365
366 fn point_utf16_to_offset_impl(&self, point: PointUtf16, clip: bool) -> usize {
367 if point >= self.summary().lines_utf16() {
368 return self.summary().len;
369 }
370 let mut cursor = self.chunks.cursor::<Dimensions<PointUtf16, usize>>(&());
371 cursor.seek(&point, Bias::Left);
372 let overshoot = point - cursor.start().0;
373 cursor.start().1
374 + cursor.item().map_or(0, |chunk| {
375 chunk.as_slice().point_utf16_to_offset(overshoot, clip)
376 })
377 }
378
379 pub fn unclipped_point_utf16_to_point(&self, point: Unclipped<PointUtf16>) -> Point {
380 if point.0 >= self.summary().lines_utf16() {
381 return self.summary().lines;
382 }
383 let mut cursor = self.chunks.cursor::<Dimensions<PointUtf16, Point>>(&());
384 cursor.seek(&point.0, Bias::Left);
385 let overshoot = Unclipped(point.0 - cursor.start().0);
386 cursor.start().1
387 + cursor.item().map_or(Point::zero(), |chunk| {
388 chunk.as_slice().unclipped_point_utf16_to_point(overshoot)
389 })
390 }
391
392 pub fn clip_offset(&self, mut offset: usize, bias: Bias) -> usize {
393 let mut cursor = self.chunks.cursor::<usize>(&());
394 cursor.seek(&offset, Bias::Left);
395 if let Some(chunk) = cursor.item() {
396 let mut ix = offset - cursor.start();
397 while !chunk.text.is_char_boundary(ix) {
398 match bias {
399 Bias::Left => {
400 ix -= 1;
401 offset -= 1;
402 }
403 Bias::Right => {
404 ix += 1;
405 offset += 1;
406 }
407 }
408 }
409 offset
410 } else {
411 self.summary().len
412 }
413 }
414
415 pub fn clip_offset_utf16(&self, offset: OffsetUtf16, bias: Bias) -> OffsetUtf16 {
416 let mut cursor = self.chunks.cursor::<OffsetUtf16>(&());
417 cursor.seek(&offset, Bias::Right);
418 if let Some(chunk) = cursor.item() {
419 let overshoot = offset - cursor.start();
420 *cursor.start() + chunk.as_slice().clip_offset_utf16(overshoot, bias)
421 } else {
422 self.summary().len_utf16
423 }
424 }
425
426 pub fn clip_point(&self, point: Point, bias: Bias) -> Point {
427 let mut cursor = self.chunks.cursor::<Point>(&());
428 cursor.seek(&point, Bias::Right);
429 if let Some(chunk) = cursor.item() {
430 let overshoot = point - cursor.start();
431 *cursor.start() + chunk.as_slice().clip_point(overshoot, bias)
432 } else {
433 self.summary().lines
434 }
435 }
436
437 pub fn clip_point_utf16(&self, point: Unclipped<PointUtf16>, bias: Bias) -> PointUtf16 {
438 let mut cursor = self.chunks.cursor::<PointUtf16>(&());
439 cursor.seek(&point.0, Bias::Right);
440 if let Some(chunk) = cursor.item() {
441 let overshoot = Unclipped(point.0 - cursor.start());
442 *cursor.start() + chunk.as_slice().clip_point_utf16(overshoot, bias)
443 } else {
444 self.summary().lines_utf16()
445 }
446 }
447
448 pub fn line_len(&self, row: u32) -> u32 {
449 self.clip_point(Point::new(row, u32::MAX), Bias::Left)
450 .column
451 }
452}
453
454impl<'a> From<&'a str> for Rope {
455 fn from(text: &'a str) -> Self {
456 let mut rope = Self::new();
457 rope.push(text);
458 rope
459 }
460}
461
462impl<'a> FromIterator<&'a str> for Rope {
463 fn from_iter<T: IntoIterator<Item = &'a str>>(iter: T) -> Self {
464 let mut rope = Rope::new();
465 for chunk in iter {
466 rope.push(chunk);
467 }
468 rope
469 }
470}
471
472impl From<String> for Rope {
473 #[inline(always)]
474 fn from(text: String) -> Self {
475 Rope::from(text.as_str())
476 }
477}
478
479impl From<&String> for Rope {
480 #[inline(always)]
481 fn from(text: &String) -> Self {
482 Rope::from(text.as_str())
483 }
484}
485
486impl fmt::Display for Rope {
487 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
488 for chunk in self.chunks() {
489 write!(f, "{}", chunk)?;
490 }
491 Ok(())
492 }
493}
494
495impl fmt::Debug for Rope {
496 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
497 use std::fmt::Write as _;
498
499 write!(f, "\"")?;
500 let mut format_string = String::new();
501 for chunk in self.chunks() {
502 write!(&mut format_string, "{:?}", chunk)?;
503 write!(f, "{}", &format_string[1..format_string.len() - 1])?;
504 format_string.clear();
505 }
506 write!(f, "\"")?;
507 Ok(())
508 }
509}
510
511pub struct Cursor<'a> {
512 rope: &'a Rope,
513 chunks: sum_tree::Cursor<'a, Chunk, usize>,
514 offset: usize,
515}
516
517impl<'a> Cursor<'a> {
518 pub fn new(rope: &'a Rope, offset: usize) -> Self {
519 let mut chunks = rope.chunks.cursor(&());
520 chunks.seek(&offset, Bias::Right);
521 Self {
522 rope,
523 chunks,
524 offset,
525 }
526 }
527
528 pub fn seek_forward(&mut self, end_offset: usize) {
529 debug_assert!(end_offset >= self.offset);
530
531 self.chunks.seek_forward(&end_offset, Bias::Right);
532 self.offset = end_offset;
533 }
534
535 pub fn slice(&mut self, end_offset: usize) -> Rope {
536 debug_assert!(
537 end_offset >= self.offset,
538 "cannot slice backwards from {} to {}",
539 self.offset,
540 end_offset
541 );
542
543 let mut slice = Rope::new();
544 if let Some(start_chunk) = self.chunks.item() {
545 let start_ix = self.offset - self.chunks.start();
546 let end_ix = cmp::min(end_offset, self.chunks.end()) - self.chunks.start();
547 slice.push_chunk(start_chunk.slice(start_ix..end_ix));
548 }
549
550 if end_offset > self.chunks.end() {
551 self.chunks.next();
552 slice.append(Rope {
553 chunks: self.chunks.slice(&end_offset, Bias::Right),
554 });
555 if let Some(end_chunk) = self.chunks.item() {
556 let end_ix = end_offset - self.chunks.start();
557 slice.push_chunk(end_chunk.slice(0..end_ix));
558 }
559 }
560
561 self.offset = end_offset;
562 slice
563 }
564
565 pub fn summary<D: TextDimension>(&mut self, end_offset: usize) -> D {
566 debug_assert!(end_offset >= self.offset);
567
568 let mut summary = D::zero(&());
569 if let Some(start_chunk) = self.chunks.item() {
570 let start_ix = self.offset - self.chunks.start();
571 let end_ix = cmp::min(end_offset, self.chunks.end()) - self.chunks.start();
572 summary.add_assign(&D::from_chunk(start_chunk.slice(start_ix..end_ix)));
573 }
574
575 if end_offset > self.chunks.end() {
576 self.chunks.next();
577 summary.add_assign(&self.chunks.summary(&end_offset, Bias::Right));
578 if let Some(end_chunk) = self.chunks.item() {
579 let end_ix = end_offset - self.chunks.start();
580 summary.add_assign(&D::from_chunk(end_chunk.slice(0..end_ix)));
581 }
582 }
583
584 self.offset = end_offset;
585 summary
586 }
587
588 pub fn suffix(mut self) -> Rope {
589 self.slice(self.rope.chunks.extent(&()))
590 }
591
592 pub fn offset(&self) -> usize {
593 self.offset
594 }
595}
596
597#[derive(Clone)]
598pub struct Chunks<'a> {
599 chunks: sum_tree::Cursor<'a, Chunk, usize>,
600 range: Range<usize>,
601 offset: usize,
602 reversed: bool,
603}
604
605impl<'a> Chunks<'a> {
606 pub fn new(rope: &'a Rope, range: Range<usize>, reversed: bool) -> Self {
607 let mut chunks = rope.chunks.cursor(&());
608 let offset = if reversed {
609 chunks.seek(&range.end, Bias::Left);
610 range.end
611 } else {
612 chunks.seek(&range.start, Bias::Right);
613 range.start
614 };
615 Self {
616 chunks,
617 range,
618 offset,
619 reversed,
620 }
621 }
622
623 fn offset_is_valid(&self) -> bool {
624 if self.reversed {
625 if self.offset <= self.range.start || self.offset > self.range.end {
626 return false;
627 }
628 } else if self.offset < self.range.start || self.offset >= self.range.end {
629 return false;
630 }
631
632 true
633 }
634
635 pub fn offset(&self) -> usize {
636 self.offset
637 }
638
639 pub fn seek(&mut self, mut offset: usize) {
640 offset = offset.clamp(self.range.start, self.range.end);
641
642 let bias = if self.reversed {
643 Bias::Left
644 } else {
645 Bias::Right
646 };
647
648 if offset >= self.chunks.end() {
649 self.chunks.seek_forward(&offset, bias);
650 } else {
651 self.chunks.seek(&offset, bias);
652 }
653
654 self.offset = offset;
655 }
656
657 pub fn set_range(&mut self, range: Range<usize>) {
658 self.range = range.clone();
659 self.seek(range.start);
660 }
661
662 /// Moves this cursor to the start of the next line in the rope.
663 ///
664 /// This method advances the cursor to the beginning of the next line.
665 /// If the cursor is already at the end of the rope, this method does nothing.
666 /// Reversed chunks iterators are not currently supported and will panic.
667 ///
668 /// Returns `true` if the cursor was successfully moved to the next line start,
669 /// or `false` if the cursor was already at the end of the rope.
670 pub fn next_line(&mut self) -> bool {
671 assert!(!self.reversed);
672
673 let mut found = false;
674 if let Some(chunk) = self.peek() {
675 if let Some(newline_ix) = chunk.find('\n') {
676 self.offset += newline_ix + 1;
677 found = self.offset <= self.range.end;
678 } else {
679 self.chunks
680 .search_forward(|summary| summary.text.lines.row > 0);
681 self.offset = *self.chunks.start();
682
683 if let Some(newline_ix) = self.peek().and_then(|chunk| chunk.find('\n')) {
684 self.offset += newline_ix + 1;
685 found = self.offset <= self.range.end;
686 } else {
687 self.offset = self.chunks.end();
688 }
689 }
690
691 if self.offset == self.chunks.end() {
692 self.next();
693 }
694 }
695
696 if self.offset > self.range.end {
697 self.offset = cmp::min(self.offset, self.range.end);
698 self.chunks.seek(&self.offset, Bias::Right);
699 }
700
701 found
702 }
703
704 /// Move this cursor to the preceding position in the rope that starts a new line.
705 /// Reversed chunks iterators are not currently supported and will panic.
706 ///
707 /// If this cursor is not on the start of a line, it will be moved to the start of
708 /// its current line. Otherwise it will be moved to the start of the previous line.
709 /// It updates the cursor's position and returns true if a previous line was found,
710 /// or false if the cursor was already at the start of the rope.
711 pub fn prev_line(&mut self) -> bool {
712 assert!(!self.reversed);
713
714 let initial_offset = self.offset;
715
716 if self.offset == *self.chunks.start() {
717 self.chunks.prev();
718 }
719
720 if let Some(chunk) = self.chunks.item() {
721 let mut end_ix = self.offset - *self.chunks.start();
722 if chunk.text.as_bytes()[end_ix - 1] == b'\n' {
723 end_ix -= 1;
724 }
725
726 if let Some(newline_ix) = chunk.text[..end_ix].rfind('\n') {
727 self.offset = *self.chunks.start() + newline_ix + 1;
728 if self.offset_is_valid() {
729 return true;
730 }
731 }
732 }
733
734 self.chunks
735 .search_backward(|summary| summary.text.lines.row > 0);
736 self.offset = *self.chunks.start();
737 if let Some(chunk) = self.chunks.item()
738 && let Some(newline_ix) = chunk.text.rfind('\n')
739 {
740 self.offset += newline_ix + 1;
741 if self.offset_is_valid() {
742 if self.offset == self.chunks.end() {
743 self.chunks.next();
744 }
745
746 return true;
747 }
748 }
749
750 if !self.offset_is_valid() || self.chunks.item().is_none() {
751 self.offset = self.range.start;
752 self.chunks.seek(&self.offset, Bias::Right);
753 }
754
755 self.offset < initial_offset && self.offset == 0
756 }
757
758 pub fn peek(&self) -> Option<&'a str> {
759 if !self.offset_is_valid() {
760 return None;
761 }
762
763 let chunk = self.chunks.item()?;
764 let chunk_start = *self.chunks.start();
765 let slice_range = if self.reversed {
766 let slice_start = cmp::max(chunk_start, self.range.start) - chunk_start;
767 let slice_end = self.offset - chunk_start;
768 slice_start..slice_end
769 } else {
770 let slice_start = self.offset - chunk_start;
771 let slice_end = cmp::min(self.chunks.end(), self.range.end) - chunk_start;
772 slice_start..slice_end
773 };
774
775 Some(&chunk.text[slice_range])
776 }
777
778 pub fn lines(self) -> Lines<'a> {
779 let reversed = self.reversed;
780 Lines {
781 chunks: self,
782 current_line: String::new(),
783 done: false,
784 reversed,
785 }
786 }
787
788 pub fn equals_str(&self, other: &str) -> bool {
789 let chunk = self.clone();
790 if chunk.reversed {
791 let mut offset = other.len();
792 for chunk in chunk {
793 if other[0..offset].ends_with(chunk) {
794 offset -= chunk.len();
795 } else {
796 return false;
797 }
798 }
799 if offset != 0 {
800 return false;
801 }
802 } else {
803 let mut offset = 0;
804 for chunk in chunk {
805 if offset >= other.len() {
806 return false;
807 }
808 if other[offset..].starts_with(chunk) {
809 offset += chunk.len();
810 } else {
811 return false;
812 }
813 }
814 if offset != other.len() {
815 return false;
816 }
817 }
818
819 true
820 }
821}
822
823impl<'a> Iterator for Chunks<'a> {
824 type Item = &'a str;
825
826 fn next(&mut self) -> Option<Self::Item> {
827 let chunk = self.peek()?;
828 if self.reversed {
829 self.offset -= chunk.len();
830 if self.offset <= *self.chunks.start() {
831 self.chunks.prev();
832 }
833 } else {
834 self.offset += chunk.len();
835 if self.offset >= self.chunks.end() {
836 self.chunks.next();
837 }
838 }
839
840 Some(chunk)
841 }
842}
843
844pub struct Bytes<'a> {
845 chunks: sum_tree::Cursor<'a, Chunk, usize>,
846 range: Range<usize>,
847 reversed: bool,
848}
849
850impl<'a> Bytes<'a> {
851 pub fn new(rope: &'a Rope, range: Range<usize>, reversed: bool) -> Self {
852 let mut chunks = rope.chunks.cursor(&());
853 if reversed {
854 chunks.seek(&range.end, Bias::Left);
855 } else {
856 chunks.seek(&range.start, Bias::Right);
857 }
858 Self {
859 chunks,
860 range,
861 reversed,
862 }
863 }
864
865 pub fn peek(&self) -> Option<&'a [u8]> {
866 let chunk = self.chunks.item()?;
867 if self.reversed && self.range.start >= self.chunks.end() {
868 return None;
869 }
870 let chunk_start = *self.chunks.start();
871 if self.range.end <= chunk_start {
872 return None;
873 }
874 let start = self.range.start.saturating_sub(chunk_start);
875 let end = self.range.end - chunk_start;
876 Some(&chunk.text.as_bytes()[start..chunk.text.len().min(end)])
877 }
878}
879
880impl<'a> Iterator for Bytes<'a> {
881 type Item = &'a [u8];
882
883 fn next(&mut self) -> Option<Self::Item> {
884 let result = self.peek();
885 if result.is_some() {
886 if self.reversed {
887 self.chunks.prev();
888 } else {
889 self.chunks.next();
890 }
891 }
892 result
893 }
894}
895
896impl io::Read for Bytes<'_> {
897 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
898 if let Some(chunk) = self.peek() {
899 let len = cmp::min(buf.len(), chunk.len());
900 if self.reversed {
901 buf[..len].copy_from_slice(&chunk[chunk.len() - len..]);
902 buf[..len].reverse();
903 self.range.end -= len;
904 } else {
905 buf[..len].copy_from_slice(&chunk[..len]);
906 self.range.start += len;
907 }
908
909 if len == chunk.len() {
910 if self.reversed {
911 self.chunks.prev();
912 } else {
913 self.chunks.next();
914 }
915 }
916 Ok(len)
917 } else {
918 Ok(0)
919 }
920 }
921}
922
923pub struct Lines<'a> {
924 chunks: Chunks<'a>,
925 current_line: String,
926 done: bool,
927 reversed: bool,
928}
929
930impl Lines<'_> {
931 pub fn next(&mut self) -> Option<&str> {
932 if self.done {
933 return None;
934 }
935
936 self.current_line.clear();
937
938 while let Some(chunk) = self.chunks.peek() {
939 let chunk_lines = chunk.split('\n');
940 if self.reversed {
941 let mut chunk_lines = chunk_lines.rev().peekable();
942 if let Some(chunk_line) = chunk_lines.next() {
943 let done = chunk_lines.peek().is_some();
944 if done {
945 self.chunks
946 .seek(self.chunks.offset() - chunk_line.len() - "\n".len());
947 if self.current_line.is_empty() {
948 return Some(chunk_line);
949 }
950 }
951 self.current_line.insert_str(0, chunk_line);
952 if done {
953 return Some(&self.current_line);
954 }
955 }
956 } else {
957 let mut chunk_lines = chunk_lines.peekable();
958 if let Some(chunk_line) = chunk_lines.next() {
959 let done = chunk_lines.peek().is_some();
960 if done {
961 self.chunks
962 .seek(self.chunks.offset() + chunk_line.len() + "\n".len());
963 if self.current_line.is_empty() {
964 return Some(chunk_line);
965 }
966 }
967 self.current_line.push_str(chunk_line);
968 if done {
969 return Some(&self.current_line);
970 }
971 }
972 }
973
974 self.chunks.next();
975 }
976
977 self.done = true;
978 Some(&self.current_line)
979 }
980
981 pub fn seek(&mut self, offset: usize) {
982 self.chunks.seek(offset);
983 self.current_line.clear();
984 self.done = false;
985 }
986
987 pub fn offset(&self) -> usize {
988 self.chunks.offset()
989 }
990}
991
992impl sum_tree::Item for Chunk {
993 type Summary = ChunkSummary;
994
995 fn summary(&self, _cx: &()) -> Self::Summary {
996 ChunkSummary {
997 text: self.as_slice().text_summary(),
998 }
999 }
1000}
1001
1002#[derive(Clone, Debug, Default, Eq, PartialEq)]
1003pub struct ChunkSummary {
1004 text: TextSummary,
1005}
1006
1007impl sum_tree::Summary for ChunkSummary {
1008 type Context = ();
1009
1010 fn zero(_cx: &()) -> Self {
1011 Default::default()
1012 }
1013
1014 fn add_summary(&mut self, summary: &Self, _: &()) {
1015 self.text += &summary.text;
1016 }
1017}
1018
1019/// Summary of a string of text.
1020#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
1021pub struct TextSummary {
1022 /// Length in bytes.
1023 pub len: usize,
1024 /// Length in UTF-8.
1025 pub chars: usize,
1026 /// Length in UTF-16 code units
1027 pub len_utf16: OffsetUtf16,
1028 /// A point representing the number of lines and the length of the last line.
1029 ///
1030 /// In other words, it marks the point after the last byte in the text, (if
1031 /// EOF was a character, this would be its position).
1032 pub lines: Point,
1033 /// How many `char`s are in the first line
1034 pub first_line_chars: u32,
1035 /// How many `char`s are in the last line
1036 pub last_line_chars: u32,
1037 /// How many UTF-16 code units are in the last line
1038 pub last_line_len_utf16: u32,
1039 /// The row idx of the longest row
1040 pub longest_row: u32,
1041 /// How many `char`s are in the longest row
1042 pub longest_row_chars: u32,
1043}
1044
1045impl TextSummary {
1046 pub fn lines_utf16(&self) -> PointUtf16 {
1047 PointUtf16 {
1048 row: self.lines.row,
1049 column: self.last_line_len_utf16,
1050 }
1051 }
1052
1053 pub fn newline() -> Self {
1054 Self {
1055 len: 1,
1056 chars: 1,
1057 len_utf16: OffsetUtf16(1),
1058 first_line_chars: 0,
1059 last_line_chars: 0,
1060 last_line_len_utf16: 0,
1061 lines: Point::new(1, 0),
1062 longest_row: 0,
1063 longest_row_chars: 0,
1064 }
1065 }
1066
1067 pub fn add_newline(&mut self) {
1068 self.len += 1;
1069 self.len_utf16 += OffsetUtf16(self.len_utf16.0 + 1);
1070 self.last_line_chars = 0;
1071 self.last_line_len_utf16 = 0;
1072 self.lines += Point::new(1, 0);
1073 }
1074}
1075
1076impl<'a> From<&'a str> for TextSummary {
1077 fn from(text: &'a str) -> Self {
1078 let mut len_utf16 = OffsetUtf16(0);
1079 let mut lines = Point::new(0, 0);
1080 let mut first_line_chars = 0;
1081 let mut last_line_chars = 0;
1082 let mut last_line_len_utf16 = 0;
1083 let mut longest_row = 0;
1084 let mut longest_row_chars = 0;
1085 let mut chars = 0;
1086 for c in text.chars() {
1087 chars += 1;
1088 len_utf16.0 += c.len_utf16();
1089
1090 if c == '\n' {
1091 lines += Point::new(1, 0);
1092 last_line_len_utf16 = 0;
1093 last_line_chars = 0;
1094 } else {
1095 lines.column += c.len_utf8() as u32;
1096 last_line_len_utf16 += c.len_utf16() as u32;
1097 last_line_chars += 1;
1098 }
1099
1100 if lines.row == 0 {
1101 first_line_chars = last_line_chars;
1102 }
1103
1104 if last_line_chars > longest_row_chars {
1105 longest_row = lines.row;
1106 longest_row_chars = last_line_chars;
1107 }
1108 }
1109
1110 TextSummary {
1111 len: text.len(),
1112 chars,
1113 len_utf16,
1114 lines,
1115 first_line_chars,
1116 last_line_chars,
1117 last_line_len_utf16,
1118 longest_row,
1119 longest_row_chars,
1120 }
1121 }
1122}
1123
1124impl sum_tree::Summary for TextSummary {
1125 type Context = ();
1126
1127 fn zero(_cx: &()) -> Self {
1128 Default::default()
1129 }
1130
1131 fn add_summary(&mut self, summary: &Self, _: &Self::Context) {
1132 *self += summary;
1133 }
1134}
1135
1136impl ops::Add<Self> for TextSummary {
1137 type Output = Self;
1138
1139 fn add(mut self, rhs: Self) -> Self::Output {
1140 AddAssign::add_assign(&mut self, &rhs);
1141 self
1142 }
1143}
1144
1145impl<'a> ops::AddAssign<&'a Self> for TextSummary {
1146 fn add_assign(&mut self, other: &'a Self) {
1147 let joined_chars = self.last_line_chars + other.first_line_chars;
1148 if joined_chars > self.longest_row_chars {
1149 self.longest_row = self.lines.row;
1150 self.longest_row_chars = joined_chars;
1151 }
1152 if other.longest_row_chars > self.longest_row_chars {
1153 self.longest_row = self.lines.row + other.longest_row;
1154 self.longest_row_chars = other.longest_row_chars;
1155 }
1156
1157 if self.lines.row == 0 {
1158 self.first_line_chars += other.first_line_chars;
1159 }
1160
1161 if other.lines.row == 0 {
1162 self.last_line_chars += other.first_line_chars;
1163 self.last_line_len_utf16 += other.last_line_len_utf16;
1164 } else {
1165 self.last_line_chars = other.last_line_chars;
1166 self.last_line_len_utf16 = other.last_line_len_utf16;
1167 }
1168
1169 self.chars += other.chars;
1170 self.len += other.len;
1171 self.len_utf16 += other.len_utf16;
1172 self.lines += other.lines;
1173 }
1174}
1175
1176impl ops::AddAssign<Self> for TextSummary {
1177 fn add_assign(&mut self, other: Self) {
1178 *self += &other;
1179 }
1180}
1181
1182pub trait TextDimension:
1183 'static + Clone + Copy + Default + for<'a> Dimension<'a, ChunkSummary> + std::fmt::Debug
1184{
1185 fn from_text_summary(summary: &TextSummary) -> Self;
1186 fn from_chunk(chunk: ChunkSlice) -> Self;
1187 fn add_assign(&mut self, other: &Self);
1188}
1189
1190impl<D1: TextDimension, D2: TextDimension> TextDimension for Dimensions<D1, D2, ()> {
1191 fn from_text_summary(summary: &TextSummary) -> Self {
1192 Dimensions(
1193 D1::from_text_summary(summary),
1194 D2::from_text_summary(summary),
1195 (),
1196 )
1197 }
1198
1199 fn from_chunk(chunk: ChunkSlice) -> Self {
1200 Dimensions(D1::from_chunk(chunk), D2::from_chunk(chunk), ())
1201 }
1202
1203 fn add_assign(&mut self, other: &Self) {
1204 self.0.add_assign(&other.0);
1205 self.1.add_assign(&other.1);
1206 }
1207}
1208
1209impl<'a> sum_tree::Dimension<'a, ChunkSummary> for TextSummary {
1210 fn zero(_cx: &()) -> Self {
1211 Default::default()
1212 }
1213
1214 fn add_summary(&mut self, summary: &'a ChunkSummary, _: &()) {
1215 *self += &summary.text;
1216 }
1217}
1218
1219impl TextDimension for TextSummary {
1220 fn from_text_summary(summary: &TextSummary) -> Self {
1221 *summary
1222 }
1223
1224 fn from_chunk(chunk: ChunkSlice) -> Self {
1225 chunk.text_summary()
1226 }
1227
1228 fn add_assign(&mut self, other: &Self) {
1229 *self += other;
1230 }
1231}
1232
1233impl<'a> sum_tree::Dimension<'a, ChunkSummary> for usize {
1234 fn zero(_cx: &()) -> Self {
1235 Default::default()
1236 }
1237
1238 fn add_summary(&mut self, summary: &'a ChunkSummary, _: &()) {
1239 *self += summary.text.len;
1240 }
1241}
1242
1243impl TextDimension for usize {
1244 fn from_text_summary(summary: &TextSummary) -> Self {
1245 summary.len
1246 }
1247
1248 fn from_chunk(chunk: ChunkSlice) -> Self {
1249 chunk.len()
1250 }
1251
1252 fn add_assign(&mut self, other: &Self) {
1253 *self += other;
1254 }
1255}
1256
1257impl<'a> sum_tree::Dimension<'a, ChunkSummary> for OffsetUtf16 {
1258 fn zero(_cx: &()) -> Self {
1259 Default::default()
1260 }
1261
1262 fn add_summary(&mut self, summary: &'a ChunkSummary, _: &()) {
1263 *self += summary.text.len_utf16;
1264 }
1265}
1266
1267impl TextDimension for OffsetUtf16 {
1268 fn from_text_summary(summary: &TextSummary) -> Self {
1269 summary.len_utf16
1270 }
1271
1272 fn from_chunk(chunk: ChunkSlice) -> Self {
1273 chunk.len_utf16()
1274 }
1275
1276 fn add_assign(&mut self, other: &Self) {
1277 *self += other;
1278 }
1279}
1280
1281impl<'a> sum_tree::Dimension<'a, ChunkSummary> for Point {
1282 fn zero(_cx: &()) -> Self {
1283 Default::default()
1284 }
1285
1286 fn add_summary(&mut self, summary: &'a ChunkSummary, _: &()) {
1287 *self += summary.text.lines;
1288 }
1289}
1290
1291impl TextDimension for Point {
1292 fn from_text_summary(summary: &TextSummary) -> Self {
1293 summary.lines
1294 }
1295
1296 fn from_chunk(chunk: ChunkSlice) -> Self {
1297 chunk.lines()
1298 }
1299
1300 fn add_assign(&mut self, other: &Self) {
1301 *self += other;
1302 }
1303}
1304
1305impl<'a> sum_tree::Dimension<'a, ChunkSummary> for PointUtf16 {
1306 fn zero(_cx: &()) -> Self {
1307 Default::default()
1308 }
1309
1310 fn add_summary(&mut self, summary: &'a ChunkSummary, _: &()) {
1311 *self += summary.text.lines_utf16();
1312 }
1313}
1314
1315impl TextDimension for PointUtf16 {
1316 fn from_text_summary(summary: &TextSummary) -> Self {
1317 summary.lines_utf16()
1318 }
1319
1320 fn from_chunk(chunk: ChunkSlice) -> Self {
1321 PointUtf16 {
1322 row: chunk.lines().row,
1323 column: chunk.last_line_len_utf16(),
1324 }
1325 }
1326
1327 fn add_assign(&mut self, other: &Self) {
1328 *self += other;
1329 }
1330}
1331
1332/// A pair of text dimensions in which only the first dimension is used for comparison,
1333/// but both dimensions are updated during addition and subtraction.
1334#[derive(Clone, Copy, Debug)]
1335pub struct DimensionPair<K, V> {
1336 pub key: K,
1337 pub value: Option<V>,
1338}
1339
1340impl<K: Default, V: Default> Default for DimensionPair<K, V> {
1341 fn default() -> Self {
1342 Self {
1343 key: Default::default(),
1344 value: Some(Default::default()),
1345 }
1346 }
1347}
1348
1349impl<K, V> cmp::Ord for DimensionPair<K, V>
1350where
1351 K: cmp::Ord,
1352{
1353 fn cmp(&self, other: &Self) -> cmp::Ordering {
1354 self.key.cmp(&other.key)
1355 }
1356}
1357
1358impl<K, V> cmp::PartialOrd for DimensionPair<K, V>
1359where
1360 K: cmp::PartialOrd,
1361{
1362 fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
1363 self.key.partial_cmp(&other.key)
1364 }
1365}
1366
1367impl<K, V> cmp::PartialEq for DimensionPair<K, V>
1368where
1369 K: cmp::PartialEq,
1370{
1371 fn eq(&self, other: &Self) -> bool {
1372 self.key.eq(&other.key)
1373 }
1374}
1375
1376impl<K, V> ops::Sub for DimensionPair<K, V>
1377where
1378 K: ops::Sub<K, Output = K>,
1379 V: ops::Sub<V, Output = V>,
1380{
1381 type Output = Self;
1382
1383 fn sub(self, rhs: Self) -> Self::Output {
1384 Self {
1385 key: self.key - rhs.key,
1386 value: self.value.zip(rhs.value).map(|(a, b)| a - b),
1387 }
1388 }
1389}
1390
1391impl<K, V> cmp::Eq for DimensionPair<K, V> where K: cmp::Eq {}
1392
1393impl<'a, K, V> sum_tree::Dimension<'a, ChunkSummary> for DimensionPair<K, V>
1394where
1395 K: sum_tree::Dimension<'a, ChunkSummary>,
1396 V: sum_tree::Dimension<'a, ChunkSummary>,
1397{
1398 fn zero(_cx: &()) -> Self {
1399 Self {
1400 key: K::zero(_cx),
1401 value: Some(V::zero(_cx)),
1402 }
1403 }
1404
1405 fn add_summary(&mut self, summary: &'a ChunkSummary, _cx: &()) {
1406 self.key.add_summary(summary, _cx);
1407 if let Some(value) = &mut self.value {
1408 value.add_summary(summary, _cx);
1409 }
1410 }
1411}
1412
1413impl<K, V> TextDimension for DimensionPair<K, V>
1414where
1415 K: TextDimension,
1416 V: TextDimension,
1417{
1418 fn add_assign(&mut self, other: &Self) {
1419 self.key.add_assign(&other.key);
1420 if let Some(value) = &mut self.value {
1421 if let Some(other_value) = other.value.as_ref() {
1422 value.add_assign(other_value);
1423 } else {
1424 self.value.take();
1425 }
1426 }
1427 }
1428
1429 fn from_chunk(chunk: ChunkSlice) -> Self {
1430 Self {
1431 key: K::from_chunk(chunk),
1432 value: Some(V::from_chunk(chunk)),
1433 }
1434 }
1435
1436 fn from_text_summary(summary: &TextSummary) -> Self {
1437 Self {
1438 key: K::from_text_summary(summary),
1439 value: Some(V::from_text_summary(summary)),
1440 }
1441 }
1442}
1443
1444#[cfg(test)]
1445mod tests {
1446 use super::*;
1447 use Bias::{Left, Right};
1448 use rand::prelude::*;
1449 use std::{cmp::Ordering, env, io::Read};
1450 use util::RandomCharIter;
1451
1452 #[ctor::ctor]
1453 fn init_logger() {
1454 zlog::init_test();
1455 }
1456
1457 #[test]
1458 fn test_all_4_byte_chars() {
1459 let mut rope = Rope::new();
1460 let text = "🏀".repeat(256);
1461 rope.push(&text);
1462 assert_eq!(rope.text(), text);
1463 }
1464
1465 #[test]
1466 fn test_clip() {
1467 let rope = Rope::from("🧘");
1468
1469 assert_eq!(rope.clip_offset(1, Bias::Left), 0);
1470 assert_eq!(rope.clip_offset(1, Bias::Right), 4);
1471 assert_eq!(rope.clip_offset(5, Bias::Right), 4);
1472
1473 assert_eq!(
1474 rope.clip_point(Point::new(0, 1), Bias::Left),
1475 Point::new(0, 0)
1476 );
1477 assert_eq!(
1478 rope.clip_point(Point::new(0, 1), Bias::Right),
1479 Point::new(0, 4)
1480 );
1481 assert_eq!(
1482 rope.clip_point(Point::new(0, 5), Bias::Right),
1483 Point::new(0, 4)
1484 );
1485
1486 assert_eq!(
1487 rope.clip_point_utf16(Unclipped(PointUtf16::new(0, 1)), Bias::Left),
1488 PointUtf16::new(0, 0)
1489 );
1490 assert_eq!(
1491 rope.clip_point_utf16(Unclipped(PointUtf16::new(0, 1)), Bias::Right),
1492 PointUtf16::new(0, 2)
1493 );
1494 assert_eq!(
1495 rope.clip_point_utf16(Unclipped(PointUtf16::new(0, 3)), Bias::Right),
1496 PointUtf16::new(0, 2)
1497 );
1498
1499 assert_eq!(
1500 rope.clip_offset_utf16(OffsetUtf16(1), Bias::Left),
1501 OffsetUtf16(0)
1502 );
1503 assert_eq!(
1504 rope.clip_offset_utf16(OffsetUtf16(1), Bias::Right),
1505 OffsetUtf16(2)
1506 );
1507 assert_eq!(
1508 rope.clip_offset_utf16(OffsetUtf16(3), Bias::Right),
1509 OffsetUtf16(2)
1510 );
1511 }
1512
1513 #[test]
1514 fn test_prev_next_line() {
1515 let rope = Rope::from("abc\ndef\nghi\njkl");
1516
1517 let mut chunks = rope.chunks();
1518 assert_eq!(chunks.peek().unwrap().chars().next().unwrap(), 'a');
1519
1520 assert!(chunks.next_line());
1521 assert_eq!(chunks.peek().unwrap().chars().next().unwrap(), 'd');
1522
1523 assert!(chunks.next_line());
1524 assert_eq!(chunks.peek().unwrap().chars().next().unwrap(), 'g');
1525
1526 assert!(chunks.next_line());
1527 assert_eq!(chunks.peek().unwrap().chars().next().unwrap(), 'j');
1528
1529 assert!(!chunks.next_line());
1530 assert_eq!(chunks.peek(), None);
1531
1532 assert!(chunks.prev_line());
1533 assert_eq!(chunks.peek().unwrap().chars().next().unwrap(), 'j');
1534
1535 assert!(chunks.prev_line());
1536 assert_eq!(chunks.peek().unwrap().chars().next().unwrap(), 'g');
1537
1538 assert!(chunks.prev_line());
1539 assert_eq!(chunks.peek().unwrap().chars().next().unwrap(), 'd');
1540
1541 assert!(chunks.prev_line());
1542 assert_eq!(chunks.peek().unwrap().chars().next().unwrap(), 'a');
1543
1544 assert!(!chunks.prev_line());
1545 assert_eq!(chunks.peek().unwrap().chars().next().unwrap(), 'a');
1546
1547 // Only return true when the cursor has moved to the start of a line
1548 let mut chunks = rope.chunks_in_range(5..7);
1549 chunks.seek(6);
1550 assert!(!chunks.prev_line());
1551 assert_eq!(chunks.peek().unwrap().chars().next().unwrap(), 'e');
1552
1553 assert!(!chunks.next_line());
1554 assert_eq!(chunks.peek(), None);
1555 }
1556
1557 #[test]
1558 fn test_lines() {
1559 let rope = Rope::from("abc\ndefg\nhi");
1560 let mut lines = rope.chunks().lines();
1561 assert_eq!(lines.next(), Some("abc"));
1562 assert_eq!(lines.next(), Some("defg"));
1563 assert_eq!(lines.next(), Some("hi"));
1564 assert_eq!(lines.next(), None);
1565
1566 let rope = Rope::from("abc\ndefg\nhi\n");
1567 let mut lines = rope.chunks().lines();
1568 assert_eq!(lines.next(), Some("abc"));
1569 assert_eq!(lines.next(), Some("defg"));
1570 assert_eq!(lines.next(), Some("hi"));
1571 assert_eq!(lines.next(), Some(""));
1572 assert_eq!(lines.next(), None);
1573
1574 let rope = Rope::from("abc\ndefg\nhi");
1575 let mut lines = rope.reversed_chunks_in_range(0..rope.len()).lines();
1576 assert_eq!(lines.next(), Some("hi"));
1577 assert_eq!(lines.next(), Some("defg"));
1578 assert_eq!(lines.next(), Some("abc"));
1579 assert_eq!(lines.next(), None);
1580
1581 let rope = Rope::from("abc\ndefg\nhi\n");
1582 let mut lines = rope.reversed_chunks_in_range(0..rope.len()).lines();
1583 assert_eq!(lines.next(), Some(""));
1584 assert_eq!(lines.next(), Some("hi"));
1585 assert_eq!(lines.next(), Some("defg"));
1586 assert_eq!(lines.next(), Some("abc"));
1587 assert_eq!(lines.next(), None);
1588
1589 let rope = Rope::from("abc\nlonger line test\nhi");
1590 let mut lines = rope.chunks().lines();
1591 assert_eq!(lines.next(), Some("abc"));
1592 assert_eq!(lines.next(), Some("longer line test"));
1593 assert_eq!(lines.next(), Some("hi"));
1594 assert_eq!(lines.next(), None);
1595
1596 let rope = Rope::from("abc\nlonger line test\nhi");
1597 let mut lines = rope.reversed_chunks_in_range(0..rope.len()).lines();
1598 assert_eq!(lines.next(), Some("hi"));
1599 assert_eq!(lines.next(), Some("longer line test"));
1600 assert_eq!(lines.next(), Some("abc"));
1601 assert_eq!(lines.next(), None);
1602 }
1603
1604 #[gpui::test(iterations = 100)]
1605 fn test_random_rope(mut rng: StdRng) {
1606 let operations = env::var("OPERATIONS")
1607 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
1608 .unwrap_or(10);
1609
1610 let mut expected = String::new();
1611 let mut actual = Rope::new();
1612 for _ in 0..operations {
1613 let end_ix = clip_offset(&expected, rng.random_range(0..=expected.len()), Right);
1614 let start_ix = clip_offset(&expected, rng.random_range(0..=end_ix), Left);
1615 let len = rng.random_range(0..=64);
1616 let new_text: String = RandomCharIter::new(&mut rng).take(len).collect();
1617
1618 let mut new_actual = Rope::new();
1619 let mut cursor = actual.cursor(0);
1620 new_actual.append(cursor.slice(start_ix));
1621 new_actual.push(&new_text);
1622 cursor.seek_forward(end_ix);
1623 new_actual.append(cursor.suffix());
1624 actual = new_actual;
1625
1626 expected.replace_range(start_ix..end_ix, &new_text);
1627
1628 assert_eq!(actual.text(), expected);
1629 log::info!("text: {:?}", expected);
1630
1631 for _ in 0..5 {
1632 let end_ix = clip_offset(&expected, rng.random_range(0..=expected.len()), Right);
1633 let start_ix = clip_offset(&expected, rng.random_range(0..=end_ix), Left);
1634
1635 let actual_text = actual.chunks_in_range(start_ix..end_ix).collect::<String>();
1636 assert_eq!(actual_text, &expected[start_ix..end_ix]);
1637
1638 let mut actual_text = String::new();
1639 actual
1640 .bytes_in_range(start_ix..end_ix)
1641 .read_to_string(&mut actual_text)
1642 .unwrap();
1643 assert_eq!(actual_text, &expected[start_ix..end_ix]);
1644
1645 assert_eq!(
1646 actual
1647 .reversed_chunks_in_range(start_ix..end_ix)
1648 .collect::<Vec<&str>>()
1649 .into_iter()
1650 .rev()
1651 .collect::<String>(),
1652 &expected[start_ix..end_ix]
1653 );
1654
1655 let mut expected_line_starts: Vec<_> = expected[start_ix..end_ix]
1656 .match_indices('\n')
1657 .map(|(index, _)| start_ix + index + 1)
1658 .collect();
1659
1660 let mut chunks = actual.chunks_in_range(start_ix..end_ix);
1661
1662 let mut actual_line_starts = Vec::new();
1663 while chunks.next_line() {
1664 actual_line_starts.push(chunks.offset());
1665 }
1666 assert_eq!(
1667 actual_line_starts,
1668 expected_line_starts,
1669 "actual line starts != expected line starts when using next_line() for {:?} ({:?})",
1670 &expected[start_ix..end_ix],
1671 start_ix..end_ix
1672 );
1673
1674 if start_ix < end_ix
1675 && (start_ix == 0 || expected.as_bytes()[start_ix - 1] == b'\n')
1676 {
1677 expected_line_starts.insert(0, start_ix);
1678 }
1679 // Remove the last index if it starts at the end of the range.
1680 if expected_line_starts.last() == Some(&end_ix) {
1681 expected_line_starts.pop();
1682 }
1683
1684 let mut actual_line_starts = Vec::new();
1685 while chunks.prev_line() {
1686 actual_line_starts.push(chunks.offset());
1687 }
1688 actual_line_starts.reverse();
1689 assert_eq!(
1690 actual_line_starts,
1691 expected_line_starts,
1692 "actual line starts != expected line starts when using prev_line() for {:?} ({:?})",
1693 &expected[start_ix..end_ix],
1694 start_ix..end_ix
1695 );
1696
1697 // Check that next_line/prev_line work correctly from random positions
1698 let mut offset = rng.random_range(start_ix..=end_ix);
1699 while !expected.is_char_boundary(offset) {
1700 offset -= 1;
1701 }
1702 chunks.seek(offset);
1703
1704 for _ in 0..5 {
1705 if rng.random() {
1706 let expected_next_line_start = expected[offset..end_ix]
1707 .find('\n')
1708 .map(|newline_ix| offset + newline_ix + 1);
1709
1710 let moved = chunks.next_line();
1711 assert_eq!(
1712 moved,
1713 expected_next_line_start.is_some(),
1714 "unexpected result from next_line after seeking to {} in range {:?} ({:?})",
1715 offset,
1716 start_ix..end_ix,
1717 &expected[start_ix..end_ix]
1718 );
1719 if let Some(expected_next_line_start) = expected_next_line_start {
1720 assert_eq!(
1721 chunks.offset(),
1722 expected_next_line_start,
1723 "invalid position after seeking to {} in range {:?} ({:?})",
1724 offset,
1725 start_ix..end_ix,
1726 &expected[start_ix..end_ix]
1727 );
1728 } else {
1729 assert_eq!(
1730 chunks.offset(),
1731 end_ix,
1732 "invalid position after seeking to {} in range {:?} ({:?})",
1733 offset,
1734 start_ix..end_ix,
1735 &expected[start_ix..end_ix]
1736 );
1737 }
1738 } else {
1739 let search_end = if offset > 0 && expected.as_bytes()[offset - 1] == b'\n' {
1740 offset - 1
1741 } else {
1742 offset
1743 };
1744
1745 let expected_prev_line_start = expected[..search_end]
1746 .rfind('\n')
1747 .and_then(|newline_ix| {
1748 let line_start_ix = newline_ix + 1;
1749 if line_start_ix >= start_ix {
1750 Some(line_start_ix)
1751 } else {
1752 None
1753 }
1754 })
1755 .or({
1756 if offset > 0 && start_ix == 0 {
1757 Some(0)
1758 } else {
1759 None
1760 }
1761 });
1762
1763 let moved = chunks.prev_line();
1764 assert_eq!(
1765 moved,
1766 expected_prev_line_start.is_some(),
1767 "unexpected result from prev_line after seeking to {} in range {:?} ({:?})",
1768 offset,
1769 start_ix..end_ix,
1770 &expected[start_ix..end_ix]
1771 );
1772 if let Some(expected_prev_line_start) = expected_prev_line_start {
1773 assert_eq!(
1774 chunks.offset(),
1775 expected_prev_line_start,
1776 "invalid position after seeking to {} in range {:?} ({:?})",
1777 offset,
1778 start_ix..end_ix,
1779 &expected[start_ix..end_ix]
1780 );
1781 } else {
1782 assert_eq!(
1783 chunks.offset(),
1784 start_ix,
1785 "invalid position after seeking to {} in range {:?} ({:?})",
1786 offset,
1787 start_ix..end_ix,
1788 &expected[start_ix..end_ix]
1789 );
1790 }
1791 }
1792
1793 assert!((start_ix..=end_ix).contains(&chunks.offset()));
1794 if rng.random() {
1795 offset = rng.random_range(start_ix..=end_ix);
1796 while !expected.is_char_boundary(offset) {
1797 offset -= 1;
1798 }
1799 chunks.seek(offset);
1800 } else {
1801 chunks.next();
1802 offset = chunks.offset();
1803 assert!((start_ix..=end_ix).contains(&chunks.offset()));
1804 }
1805 }
1806 }
1807
1808 let mut offset_utf16 = OffsetUtf16(0);
1809 let mut point = Point::new(0, 0);
1810 let mut point_utf16 = PointUtf16::new(0, 0);
1811 for (ix, ch) in expected.char_indices().chain(Some((expected.len(), '\0'))) {
1812 assert_eq!(actual.offset_to_point(ix), point, "offset_to_point({})", ix);
1813 assert_eq!(
1814 actual.offset_to_point_utf16(ix),
1815 point_utf16,
1816 "offset_to_point_utf16({})",
1817 ix
1818 );
1819 assert_eq!(
1820 actual.point_to_offset(point),
1821 ix,
1822 "point_to_offset({:?})",
1823 point
1824 );
1825 assert_eq!(
1826 actual.point_utf16_to_offset(point_utf16),
1827 ix,
1828 "point_utf16_to_offset({:?})",
1829 point_utf16
1830 );
1831 assert_eq!(
1832 actual.offset_to_offset_utf16(ix),
1833 offset_utf16,
1834 "offset_to_offset_utf16({:?})",
1835 ix
1836 );
1837 assert_eq!(
1838 actual.offset_utf16_to_offset(offset_utf16),
1839 ix,
1840 "offset_utf16_to_offset({:?})",
1841 offset_utf16
1842 );
1843 if ch == '\n' {
1844 point += Point::new(1, 0);
1845 point_utf16 += PointUtf16::new(1, 0);
1846 } else {
1847 point.column += ch.len_utf8() as u32;
1848 point_utf16.column += ch.len_utf16() as u32;
1849 }
1850 offset_utf16.0 += ch.len_utf16();
1851 }
1852
1853 let mut offset_utf16 = OffsetUtf16(0);
1854 let mut point_utf16 = Unclipped(PointUtf16::zero());
1855 for unit in expected.encode_utf16() {
1856 let left_offset = actual.clip_offset_utf16(offset_utf16, Bias::Left);
1857 let right_offset = actual.clip_offset_utf16(offset_utf16, Bias::Right);
1858 assert!(right_offset >= left_offset);
1859 // Ensure translating UTF-16 offsets to UTF-8 offsets doesn't panic.
1860 actual.offset_utf16_to_offset(left_offset);
1861 actual.offset_utf16_to_offset(right_offset);
1862
1863 let left_point = actual.clip_point_utf16(point_utf16, Bias::Left);
1864 let right_point = actual.clip_point_utf16(point_utf16, Bias::Right);
1865 assert!(right_point >= left_point);
1866 // Ensure translating valid UTF-16 points to offsets doesn't panic.
1867 actual.point_utf16_to_offset(left_point);
1868 actual.point_utf16_to_offset(right_point);
1869
1870 offset_utf16.0 += 1;
1871 if unit == b'\n' as u16 {
1872 point_utf16.0 += PointUtf16::new(1, 0);
1873 } else {
1874 point_utf16.0 += PointUtf16::new(0, 1);
1875 }
1876 }
1877
1878 for _ in 0..5 {
1879 let end_ix = clip_offset(&expected, rng.random_range(0..=expected.len()), Right);
1880 let start_ix = clip_offset(&expected, rng.random_range(0..=end_ix), Left);
1881 assert_eq!(
1882 actual.cursor(start_ix).summary::<TextSummary>(end_ix),
1883 TextSummary::from(&expected[start_ix..end_ix])
1884 );
1885 }
1886
1887 let mut expected_longest_rows = Vec::new();
1888 let mut longest_line_len = -1_isize;
1889 for (row, line) in expected.split('\n').enumerate() {
1890 let row = row as u32;
1891 assert_eq!(
1892 actual.line_len(row),
1893 line.len() as u32,
1894 "invalid line len for row {}",
1895 row
1896 );
1897
1898 let line_char_count = line.chars().count() as isize;
1899 match line_char_count.cmp(&longest_line_len) {
1900 Ordering::Less => {}
1901 Ordering::Equal => expected_longest_rows.push(row),
1902 Ordering::Greater => {
1903 longest_line_len = line_char_count;
1904 expected_longest_rows.clear();
1905 expected_longest_rows.push(row);
1906 }
1907 }
1908 }
1909
1910 let longest_row = actual.summary().longest_row;
1911 assert!(
1912 expected_longest_rows.contains(&longest_row),
1913 "incorrect longest row {}. expected {:?} with length {}",
1914 longest_row,
1915 expected_longest_rows,
1916 longest_line_len,
1917 );
1918 }
1919 }
1920
1921 #[test]
1922 fn test_chunks_equals_str() {
1923 let text = "This is a multi-chunk\n& multi-line test string!";
1924 let rope = Rope::from(text);
1925 for start in 0..text.len() {
1926 for end in start..text.len() {
1927 let range = start..end;
1928 let correct_substring = &text[start..end];
1929
1930 // Test that correct range returns true
1931 assert!(
1932 rope.chunks_in_range(range.clone())
1933 .equals_str(correct_substring)
1934 );
1935 assert!(
1936 rope.reversed_chunks_in_range(range.clone())
1937 .equals_str(correct_substring)
1938 );
1939
1940 // Test that all other ranges return false (unless they happen to match)
1941 for other_start in 0..text.len() {
1942 for other_end in other_start..text.len() {
1943 if other_start == start && other_end == end {
1944 continue;
1945 }
1946 let other_substring = &text[other_start..other_end];
1947
1948 // Only assert false if the substrings are actually different
1949 if other_substring == correct_substring {
1950 continue;
1951 }
1952 assert!(
1953 !rope
1954 .chunks_in_range(range.clone())
1955 .equals_str(other_substring)
1956 );
1957 assert!(
1958 !rope
1959 .reversed_chunks_in_range(range.clone())
1960 .equals_str(other_substring)
1961 );
1962 }
1963 }
1964 }
1965 }
1966
1967 let rope = Rope::from("");
1968 assert!(rope.chunks_in_range(0..0).equals_str(""));
1969 assert!(rope.reversed_chunks_in_range(0..0).equals_str(""));
1970 assert!(!rope.chunks_in_range(0..0).equals_str("foo"));
1971 assert!(!rope.reversed_chunks_in_range(0..0).equals_str("foo"));
1972 }
1973
1974 fn clip_offset(text: &str, mut offset: usize, bias: Bias) -> usize {
1975 while !text.is_char_boundary(offset) {
1976 match bias {
1977 Bias::Left => offset -= 1,
1978 Bias::Right => offset += 1,
1979 }
1980 }
1981 offset
1982 }
1983
1984 impl Rope {
1985 fn text(&self) -> String {
1986 let mut text = String::new();
1987 for chunk in self.chunks.cursor::<()>(&()) {
1988 text.push_str(&chunk.text);
1989 }
1990 text
1991 }
1992 }
1993}