any_rope/
iter.rs

1//! Iterators over a [`Rope<M>`]'s data.
2//!
3//! The iterators in Any-Ropey can be created from both [`Rope<M>`]s and
4//! [`RopeSlice<M>`]s. When created from a [`RopeSlice<M>`], they iterate over
5//! only the data that the [`RopeSlice<M>`] refers to.  For the [`Chunks`]
6//! iterator, the data of the first and last yielded item will be correctly
7//! truncated to match the bounds of the [`RopeSlice<M>`].
8//!
9//! # Reverse iteration
10//!
11//! All iterators in Ropey operate as a cursor that can move both forwards
12//! and backwards over its contents.  This can be accomplished via the
13//! `next()` and `prev()` methods on each iterator, or by using the `reverse()`
14//! or `reversed()` methods to change the iterator's direction.
15//!
16//! Conceptually, an iterator in Any-Ropey is always positioned *between* the
17//! elements it iterates over, and returns an element when it jumps over it
18//! via the `next()` or `prev()` methods.
19//!
20//! For example, given the slice `[Width(1), Width(2), Width(5)]` and a an
21//! iterator starting at the beginning of the slice, you would get the following
22//! sequence of states and return values by repeatedly calling `next()` (the
23//! vertical bar represents the position of the iterator):
24//!
25//! 0. `[|Width(1), Width(2), Width(5)]`
26//! 1. `[Width(1), |Width(2), Width(5)] -> Some(Width(1))`
27//! 2. `[Width(1), Width(2), |Width(5)] -> Some(Width(2))`
28//! 3. `[Width(1), Width(2), Width(5)|] -> Some(Width(5))`
29//! 4. `[Width(1), Width(2), Width(5)|] -> None`
30//!
31//! The `prev()` method operates identically, except moving in the opposite
32//! direction.  And `reverse()` simply swaps the behavior of `prev()` and
33//! `next()`.
34//!
35//! # Creating iterators at any position
36//!
37//! Iterators in Ropey can be created starting at any position in the rope.
38//! This is accomplished with the [`Iter<M>`] and [`Chunks<M>`] iterators, which
39//! can be created by various functions on a [`Rope<M>`].
40//!
41//! When an iterator is created this way, it is positioned such that a call to
42//! `next()` will return the specified element, and a call to `prev()` will
43//! return the element just before the specified one.
44//!
45//! Importantly, iterators created this way still have access to the entire
46//! contents of the [`Rope<M>`]/[`RopeSlice<M>`] they were created from and the
47//! contents before the specified position is not truncated.  For example, you
48//! can create an [`Iter<M>`] iterator starting at the end of a [`Rope<M>`], and
49//! then use the [`prev()`][Iter::prev] method to iterate backwards over all of
50//! that [`Rope<M>`]'s elements.
51//!
52//! # A possible point of confusion
53//!
54//! The Rust standard library has an iterator trait [`DoubleEndedIterator`] with
55//! a method [`rev()`]. While this method's name is //! very similar to Ropey's
56//! [`reverse()`][Iter::reverse] method, its behavior is very different.
57//!
58//! [`DoubleEndedIterator`] actually provides two iterators: one starting at
59//! each end of the collection, moving in opposite directions towards each
60//! other. Calling [`rev()`] switches between those two iterators, changing not
61//! only the direction of iteration but also its current position in the
62//! collection.
63//!
64//! The [`reverse()`][Iter::reverse] method on AnyRopey's iterators, on the
65//! other hand, reverses the direction of the iterator in-place, without
66//! changing its position in the rope.
67//!
68//! [`Rope<M>`]: crate::rope::Rope
69//! [`RopeSlice<M>`]: crate::slice::RopeSlice
70//! [`rev()`]: Iterator::rev
71
72use std::{cmp::Ordering, sync::Arc};
73
74use crate::{
75    fallible_max,
76    slice_utils::{index_to_measure, measure_of, start_measure_to_index},
77    tree::{max_children, max_len, Node, SliceInfo},
78    FallibleOrd, Measurable,
79};
80
81//==========================================================
82
83/// An iterator over a [`Rope<M>`][crate::rope::Rope]'s elements.
84#[derive(Clone)]
85pub struct Iter<'a, M>
86where
87    M: Measurable,
88    [(); max_len::<M, M::Measure>()]: Sized,
89    [(); max_children::<M, M::Measure>()]: Sized,
90{
91    chunks: Chunks<'a, M>,
92    cur_chunk: &'a [M],
93    index: usize,
94    measure: M::Measure,
95    last_call_was_prev_impl: bool,
96    total_len: usize,
97    remaining_len: usize,
98    is_reversed: bool,
99}
100
101impl<'a, M> Iter<'a, M>
102where
103    M: Measurable,
104    [(); max_len::<M, M::Measure>()]: Sized,
105    [(); max_children::<M, M::Measure>()]: Sized,
106{
107    pub(crate) fn new(node: &'a Arc<Node<M>>) -> Self {
108        let mut chunk_iter = Chunks::new(node);
109        let cur_chunk = if let Some(chunk) = chunk_iter.next() {
110            chunk
111        } else {
112            &[]
113        };
114        Iter {
115            chunks: chunk_iter,
116            cur_chunk,
117            index: 0,
118            measure: M::Measure::default(),
119            last_call_was_prev_impl: false,
120            total_len: node.info().len as usize,
121            remaining_len: node.info().len as usize,
122            is_reversed: false,
123        }
124    }
125
126    #[inline(always)]
127    pub(crate) fn new_with_range(
128        node: &'a Arc<Node<M>>,
129        index_range: (usize, usize),
130        measure_range: (M::Measure, M::Measure),
131        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
132    ) -> Self {
133        Iter::new_with_range_at_measure(node, measure_range.0, index_range, measure_range, cmp)
134    }
135
136    pub(crate) fn new_with_range_at_measure(
137        node: &'a Arc<Node<M>>,
138        at_measure: M::Measure,
139        index_range: (usize, usize),
140        measure_range: (M::Measure, M::Measure),
141        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
142    ) -> Self {
143        let (mut chunks, mut chunk_start_index, mut chunk_start_measure) =
144            Chunks::new_with_range_at_measure(node, at_measure, index_range, measure_range, &cmp);
145
146        let cur_chunk = if index_range.0 == index_range.1 {
147            &[]
148        } else if let Some(chunk) = chunks.next() {
149            chunk
150        } else {
151            let chunk = chunks.prev().unwrap();
152            chunks.next();
153            chunk_start_index -= chunk.len();
154
155            let accum_prev_measure = chunk
156                .iter()
157                .map(|m| m.measure())
158                .fold(M::Measure::default(), |accum, measure| accum + measure);
159            chunk_start_measure = chunk_start_measure - accum_prev_measure;
160
161            chunk
162        };
163
164        let index = start_measure_to_index(cur_chunk, at_measure - chunk_start_measure, &cmp);
165        let measure = index_to_measure(cur_chunk, index) + chunk_start_measure;
166
167        Iter {
168            chunks,
169            cur_chunk,
170            index,
171            measure,
172            last_call_was_prev_impl: false,
173            total_len: index_range.1 - index_range.0,
174            remaining_len: index_range.1 - (index + chunk_start_index),
175            is_reversed: false,
176        }
177    }
178
179    #[inline(always)]
180    pub(crate) fn from_slice(slice: &'a [M]) -> Self {
181        Iter::from_slice_at(slice, M::Measure::default(), M::Measure::fallible_cmp)
182    }
183
184    pub(crate) fn from_slice_at(
185        slice: &'a [M],
186        measure: M::Measure,
187        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
188    ) -> Self {
189        let mut chunks = Chunks::from_slice(slice, false);
190        let cur_chunk = if let Some(chunk) = chunks.next() {
191            chunk
192        } else {
193            &[]
194        };
195
196        let index = start_measure_to_index(slice, measure, cmp);
197        let measure = index_to_measure(slice, index);
198
199        Iter {
200            chunks,
201            cur_chunk,
202            index,
203            measure,
204            last_call_was_prev_impl: false,
205            total_len: slice.len(),
206            remaining_len: slice.len() - index,
207            is_reversed: false,
208        }
209    }
210
211    /// Reverses the direction of the iterator in-place.
212    ///
213    /// In other words, swaps the behavior of [`prev()`][Self::prev]
214    /// and [`next()`][Self::next].
215    #[inline]
216    pub fn reverse(&mut self) {
217        self.is_reversed = !self.is_reversed;
218    }
219
220    /// Same as [`reverse()`][Self::reverse], but returns itself.
221    ///
222    /// This is useful when chaining iterator methods:
223    ///
224    /// ```rust
225    /// #![feature(generic_const_exprs)]
226    /// # use any_rope::{Rope, Width};
227    /// # let rope = Rope::from_slice(&[Width(1), Width(2), Width(5)]);
228    /// // Print the rope's elements and their measures in reverse.
229    /// for (measure, element) in rope.iter_at_measure(rope.measure(), usize::cmp).reversed() {
230    ///     println!("{} {:?}", measure, element);
231    /// #   assert_eq!((measure, element), rope.from_measure(measure, usize::cmp));
232    /// }
233    #[inline]
234    #[must_use]
235    pub fn reversed(mut self) -> Self {
236        self.reverse();
237        self
238    }
239
240    /// Advances the iterator backwards and returns the previous value.
241    ///
242    /// Runs in amortized O(1) time and worst-case O(log N) time.
243    #[inline(always)]
244    pub fn prev(&mut self) -> Option<(M::Measure, M)> {
245        if !self.is_reversed {
246            self.prev_impl()
247        } else {
248            self.next_impl()
249        }
250    }
251
252    #[inline]
253    fn prev_impl(&mut self) -> Option<(M::Measure, M)> {
254        // Put us back into a "prev" progression.
255        if !self.last_call_was_prev_impl {
256            self.chunks.prev();
257            self.last_call_was_prev_impl = true;
258        }
259
260        // Progress the chunks iterator back if needed.
261        if self.index == 0 {
262            if let Some(chunk) = self.chunks.prev() {
263                self.cur_chunk = chunk;
264                self.index = self.cur_chunk.len();
265            } else {
266                return None;
267            }
268        }
269
270        // Progress the byte counts and return the previous element.
271        self.index -= 1;
272        self.remaining_len += 1;
273        self.measure = self.measure - self.cur_chunk[self.index].measure();
274        return Some((self.measure, self.cur_chunk[self.index].clone()));
275    }
276
277    #[inline]
278    fn next_impl(&mut self) -> Option<(M::Measure, M)> {
279        // Put us back into a "next" progression.
280        if self.last_call_was_prev_impl {
281            self.chunks.next();
282            self.last_call_was_prev_impl = false;
283        }
284
285        // Progress the chunks iterator forward if needed.
286        if self.index >= self.cur_chunk.len() {
287            if let Some(chunk) = self.chunks.next() {
288                self.cur_chunk = chunk;
289                self.index = 0;
290            } else {
291                return None;
292            }
293        }
294
295        // Progress the byte counts and return the next element.
296        let element = self.cur_chunk[self.index].clone();
297        self.index += 1;
298        self.remaining_len -= 1;
299
300        let old_measure = self.measure;
301        self.measure = self.measure + element.measure();
302        return Some((old_measure, element));
303    }
304}
305
306impl<'a, M> Iterator for Iter<'a, M>
307where
308    M: Measurable,
309    [(); max_len::<M, M::Measure>()]: Sized,
310    [(); max_children::<M, M::Measure>()]: Sized,
311{
312    type Item = (M::Measure, M);
313
314    /// Advances the iterator forward and returns the next value.
315    ///
316    /// Runs in amortized O(1) time and worst-case O(log N) time.
317    #[inline(always)]
318    fn next(&mut self) -> Option<Self::Item> {
319        if !self.is_reversed {
320            self.next_impl()
321        } else {
322            self.prev_impl()
323        }
324    }
325
326    fn size_hint(&self) -> (usize, Option<usize>) {
327        let remaining = if !self.is_reversed {
328            self.remaining_len
329        } else {
330            self.total_len - self.remaining_len
331        };
332        (remaining, Some(remaining))
333    }
334}
335
336impl<'a, M> ExactSizeIterator for Iter<'a, M>
337where
338    M: Measurable,
339    [(); max_len::<M, M::Measure>()]: Sized,
340    [(); max_children::<M, M::Measure>()]: Sized,
341{
342}
343
344//==========================================================
345
346/// An iterator over a [`Rope<M>`]'s contiguous [`M`] chunks.
347///
348/// Internally, each [`Rope<M>`] stores [`M`]s as a segemented collection of
349/// [`&[M]`][Measurable]. It is useful for situations such as:
350///
351/// - Streaming a [`Rope<M>`]'s elements data somewhere.
352/// - Writing custom iterators over a [`Rope<M>`]'s data.
353///
354/// There are no guarantees about the size of yielded chunks, and there are
355/// no guarantees about where the chunks are split.  For example, they may
356/// be zero-sized.
357///
358/// [`M`]: Measurable
359/// [`Rope<M>`]: crate::rope::Rope
360#[derive(Clone)]
361pub struct Chunks<'a, M>
362where
363    M: Measurable,
364    [(); max_len::<M, M::Measure>()]: Sized,
365    [(); max_children::<M, M::Measure>()]: Sized,
366{
367    iter: ChunksEnum<'a, M>,
368    is_reversed: bool,
369}
370
371#[derive(Clone)]
372enum ChunksEnum<'a, M>
373where
374    M: Measurable,
375    [(); max_len::<M, M::Measure>()]: Sized,
376    [(); max_children::<M, M::Measure>()]: Sized,
377{
378    Full {
379        /// (node ref, index of current child)
380        node_stack: Vec<(&'a Arc<Node<M>>, usize)>,
381        /// Total lenght of the data range of the iterator.
382        len: usize,
383        /// The index of the current element relative to the data range start.
384        index: isize,
385    },
386    Light {
387        slice: &'a [M],
388        is_end: bool,
389    },
390}
391
392impl<'a, M> Chunks<'a, M>
393where
394    M: Measurable,
395    [(); max_len::<M, M::Measure>()]: Sized,
396    [(); max_children::<M, M::Measure>()]: Sized,
397{
398    #[inline(always)]
399    pub(crate) fn new(node: &'a Arc<Node<M>>) -> Self {
400        let info = node.info();
401        Chunks::new_with_range_at_index(
402            node,
403            0,
404            (0, info.len as usize),
405            (M::Measure::default(), info.measure),
406        )
407        .0
408    }
409
410    #[inline(always)]
411    pub(crate) fn new_with_range(
412        node: &'a Arc<Node<M>>,
413        index_range: (usize, usize),
414        measure_range: (M::Measure, M::Measure),
415    ) -> Self {
416        Chunks::new_with_range_at_index(node, index_range.0, index_range, measure_range).0
417    }
418
419    /// The main workhorse function for creating new [`Chunks`] iterators.
420    ///
421    /// Creates a new [`Chunks`] iterator from the given node, starting the
422    /// iterator at the chunk containing the element in `at_index`
423    /// (i.e. the [`next()`][Self::next] method will yield the chunk containing
424    /// that element). The range of the iterator is bounded by `index_range`.
425    ///
426    /// Both `at_index` and `index_range` are relative to the beginning of
427    /// of the passed node.
428    ///
429    /// Passing an `at_index` equal to the max of `index_range` creates an
430    /// iterator at the end of forward iteration.
431    ///
432    /// Returns the iterator and the index/measure of its start relative
433    /// to the start of the node.
434    pub(crate) fn new_with_range_at_index(
435        node: &Arc<Node<M>>,
436        at_index: usize,
437        (start_index, end_index): (usize, usize),
438        measure_range: (M::Measure, M::Measure),
439    ) -> (Chunks<M>, usize, M::Measure) {
440        debug_assert!(at_index >= start_index);
441        debug_assert!(at_index <= end_index);
442
443        // Special-case for empty slice contents.
444        if start_index == end_index {
445            return (
446                Chunks {
447                    iter: ChunksEnum::Light {
448                        slice: &[],
449                        is_end: false,
450                    },
451                    is_reversed: false,
452                },
453                0,
454                M::Measure::default(),
455            );
456        }
457
458        // If root is a leaf, return light version of the iter.
459        if node.is_leaf() {
460            let slice = &node.leaf_slice()[start_index..end_index];
461            if at_index == end_index {
462                return (
463                    Chunks {
464                        iter: ChunksEnum::Light {
465                            slice,
466                            is_end: true,
467                        },
468                        is_reversed: false,
469                    },
470                    slice.len(),
471                    measure_of(slice),
472                );
473            } else {
474                return (
475                    Chunks {
476                        iter: ChunksEnum::Light {
477                            slice,
478                            is_end: false,
479                        },
480                        is_reversed: false,
481                    },
482                    0,
483                    M::Measure::default(),
484                );
485            }
486        }
487
488        // Create and populate the node stack, and determine the char index
489        // within the first chunk, and byte index of the start of that chunk.
490        let mut info = SliceInfo::<M::Measure>::new::<M>();
491        let mut index = at_index as isize;
492        let node_stack = {
493            let mut node_stack: Vec<(&Arc<Node<M>>, usize)> = Vec::new();
494            let mut node_ref = node;
495            loop {
496                match **node_ref {
497                    Node::Leaf(ref slice) => {
498                        if at_index < end_index || index == 0 {
499                            index = info.len as isize - start_index as isize;
500                        } else {
501                            index =
502                                (info.len as isize + slice.len() as isize) - start_index as isize;
503                            info = SliceInfo {
504                                len: end_index as u64,
505                                measure: measure_range.1,
506                            };
507                            node_stack.last_mut().unwrap().1 += 1;
508                        }
509                        break;
510                    }
511                    Node::Branch(ref children) => {
512                        let (child_i, acc_info) = children.search_index(index as usize);
513                        info += acc_info;
514                        node_stack.push((node_ref, child_i));
515                        node_ref = &children.nodes()[child_i];
516                        index -= acc_info.len as isize;
517                    }
518                }
519            }
520            node_stack
521        };
522
523        // Create the iterator.
524        (
525            Chunks {
526                iter: ChunksEnum::Full {
527                    node_stack,
528                    len: end_index - start_index,
529                    index,
530                },
531                is_reversed: false,
532            },
533            (info.len as usize).max(start_index),
534            fallible_max(info.measure, measure_range.0),
535        )
536    }
537
538    #[inline(always)]
539    pub(crate) fn new_with_range_at_measure(
540        node: &'a Arc<Node<M>>,
541        at_measure: M::Measure,
542        index_range: (usize, usize),
543        measure_range: (M::Measure, M::Measure),
544        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
545    ) -> (Self, usize, M::Measure) {
546        let at_index =
547            (node.get_first_chunk_at_measure(at_measure, &cmp).1.len as usize).max(index_range.0);
548
549        Chunks::new_with_range_at_index(node, at_index, index_range, measure_range)
550    }
551
552    pub(crate) fn from_slice(slice: &'a [M], is_end: bool) -> Self {
553        Chunks {
554            iter: ChunksEnum::Light { slice, is_end },
555            is_reversed: false,
556        }
557    }
558
559    /// Reverses the direction of the iterator in-place.
560    ///
561    /// In other words, swaps the behavior of [`prev()`][Self::prev]
562    /// and [`next()`][Self::next].
563    #[inline]
564    pub fn reverse(&mut self) {
565        self.is_reversed = !self.is_reversed;
566    }
567
568    /// Same as [`reverse()`][Self::reverse], but returns itself.
569    ///
570    /// This is useful when chaining iterator methods:
571    ///
572    /// ```rust
573    /// # use any_rope::{Rope, Width};
574    /// # let rope = Rope::from_slice(
575    /// #    &[Width(1), Width(2), Width(3), Width(0), Width(0)]
576    /// # );
577    /// // Enumerate the rope's chunks in reverse, starting from the end.
578    /// for (index, chunk) in rope.chunks_at_index(rope.len()).0.reversed().enumerate() {
579    ///     println!("{} {:?}", index, chunk);
580    /// #   assert_eq!(chunk, rope.chunks().nth(rope.chunks().count() - index - 1).unwrap());
581    /// }
582    #[inline]
583    #[must_use]
584    pub fn reversed(mut self) -> Self {
585        self.reverse();
586        self
587    }
588
589    /// Advances the iterator backwards and returns the previous value.
590    ///
591    /// Runs in amortized O(1) time and worst-case O(log N) time.
592    #[inline(always)]
593    pub fn prev(&mut self) -> Option<&'a [M]> {
594        if !self.is_reversed {
595            self.prev_impl()
596        } else {
597            self.next_impl()
598        }
599    }
600
601    fn prev_impl(&mut self) -> Option<&'a [M]> {
602        match *self {
603            Chunks {
604                iter:
605                    ChunksEnum::Full {
606                        ref mut node_stack,
607                        len,
608                        ref mut index,
609                    },
610                ..
611            } => {
612                if *index <= 0 {
613                    return None;
614                }
615
616                // Progress the node stack if needed.
617                let mut stack_index = node_stack.len() - 1;
618                if node_stack[stack_index].1 == 0 {
619                    while node_stack[stack_index].1 == 0 {
620                        if stack_index == 0 {
621                            return None;
622                        } else {
623                            stack_index -= 1;
624                        }
625                    }
626                    node_stack[stack_index].1 -= 1;
627                    while stack_index < (node_stack.len() - 1) {
628                        let child_i = node_stack[stack_index].1;
629                        let node = &node_stack[stack_index].0.children().nodes()[child_i];
630                        node_stack[stack_index + 1] = (node, node.child_count() - 1);
631                        stack_index += 1;
632                    }
633                    node_stack[stack_index].1 += 1;
634                }
635
636                // Fetch the node and child index.
637                let (node, ref mut child_i) = node_stack.last_mut().unwrap();
638                *child_i -= 1;
639
640                // Get the slice in the appropriate range.
641                let slice = node.children().nodes()[*child_i].leaf_slice();
642                *index -= slice.len() as isize;
643                let slice = {
644                    let start_byte = if *index < 0 { (-*index) as usize } else { 0 };
645                    let end_byte = slice.len().min((len as isize - *index) as usize);
646                    &slice[start_byte..end_byte]
647                };
648
649                // Return the slice.
650                return Some(slice);
651            }
652
653            Chunks {
654                iter:
655                    ChunksEnum::Light {
656                        slice,
657                        ref mut is_end,
658                    },
659                ..
660            } => {
661                if !*is_end || slice.is_empty() {
662                    return None;
663                } else {
664                    *is_end = false;
665                    return Some(slice);
666                }
667            }
668        }
669    }
670
671    fn next_impl(&mut self) -> Option<&'a [M]> {
672        match *self {
673            Chunks {
674                iter:
675                    ChunksEnum::Full {
676                        ref mut node_stack,
677                        len,
678                        ref mut index,
679                    },
680                ..
681            } => {
682                if *index >= len as isize {
683                    return None;
684                }
685
686                // Progress the node stack if needed.
687                let mut stack_index = node_stack.len() - 1;
688                if node_stack[stack_index].1 >= node_stack[stack_index].0.child_count() {
689                    while node_stack[stack_index].1 >= (node_stack[stack_index].0.child_count() - 1)
690                    {
691                        if stack_index == 0 {
692                            return None;
693                        } else {
694                            stack_index -= 1;
695                        }
696                    }
697                    node_stack[stack_index].1 += 1;
698                    while stack_index < (node_stack.len() - 1) {
699                        let child_i = node_stack[stack_index].1;
700                        let node = &node_stack[stack_index].0.children().nodes()[child_i];
701                        node_stack[stack_index + 1] = (node, 0);
702                        stack_index += 1;
703                    }
704                }
705
706                // Fetch the node and child index.
707                let (node, ref mut child_i) = node_stack.last_mut().unwrap();
708
709                // Get the slice, sliced to the appropriate range.
710                let leaf_slice = node.children().nodes()[*child_i].leaf_slice();
711                let slice = {
712                    let start_byte = if *index < 0 { (-*index) as usize } else { 0 };
713                    let end_byte = leaf_slice.len().min((len as isize - *index) as usize);
714                    &leaf_slice[start_byte..end_byte]
715                };
716
717                // Book keeping.
718                *index += leaf_slice.len() as isize;
719                *child_i += 1;
720
721                // Return the slice.
722                return Some(slice);
723            }
724
725            Chunks {
726                iter:
727                    ChunksEnum::Light {
728                        slice,
729                        ref mut is_end,
730                    },
731                ..
732            } => {
733                if *is_end || slice.is_empty() {
734                    return None;
735                } else {
736                    *is_end = true;
737                    return Some(slice);
738                }
739            }
740        }
741    }
742}
743
744impl<'a, M> Iterator for Chunks<'a, M>
745where
746    M: Measurable,
747    [(); max_len::<M, M::Measure>()]: Sized,
748    [(); max_children::<M, M::Measure>()]: Sized,
749{
750    type Item = &'a [M];
751
752    /// Advances the iterator forward and returns the next value.
753    ///
754    /// Runs in amortized O(1) time and worst-case O(log N) time.
755    #[inline(always)]
756    fn next(&mut self) -> Option<&'a [M]> {
757        if !self.is_reversed {
758            self.next_impl()
759        } else {
760            self.prev_impl()
761        }
762    }
763}
764
765#[cfg(test)]
766mod tests {
767    #![allow(clippy::while_let_on_iterator)]
768    use super::*;
769    use crate::{Rope, Width};
770
771    fn pseudo_random() -> Vec<Width> {
772        (0..1400)
773            .map(|num| match num % 14 {
774                0 => Width(1),
775                1 => Width(2),
776                2 => Width(4),
777                3 => Width(0),
778                4 => Width(0),
779                5 => Width(5),
780                6 => Width(1),
781                7 => Width(1),
782                8 => Width(2),
783                9 => Width(8),
784                10 => Width(0),
785                11 => Width(0),
786                12 => Width(3),
787                13 => Width(0),
788                _ => unreachable!(),
789            })
790            .collect()
791    }
792
793    #[test]
794    #[cfg_attr(miri, ignore)]
795    fn iter_01() {
796        let rope = Rope::from_slice(pseudo_random().as_slice());
797        for ((_, from_rope), from_vec) in rope.iter().zip(pseudo_random().iter().copied()) {
798            assert_eq!(from_rope, from_vec);
799        }
800    }
801
802    #[test]
803    #[cfg_attr(miri, ignore)]
804    fn iter_02() {
805        let rope = Rope::from_slice(pseudo_random().as_slice());
806        let mut iter = rope.iter();
807        while let Some(_) = iter.next() {}
808
809        let mut i = pseudo_random().len();
810        while let Some((_, element)) = iter.prev() {
811            i -= 1;
812            assert_eq!(element, pseudo_random()[i]);
813        }
814    }
815
816    #[test]
817    #[cfg_attr(miri, ignore)]
818    fn iter_03() {
819        let rope = Rope::from_slice(pseudo_random().as_slice());
820        let mut iter = rope.iter();
821
822        iter.next();
823        iter.prev();
824        assert_eq!(None, iter.prev());
825    }
826
827    #[test]
828    #[cfg_attr(miri, ignore)]
829    fn iter_04() {
830        let rope = Rope::from_slice(pseudo_random().as_slice());
831        let mut iter = rope.iter();
832        while let Some(_) = iter.next() {}
833
834        iter.prev();
835        iter.next();
836        assert_eq!(None, iter.next());
837    }
838
839    #[test]
840    #[cfg_attr(miri, ignore)]
841    fn iter_05() {
842        let rope = Rope::from_slice(pseudo_random().as_slice());
843        let mut iter = rope.iter();
844
845        assert_eq!(None, iter.prev());
846        iter.next();
847        iter.prev();
848        assert_eq!(None, iter.prev());
849    }
850
851    #[test]
852    #[cfg_attr(miri, ignore)]
853    fn iter_06() {
854        let rope = Rope::from_slice(pseudo_random().as_slice());
855        let mut iter = rope.iter();
856        while let Some(_) = iter.next() {}
857
858        assert_eq!(None, iter.next());
859        iter.prev();
860        iter.next();
861        assert_eq!(None, iter.next());
862    }
863
864    #[test]
865    #[cfg_attr(miri, ignore)]
866    fn iter_07() {
867        let mut iter = Iter::from_slice(&[Width(1)]);
868
869        assert_eq!(Some((0, Width(1))), iter.next());
870        assert_eq!(None, iter.next());
871        assert_eq!(Some((0, Width(1))), iter.prev());
872        assert_eq!(None, iter.prev());
873    }
874
875    #[test]
876    #[cfg_attr(miri, ignore)]
877    fn iter_08() {
878        let measure_vec = pseudo_random();
879        let mut iter = Iter::from_slice(measure_vec.as_slice());
880
881        assert_eq!(iter.next(), Some((0, Width(1))));
882        assert_eq!(iter.next(), Some((1, Width(2))));
883        assert_eq!(iter.next(), Some((3, Width(4))));
884        assert_eq!(iter.next(), Some((7, Width(0))));
885        assert_eq!(iter.next(), Some((7, Width(0))));
886        assert_eq!(iter.next(), Some((7, Width(5))));
887        assert_eq!(iter.next(), Some((12, Width(1))));
888        assert_eq!(iter.next(), Some((13, Width(1))));
889        assert_eq!(iter.next(), Some((14, Width(2))));
890        assert_eq!(iter.next(), Some((16, Width(8))));
891        assert_eq!(iter.next(), Some((24, Width(0))));
892        assert_eq!(iter.next(), Some((24, Width(0))));
893        assert_eq!(iter.next(), Some((24, Width(3))));
894        assert_eq!(iter.next(), Some((27, Width(0))));
895        assert_eq!(iter.next(), Some((27, Width(1))));
896    }
897
898    #[test]
899    #[cfg_attr(miri, ignore)]
900    fn iter_at_01() {
901        let rope = Rope::from_slice(pseudo_random().as_slice());
902        let slice = rope.measure_slice(..79, usize::cmp);
903        let mut iter = slice.iter_at(56, usize::cmp);
904
905        assert_eq!(iter.next(), Some((55, Width(2))));
906        assert_eq!(iter.next(), Some((57, Width(4))));
907        assert_eq!(iter.next(), Some((61, Width(0))));
908        assert_eq!(iter.next(), Some((61, Width(0))));
909        assert_eq!(iter.next(), Some((61, Width(5))));
910        assert_eq!(iter.next(), Some((66, Width(1))));
911        assert_eq!(iter.next(), Some((67, Width(1))));
912        assert_eq!(iter.next(), Some((68, Width(2))));
913        assert_eq!(iter.next(), Some((70, Width(8))));
914        assert_eq!(iter.next(), Some((78, Width(0))));
915        assert_eq!(iter.next(), Some((78, Width(0))));
916        assert_eq!(iter.next(), Some((78, Width(3))));
917        assert_eq!(iter.next(), None);
918    }
919
920    #[test]
921    #[cfg_attr(miri, ignore)]
922    fn iter_at_02() {
923        let rope = Rope::from_slice(pseudo_random().as_slice());
924        let mut bytes = rope.iter_at_measure(rope.measure(), usize::cmp);
925        // Iterating at the end, when there are zero measure elements, always yields
926        // them.
927        assert_eq!(bytes.next(), Some((2700, Width(0))));
928        assert_eq!(bytes.next(), None);
929    }
930
931    #[test]
932    #[cfg_attr(miri, ignore)]
933    fn iter_at_03() {
934        let rope = Rope::from_slice(pseudo_random().as_slice());
935        let mut iter_1 = rope.iter_at_measure(rope.measure(), usize::cmp);
936        let measure_vec = pseudo_random();
937        // Skip the last element, since it's zero measure.
938        let mut iter_2 = measure_vec.iter().take(1399).copied();
939
940        while let Some(b) = iter_2.next_back() {
941            assert_eq!(iter_1.prev().map(|(_, element)| element), Some(b));
942        }
943    }
944
945    #[test]
946    #[cfg_attr(miri, ignore)]
947    fn exact_size_iter_01() {
948        let rope = Rope::from_slice(pseudo_random().as_slice());
949        let slice = rope.measure_slice(34..75, usize::cmp);
950
951        let mut len = slice.len();
952        let mut iter = slice.iter();
953        assert_eq!(len, iter.len());
954
955        while let Some(_) = iter.next() {
956            len -= 1;
957            assert_eq!(len, iter.len());
958        }
959
960        iter.next();
961        iter.next();
962        iter.next();
963        iter.next();
964        iter.next();
965        iter.next();
966        iter.next();
967        assert_eq!(iter.len(), 0);
968        assert_eq!(len, 0);
969    }
970
971    #[test]
972    #[cfg_attr(miri, ignore)]
973    fn exact_size_iter_02() {
974        let rope = Rope::from_slice(pseudo_random().as_slice());
975        let slice = rope.measure_slice(34..300, usize::cmp);
976
977        let mut len = 0;
978        let mut iter = slice.iter_at(slice.measure(), usize::cmp);
979
980        assert_eq!(len, iter.len());
981
982        while iter.prev().is_some() {
983            len += 1;
984            assert_eq!(len, iter.len());
985        }
986
987        assert_eq!(iter.len(), slice.len());
988        iter.prev();
989        iter.prev();
990        iter.prev();
991        iter.prev();
992        iter.prev();
993        iter.prev();
994        iter.prev();
995        assert_eq!(iter.len(), slice.len());
996        assert_eq!(len, slice.len());
997    }
998
999    #[test]
1000    #[cfg_attr(miri, ignore)]
1001    fn exact_size_iter_03() {
1002        let rope = Rope::from_slice(pseudo_random().as_slice());
1003        let slice = rope.measure_slice(34..34, usize::cmp);
1004        let mut iter = slice.iter();
1005
1006        assert_eq!(iter.next(), Some((34, Width(0))));
1007        assert_eq!(iter.next(), Some((34, Width(0))));
1008        assert_eq!(iter.next(), None);
1009    }
1010
1011    #[test]
1012    #[cfg_attr(miri, ignore)]
1013    fn iter_reverse_01() {
1014        let rope = Rope::from_slice(pseudo_random().as_slice());
1015        let mut iter = rope.iter();
1016        let mut stack = Vec::new();
1017
1018        for _ in 0..32 {
1019            stack.push(iter.next().unwrap());
1020        }
1021        iter.reverse();
1022        for _ in 0..32 {
1023            assert_eq!(stack.pop(), iter.next());
1024        }
1025    }
1026
1027    #[test]
1028    #[cfg_attr(miri, ignore)]
1029    fn iter_reverse_02() {
1030        let rope = Rope::from_slice(pseudo_random().as_slice());
1031        let mut iter = rope.iter_at_measure(rope.len() / 3, usize::cmp);
1032        let mut stack = Vec::new();
1033
1034        for _ in 0..32 {
1035            stack.push(iter.next().unwrap());
1036        }
1037        iter.reverse();
1038        for _ in 0..32 {
1039            assert_eq!(stack.pop(), iter.next());
1040        }
1041    }
1042
1043    #[test]
1044    #[cfg_attr(miri, ignore)]
1045    fn chunks_01() {
1046        let rope = Rope::from_slice(pseudo_random().as_slice());
1047
1048        let mut index = 0;
1049        for chunk in rope.chunks() {
1050            assert_eq!(chunk, &pseudo_random()[index..(index + chunk.len())]);
1051            index += chunk.len();
1052        }
1053    }
1054
1055    #[test]
1056    #[cfg_attr(miri, ignore)]
1057    fn chunks_02() {
1058        let rope = Rope::<Width>::from_slice(&[]);
1059        let mut iter = rope.chunks();
1060
1061        assert_eq!(None, iter.next());
1062    }
1063
1064    #[test]
1065    #[cfg_attr(miri, ignore)]
1066    fn chunks_03() {
1067        let rope = Rope::from_slice(pseudo_random().as_slice());
1068
1069        let mut iter = rope.chunks();
1070
1071        assert_eq!(None, iter.prev());
1072    }
1073
1074    #[test]
1075    #[cfg_attr(miri, ignore)]
1076    fn chunks_04() {
1077        let rope = Rope::from_slice(pseudo_random().as_slice());
1078
1079        let mut chunks = Vec::new();
1080        let mut iter = rope.chunks();
1081
1082        while let Some(slice) = iter.next() {
1083            chunks.push(slice);
1084        }
1085
1086        while let Some(slice) = iter.prev() {
1087            assert_eq!(slice, chunks.pop().unwrap());
1088        }
1089
1090        assert!(chunks.is_empty());
1091    }
1092
1093    #[test]
1094    #[cfg_attr(miri, ignore)]
1095    fn chunks_at_01() {
1096        let rope = Rope::from_slice(pseudo_random().as_slice());
1097
1098        for i in 0..rope.len() {
1099            let (chunk, index, measure) = rope.chunk_at_index(i);
1100            let (mut chunks, slice_index, slice_measure) = rope.chunks_at_index(i);
1101
1102            assert_eq!(index, slice_index);
1103            assert_eq!(measure, slice_measure);
1104            assert_eq!(Some(chunk), chunks.next());
1105        }
1106    }
1107
1108    #[test]
1109    #[cfg_attr(miri, ignore)]
1110    fn chunks_at_02() {
1111        let rope = Rope::from_slice(pseudo_random().as_slice());
1112        let slice = rope.measure_slice(34..301, usize::cmp);
1113
1114        let (mut chunks, ..) = slice.chunks_at_index(slice.len());
1115        assert_eq!(chunks.next(), None);
1116
1117        let (mut chunks, ..) = slice.chunks_at_index(slice.len());
1118        assert_eq!(slice.chunks().last(), chunks.prev());
1119    }
1120
1121    #[test]
1122    #[cfg_attr(miri, ignore)]
1123    fn chunks_at_03() {
1124        let rope = Rope::from_slice(pseudo_random().as_slice());
1125        let slice = rope.measure_slice(34..34, usize::cmp);
1126
1127        let (mut chunks, ..) = slice.chunks_at_index(0);
1128        assert_eq!(chunks.next(), Some([Width(0)].as_slice()));
1129        assert!(chunks.next().is_some());
1130
1131        let (mut chunks, ..) = slice.chunks_at_index(0);
1132        assert_eq!(chunks.prev(), None);
1133    }
1134
1135    #[test]
1136    #[cfg_attr(miri, ignore)]
1137    fn chunks_reverse_01() {
1138        let rope = Rope::from_slice(pseudo_random().as_slice());
1139        let mut iter = rope.chunks();
1140        let mut stack = Vec::new();
1141
1142        for _ in 0..8 {
1143            stack.push(iter.next().unwrap());
1144        }
1145        iter.reverse();
1146        for _ in 0..8 {
1147            assert_eq!(stack.pop().unwrap(), iter.next().unwrap());
1148        }
1149    }
1150
1151    #[test]
1152    #[cfg_attr(miri, ignore)]
1153    fn chunks_reverse_02() {
1154        let rope = Rope::from_slice(pseudo_random().as_slice());
1155        let mut iter = rope.chunks_at_measure(rope.measure() / 3, usize::cmp).0;
1156        let mut stack = Vec::new();
1157
1158        for _ in 0..8 {
1159            stack.push(iter.next().unwrap());
1160        }
1161        iter.reverse();
1162        for _ in 0..8 {
1163            assert_eq!(stack.pop().unwrap(), iter.next().unwrap());
1164        }
1165    }
1166
1167    #[test]
1168    #[cfg_attr(miri, ignore)]
1169    fn chunks_reverse_03() {
1170        let rope = Rope::from_slice(pseudo_random().as_slice());
1171        let mut iter = rope.chunks_at_measure(rope.measure() / 3, usize::cmp).0;
1172        let mut stack = Vec::new();
1173
1174        iter.reverse();
1175        for _ in 0..8 {
1176            stack.push(iter.next().unwrap());
1177        }
1178        iter.reverse();
1179        for _ in 0..8 {
1180            assert_eq!(stack.pop().unwrap(), iter.next().unwrap());
1181        }
1182    }
1183
1184    #[test]
1185    #[cfg_attr(miri, ignore)]
1186    fn chunks_reverse_04() {
1187        let mut iter = Chunks::from_slice(&[Width(5), Width(0)], false);
1188
1189        assert_eq!(Some([Width(5), Width(0)].as_slice()), iter.next());
1190        assert_eq!(None, iter.next());
1191        iter.reverse();
1192        assert_eq!(Some([Width(5), Width(0)].as_slice()), iter.next());
1193        assert_eq!(None, iter.next());
1194    }
1195
1196    #[test]
1197    #[cfg_attr(miri, ignore)]
1198    fn iter_sliced_01() {
1199        let rope = Rope::from_slice(pseudo_random().as_slice());
1200
1201        let slice_start = 34;
1202        let slice_end = 301;
1203        let slice_start_byte = rope.start_measure_to_index(slice_start, usize::cmp);
1204        let s_end_byte = rope.end_measure_to_index(slice_end, usize::cmp);
1205
1206        let slice_1 = rope.measure_slice(slice_start..slice_end, usize::cmp);
1207        let slice_2 = &pseudo_random()[slice_start_byte..s_end_byte];
1208
1209        let mut slice_1_iter = slice_1.iter();
1210        let mut slice_2_iter = slice_2.iter().copied();
1211
1212        assert_eq!(slice_1, slice_2);
1213        assert_eq!(slice_1.from_index(0).1, slice_2[0]);
1214        for _ in 0..(slice_2.len() + 1) {
1215            assert_eq!(
1216                slice_1_iter.next().map(|(_, element)| element),
1217                slice_2_iter.next()
1218            );
1219        }
1220    }
1221
1222    #[test]
1223    #[cfg_attr(miri, ignore)]
1224    fn iter_at_sliced_02() {
1225        let rope = Rope::from_slice(pseudo_random().as_slice());
1226        let slice = rope.measure_slice(34..300, usize::cmp);
1227        let mut iter = slice.iter_at(slice.measure(), usize::cmp);
1228        // Yields None, since we're iterating in the middle of a Width(4) element.
1229        assert_eq!(iter.next(), None);
1230    }
1231
1232    #[test]
1233    #[cfg_attr(miri, ignore)]
1234    fn iter_at_sliced_03() {
1235        let rope = Rope::from_slice(pseudo_random().as_slice());
1236
1237        let slice_start = 34;
1238        let slice_end = 300;
1239        let slice_start_byte = rope.start_measure_to_index(slice_start, usize::cmp);
1240        let s_end_byte = rope.end_measure_to_index(slice_end, usize::cmp);
1241
1242        let slice_1 = rope.measure_slice(slice_start..slice_end, usize::cmp);
1243        let slice_2 = &pseudo_random()[slice_start_byte..s_end_byte];
1244
1245        let mut bytes_1 = slice_1.iter_at(slice_1.measure(), usize::cmp);
1246        let mut bytes_2 = slice_2.iter().copied();
1247        while let Some(b) = bytes_2.next_back() {
1248            assert_eq!(bytes_1.prev().map(|(_, element)| element), Some(b));
1249        }
1250    }
1251
1252    #[test]
1253    #[cfg_attr(miri, ignore)]
1254    fn iter_at_sliced_reverse_01() {
1255        let rope = Rope::from_slice(pseudo_random().as_slice());
1256
1257        let slice_start = 34;
1258        let slice_end = 301;
1259        let slice = rope.measure_slice(slice_start..slice_end, usize::cmp);
1260
1261        let mut iter = slice.iter_at(slice.len() / 3, usize::cmp);
1262        let mut stack = Vec::new();
1263        for _ in 0..32 {
1264            stack.push(iter.next().unwrap());
1265        }
1266        iter.reverse();
1267        for _ in 0..32 {
1268            assert_eq!(stack.pop(), iter.next());
1269        }
1270    }
1271
1272    #[test]
1273    #[cfg_attr(miri, ignore)]
1274    fn chunks_sliced_01() {
1275        let rope = Rope::from_slice(pseudo_random().as_slice());
1276
1277        let slice_start = 34;
1278        let slice_end = 301;
1279        let slice_start_index = rope.start_measure_to_index(slice_start, usize::cmp);
1280        let slice_end_index = rope.end_measure_to_index(slice_end, usize::cmp);
1281
1282        let slice_1 = rope.measure_slice(slice_start..slice_end, usize::cmp);
1283        let slice_2 = &pseudo_random()[slice_start_index..slice_end_index];
1284
1285        let mut index = 0;
1286        for chunk in slice_1.chunks() {
1287            assert_eq!(chunk, &slice_2[index..(index + chunk.len())]);
1288            index += chunk.len();
1289        }
1290
1291        assert_eq!(index, slice_2.len());
1292    }
1293
1294    #[test]
1295    #[cfg_attr(miri, ignore)]
1296    fn chunks_sliced_reverse_01() {
1297        let rope = Rope::from_slice(pseudo_random().as_slice());
1298
1299        let slice_start = 34;
1300        let slice_end = 301;
1301        let slice = rope.measure_slice(slice_start..slice_end, usize::cmp);
1302
1303        let mut iter = slice.chunks();
1304        let mut stack = Vec::new();
1305        for _ in 0..8 {
1306            stack.push(iter.next().unwrap());
1307        }
1308        iter.reverse();
1309        for _ in 0..8 {
1310            assert_eq!(stack.pop(), iter.next());
1311        }
1312    }
1313
1314    #[test]
1315    #[cfg_attr(miri, ignore)]
1316    fn empty_iter() {
1317        let rope = Rope::<Width>::from_slice(&[]);
1318        let rope: Vec<Width> = rope.iter().map(|(_, element)| element).collect();
1319        assert_eq!(&*rope, [].as_slice())
1320    }
1321}