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