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