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