any_rope/
rope.rs

1use std::{cmp::Ordering, iter::FromIterator, ops::RangeBounds, sync::Arc};
2
3use crate::{
4    end_bound_to_num,
5    iter::{Chunks, Iter},
6    measures_from_range,
7    rope_builder::RopeBuilder,
8    slice::RopeSlice,
9    slice_utils::{end_measure_to_index, index_to_measure, start_measure_to_index},
10    start_bound_to_num,
11    tree::{max_children, max_len, min_len, BranchChildren, Node, SliceInfo},
12    Error, FallibleOrd, Measurable, MeasureRange, Result,
13};
14
15/// A rope of elements that are [`Measurable`].
16///
17/// The time complexity of nearly all edit and query operations on [`Rope<M>`]
18/// are worst-case `O(log N)` in the length of the rope. [`Rope<M>`] is designed
19/// to work efficiently even for huge (in the gigabytes) arrays of
20/// [`M`][Measurable].
21///
22/// In the examples below, a struct called [`Width`][crate::Width] will be used
23/// in order to demonstrate AnyRope's features.
24///
25/// # Editing Operations
26///
27/// The primary editing operations on [`Rope<M>`] are insertion and removal of
28/// slices or individual elements.
29/// For example:
30///
31/// ```
32/// # use any_rope::{Rope, Width};
33/// let mut rope = Rope::from_slice(&[
34///     Width(1),
35///     Width(2),
36///     Width(3),
37///     Width(0),
38///     Width(0),
39///     Width(2),
40///     Width(1),
41/// ]);
42/// rope.remove_inclusive(6..8, usize::cmp);
43/// rope.insert(6, Width(5), usize::cmp);
44///
45/// assert_eq!(
46///     rope,
47///     [Width(1), Width(2), Width(3), Width(5), Width(1)].as_slice()
48/// );
49/// ```
50///
51/// # Query Operations
52///
53/// [`Rope<M>`] gives you the ability to query an element at any given index or
54/// measure, and the convertion between the two. You can either convert an index
55/// to a measure, or convert the measure at the start or end of an element to an
56/// index. For example:
57///
58/// ```rust
59/// # use any_rope::{Rope, Width};
60/// let rope = Rope::from_slice(&[
61///     Width(0),
62///     Width(0),
63///     Width(1),
64///     Width(1),
65///     Width(2),
66///     Width(25),
67///     Width(0),
68///     Width(0),
69///     Width(1),
70/// ]);
71///
72/// // `start_measure_to_index()` will pick the first element that starts at the given index.
73/// assert_eq!(rope.start_measure_to_index(0, usize::cmp), 0);
74/// // `end_measure_to_index()` will pick the last element that still starts at the given index.
75/// assert_eq!(rope.end_measure_to_index(0, usize::cmp), 2);
76/// assert_eq!(rope.start_measure_to_index(2, usize::cmp), 4);
77/// assert_eq!(rope.start_measure_to_index(3, usize::cmp), 4);
78/// assert_eq!(rope.start_measure_to_index(16, usize::cmp), 5);
79/// assert_eq!(rope.start_measure_to_index(29, usize::cmp), 6);
80/// ```
81///
82/// # Slicing
83///
84/// You can take immutable slices of a [`Rope<M>`] using
85/// [`measure_slice()`][Rope::measure_slice]
86/// or [`index_slice()`][Rope::index_slice]:
87///
88/// ```rust
89/// # use any_rope::{Rope, Width};
90/// let mut rope = Rope::from_slice(&[
91///     Width(1),
92///     Width(2),
93///     Width(3),
94///     Width(0),
95///     Width(0),
96///     Width(2),
97///     Width(1),
98/// ]);
99/// let measure_slice = rope.measure_slice(3..6, usize::cmp);
100/// let index_slice = rope.index_slice(2..5);
101///
102/// assert_eq!(measure_slice, index_slice);
103/// ```
104///
105/// # Cloning
106///
107/// Cloning [`Rope<M>`]s is extremely cheap, running in `O(1)` time and taking a
108/// small constant amount of memory for the new clone, regardless of slice size.
109/// This is accomplished by data sharing between [`Rope<M>`] clones. The memory
110/// used by clones only grows incrementally as the their contents diverge due
111/// to edits. All of this is thread safe, so clones can be sent freely
112/// between threads.
113///
114/// The primary intended use-case for this feature is to allow asynchronous
115/// processing of [`Rope<M>`]s.
116#[derive(Clone)]
117pub struct Rope<M>
118where
119    M: Measurable,
120    [(); max_len::<M, M::Measure>()]: Sized,
121    [(); max_children::<M, M::Measure>()]: Sized,
122{
123    pub(crate) root: Arc<Node<M>>,
124}
125
126impl<M> Rope<M>
127where
128    M: Measurable,
129    [(); max_len::<M, M::Measure>()]: Sized,
130    [(); max_children::<M, M::Measure>()]: Sized,
131{
132    //-----------------------------------------------------------------------
133    // Constructors
134
135    /// Creates an empty [`Rope<M>`].
136    #[inline]
137    pub fn new() -> Self {
138        Rope {
139            root: Arc::new(Node::new()),
140        }
141    }
142
143    /// Creates a [`Rope<M>`] from an [`M`][Measurable] slice.
144    ///
145    /// Runs in O(N) time.
146    #[inline]
147    #[allow(clippy::should_implement_trait)]
148    pub fn from_slice(slice: &[M]) -> Self {
149        RopeBuilder::new().build_at_once(slice)
150    }
151
152    //-----------------------------------------------------------------------
153    // Informational methods
154
155    /// Total number of elements in [`Rope<M>`].
156    ///
157    /// Runs in O(N) time.
158    #[inline]
159    pub fn len(&self) -> usize {
160        self.root.len()
161    }
162
163    /// Returns `true` if the [`Rope<M>`] is empty.
164    ///
165    /// Runs in O(N) time.
166    #[inline]
167    pub fn is_empty(&self) -> bool {
168        self.root.len() == 0
169    }
170
171    /// Sum of all measures of in [`Rope<M>`].
172    ///
173    /// Runs in O(N) time.
174    #[inline]
175    pub fn measure(&self) -> M::Measure {
176        self.root.measure()
177    }
178
179    //-----------------------------------------------------------------------
180    // Memory management methods
181
182    /// Total size of the [`Rope<M>`]'s buffer space.
183    ///
184    /// This includes unoccupied buffer space. You can calculate
185    /// the unoccupied space with `Rope::capacity() - Rope::len()`. In general,
186    /// there will always be some unoccupied buffer space.
187    ///
188    /// Runs in O(N) time.
189    #[inline]
190    pub fn capacity(&self) -> usize {
191        let mut count = 0;
192        for chunk in self.chunks() {
193            count += chunk.len().max(max_len::<M, M::Measure>());
194        }
195        count
196    }
197
198    /// Shrinks the [`Rope<M>`]'s capacity to the minimum possible.
199    ///
200    /// This will rarely result in `Rope::capacity() == Rope::len()`.
201    /// [`Rope<M>`] stores [`M`][Measurable]s in a sequence of
202    /// fixed-capacity chunks, so an exact fit only happens for lists of a
203    /// lenght that is a multiple of that capacity.
204    ///
205    /// After calling this, the difference between `capacity()` and
206    /// `len()` is typically under 1000 for each 1000000 [`M`][Measurable] in
207    /// the [`Rope<M>`].
208    ///
209    /// **NOTE:** calling this on a [`Rope<M>`] clone causes it to stop sharing
210    /// all data with its other clones. In such cases you will very likely
211    /// be _increasing_ total memory usage despite shrinking the [`Rope<M>`]'s
212    /// capacity.
213    ///
214    /// Runs in O(N) time, and uses O(log N) additional space during
215    /// shrinking.
216    #[inline]
217    pub fn shrink_to_fit(&mut self) {
218        let mut node_stack = Vec::new();
219        let mut builder = RopeBuilder::new();
220
221        node_stack.push(self.root.clone());
222        *self = Rope::new();
223
224        loop {
225            if node_stack.is_empty() {
226                break;
227            }
228
229            if node_stack.last().unwrap().is_leaf() {
230                builder.append_slice(node_stack.pop().unwrap().leaf_slice());
231            } else if node_stack.last().unwrap().child_count() == 0 {
232                node_stack.pop();
233            } else {
234                let (_, next_node) = Arc::make_mut(node_stack.last_mut().unwrap())
235                    .children_mut()
236                    .remove(0);
237                node_stack.push(next_node);
238            }
239        }
240
241        *self = builder.finish();
242    }
243
244    //-----------------------------------------------------------------------
245    // Edit methods
246
247    /// Inserts [`slice`][Measurable] at `measure`.
248    ///
249    /// Runs in O(L + log N) time, where N is the length of the [`Rope<M>`] and
250    /// L is the length of [`slice`][Measurable].
251    ///
252    /// # Panics
253    ///
254    /// Panics if the `measure` is out of bounds (i.e. `measure >
255    /// Rope::measure()`).
256    #[inline]
257    pub fn insert_slice(
258        &mut self,
259        measure: M::Measure,
260        slice: &[M],
261        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
262    ) {
263        // Bounds check
264        self.try_insert_slice(measure, slice, cmp).unwrap()
265    }
266
267    /// Inserts a single [`M`][Measurable] at `measure`.
268    ///
269    /// Runs in O(log N) time.
270    ///
271    /// # Panics
272    ///
273    /// Panics if the `measure` is out of bounds (i.e. `measure >
274    /// Rope::measure()`).
275    #[inline]
276    pub fn insert(
277        &mut self,
278        measure: M::Measure,
279        measurable: M,
280        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
281    ) {
282        self.try_insert(measure, measurable, &cmp).unwrap()
283    }
284
285    /// Private internal-only method that does a single insertion of
286    /// a sufficiently small slice.
287    ///
288    /// This only works correctly for insertion slices smaller than or equal to
289    /// `MAX_BYTES - 4`.
290    #[inline]
291    fn insert_internal(
292        &mut self,
293        measure: M::Measure,
294        slice: &[M],
295        cmp: &impl Fn(&M::Measure, &M::Measure) -> Ordering,
296    ) {
297        let root_info = self.root.info();
298
299        let (l_info, residual) = Arc::make_mut(&mut self.root).edit_chunk_at_measure(
300            measure,
301            cmp,
302            root_info,
303            |index, cur_info, leaf_slice| {
304                // Find our index
305                let index = end_measure_to_index(leaf_slice, index, cmp);
306
307                // No node splitting
308                if (leaf_slice.len() + slice.len()) <= max_len::<M, M::Measure>() {
309                    // Calculate new info without doing a full re-scan of cur_slice.
310                    let new_info = cur_info + SliceInfo::<M::Measure>::from_slice(slice);
311                    leaf_slice.insert_slice(index, slice);
312                    (new_info, None)
313                }
314                // We're splitting the node
315                else {
316                    let r_slice = leaf_slice.insert_slice_split(index, slice);
317                    let l_slice_info = SliceInfo::<M::Measure>::from_slice(leaf_slice);
318                    if r_slice.len() > 0 {
319                        let r_slice_info = SliceInfo::<M::Measure>::from_slice(&r_slice);
320                        (
321                            l_slice_info,
322                            Some((r_slice_info, Arc::new(Node::Leaf(r_slice)))),
323                        )
324                    } else {
325                        // Leaf couldn't be validly split, so leave it oversized
326                        (l_slice_info, None)
327                    }
328                }
329            },
330        );
331
332        // Handle root splitting, if any.
333        if let Some((r_info, r_node)) = residual {
334            let mut l_node = Arc::new(Node::new());
335            std::mem::swap(&mut l_node, &mut self.root);
336
337            let mut children = BranchChildren::new();
338            children.push((l_info, l_node));
339            children.push((r_info, r_node));
340
341            *Arc::make_mut(&mut self.root) = Node::Branch(children);
342        }
343    }
344
345    /// Removes the slice in the given measure range.
346    ///
347    /// Uses range syntax, e.g. `2..7`, `2..`, etc.
348    ///
349    /// Runs in O(M + log N) time, where N is the length of the [`Rope<M>`] and
350    /// M is the length of the range being removed.
351    ///
352    /// The first removed [`M`][Measurable] will be the first with a end measure
353    /// sum greater than the starting bound if its
354    /// [`measure()`][Measurable::measure] is greater than 0, or equal to the
355    /// starting bound if its [`measure()`][Measurable::measure] is equal to 0.
356    ///
357    /// The last removed [`M`][Measurable] will be the first with a start
358    /// measure sum greater than the ending bound if its
359    /// [`measure()`][Measurable::measure] is greater than 0, or the last one
360    /// with a start measure sum equal to the ending bound if its
361    /// [`measure()`][Measurable::measure] is equal to 0.
362    ///
363    /// In essence, this means the following:
364    /// - A range starting between a [`M`][Measurable]'s start and end measure
365    ///   sums will remove
366    /// said [`M`][Measurable].
367    /// - A range ending in the start of a list of 0 measure [`M`][Measurable]s
368    ///   will remove
369    /// all of them.
370    /// - An empty range that starts and ends in a list of 0 measure
371    ///   [`M`][Measurable]s will
372    /// remove all of them, and nothing else. This contrasts with Rust's usual
373    /// definition of an empty range.
374    ///
375    /// # Examples
376    ///
377    /// ```rust
378    /// # use any_rope::{Rope, Width};
379    /// let array = [
380    ///     Width(1),
381    ///     Width(2),
382    ///     Width(3),
383    ///     Width(0),
384    ///     Width(0),
385    ///     Width(2),
386    ///     Width(1),
387    /// ];
388    /// let mut rope = Rope::from_slice(&array);
389    ///
390    /// // Removing in the middle of `Width(3)`.
391    /// rope.remove_inclusive(5.., usize::cmp);
392    ///
393    /// assert_eq!(rope, [Width(1), Width(2)].as_slice());
394    /// ```
395    /// ```rust
396    /// # use any_rope::{Rope, Width};
397    /// let array = [
398    ///     Width(1),
399    ///     Width(2),
400    ///     Width(3),
401    ///     Width(0),
402    ///     Width(0),
403    ///     Width(2),
404    ///     Width(1),
405    /// ];
406    /// let mut rope = Rope::from_slice(&array);
407    ///
408    /// // End bound coincides with a 0 measure list.
409    /// rope.remove_inclusive(1..6, usize::cmp);
410    ///
411    /// assert_eq!(rope, [Width(1), Width(2), Width(1)].as_slice());
412    /// ```
413    /// ```rust
414    /// # use any_rope::{Rope, Width};
415    /// let array = [
416    ///     Width(1),
417    ///     Width(2),
418    ///     Width(3),
419    ///     Width(0),
420    ///     Width(0),
421    ///     Width(2),
422    ///     Width(1),
423    /// ];
424    /// let mut rope = Rope::from_slice(&array);
425    ///
426    /// // Empty range at the start of a 0 measure list.
427    /// rope.remove_inclusive(6..6, usize::cmp);
428    ///
429    /// // Inclusively removing an empty range does nothing.
430    /// assert_eq!(
431    ///     rope,
432    ///     [Width(1), Width(2), Width(3), Width(2), Width(1)].as_slice()
433    /// );
434    /// ```
435    ///
436    /// # Panics
437    ///
438    /// Panics if the start of the range is greater than the end, or if the
439    /// end is out of bounds (i.e. `end > self.measure()`).
440    #[inline]
441    pub fn remove_inclusive(
442        &mut self,
443        range: impl MeasureRange<M>,
444        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
445    ) {
446        self.try_remove_inclusive(range, cmp).unwrap()
447    }
448
449    /// Same as [`remove_inclusive()`][Rope::remove_inclusive], but keeps
450    /// elements measure measure equal to 0 at the edges.
451    ///
452    /// If the `measure_range` doesn't cover the entire measure of a single
453    /// [`M`][Measurable], then the removal does nothing.
454    ///
455    /// # Examples
456    ///
457    /// ```rust
458    /// # use any_rope::{Rope, Width};
459    /// let array = [
460    ///     Width(1),
461    ///     Width(2),
462    ///     Width(3),
463    ///     Width(0),
464    ///     Width(0),
465    ///     Width(2),
466    ///     Width(1),
467    /// ];
468    /// let mut rope = Rope::from_slice(&array);
469    ///
470    /// // End bound coincides with a 0 measure list, which does not get removed.
471    /// rope.remove_exclusive(1..6, usize::cmp);
472    ///
473    /// assert_eq!(
474    ///     rope,
475    ///     [Width(1), Width(0), Width(0), Width(2), Width(1)].as_slice()
476    /// );
477    /// ```
478    /// ```rust
479    /// # use any_rope::{Rope, Width};
480    /// let array = [
481    ///     Width(1),
482    ///     Width(2),
483    ///     Width(3),
484    ///     Width(0),
485    ///     Width(0),
486    ///     Width(2),
487    ///     Width(1),
488    /// ];
489    /// let mut rope = Rope::from_slice(&array);
490    ///
491    /// // Empty range at the start of a 0 measure list.
492    /// rope.remove_exclusive(6..6, usize::cmp);
493    ///
494    /// // Exclusively removing an empty range does nothing.
495    /// assert_eq!(rope, array.as_slice());
496    /// ```
497    /// ```rust
498    /// # use any_rope::{Rope, Width};
499    /// let array = [
500    ///     Width(1),
501    ///     Width(2),
502    ///     Width(3),
503    ///     Width(0),
504    ///     Width(0),
505    ///     Width(2),
506    ///     Width(1),
507    /// ];
508    /// let mut rope = Rope::from_slice(&array);
509    ///
510    /// // Removing in the middle of `Width(3)`.
511    /// rope.remove_exclusive(5..6, usize::cmp);
512    ///
513    /// // Exclusively removing in the middle of an element does nothing.
514    /// assert_eq!(rope, array.as_slice());
515    /// ```
516    ///
517    /// # Panics
518    ///
519    /// Panics if the start of the range is greater than the end, or if the
520    /// end is out of bounds (i.e. `end > self.measure()`).
521    #[inline]
522    pub fn remove_exclusive(
523        &mut self,
524        range: impl MeasureRange<M>,
525        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
526    ) {
527        self.try_remove_exclusive(range, cmp).unwrap()
528    }
529
530    /// Splits the [`Rope<M>`] at `measure`, returning the right part of the
531    /// split.
532    ///
533    /// Runs in O(log N) time.
534    ///
535    /// # Panics
536    ///
537    /// Panics if the `measure` is out of bounds (i.e. `measure >
538    /// self.measure()`).
539    #[inline]
540    pub fn split_off(
541        &mut self,
542        measure: M::Measure,
543        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
544    ) -> Self {
545        self.try_split_off(measure, cmp).unwrap()
546    }
547
548    /// Appends a [`Rope<M>`] to the end of this one, consuming the other
549    /// [`Rope<M>`].
550    ///
551    /// Runs in O(log N) time.
552    #[inline]
553    pub fn append(&mut self, other: Self) {
554        if other.measure().fallible_cmp(&M::Measure::default()).is_gt() {
555            let left_info = self.root.info();
556            let right_info = other.root.info();
557
558            let l_depth = self.root.depth();
559            let r_depth = other.root.depth();
560
561            if l_depth > r_depth {
562                let extra =
563                    Arc::make_mut(&mut self.root).append_at_depth(other.root, l_depth - r_depth);
564                if let Some(node) = extra {
565                    let mut children = BranchChildren::new();
566                    children.push((self.root.info(), Arc::clone(&self.root)));
567                    children.push((node.info(), node));
568                    self.root = Arc::new(Node::Branch(children));
569                }
570            } else {
571                let mut other = other;
572                let extra = Arc::make_mut(&mut other.root)
573                    .prepend_at_depth(Arc::clone(&self.root), r_depth - l_depth);
574                if let Some(node) = extra {
575                    let mut children = BranchChildren::new();
576                    children.push((node.info(), node));
577                    children.push((other.root.info(), Arc::clone(&other.root)));
578                    other.root = Arc::new(Node::Branch(children));
579                }
580                *self = other;
581            };
582
583            // Fix up any mess left behind.
584            let root = Arc::make_mut(&mut self.root);
585            if (left_info.len as usize) < min_len::<M, M::Measure>()
586                || (right_info.len as usize) < min_len::<M, M::Measure>()
587            {
588                root.fix_tree_seam(left_info.measure, &M::Measure::fallible_cmp);
589            }
590            self.pull_up_singular_nodes();
591        }
592    }
593
594    //-----------------------------------------------------------------------
595    // Index conversion methods
596
597    /// Returns the measure sum at the start of the given index.
598    ///
599    /// Notes:
600    ///
601    /// Runs in O(log N) time.
602    ///
603    /// # Panics
604    ///
605    /// Panics if the `index` is out of bounds (i.e. `index > Rope::len()`).
606    #[inline]
607    pub fn index_to_measure(&self, index: usize) -> M::Measure {
608        self.try_index_to_measure(index).unwrap()
609    }
610
611    /// Returns an index, given a starting measure sum.
612    ///
613    /// Runs in O(log N) time.
614    ///
615    /// # Panics
616    ///
617    /// Panics if the `measure` is out of bounds (i.e. `measure >
618    /// Rope::measure()`).
619    #[inline]
620    pub fn start_measure_to_index(
621        &self,
622        measure: M::Measure,
623        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
624    ) -> usize {
625        self.try_start_measure_to_index(measure, cmp).unwrap()
626    }
627
628    /// Returns an index, given an ending measure sum.
629    ///
630    /// Runs in O(log N) time.
631    ///
632    /// # Panics
633    ///
634    /// Panics if the `measure` is out of bounds (i.e. `measure >
635    /// Rope::measure()`).
636    #[inline]
637    pub fn end_measure_to_index(
638        &self,
639        measure: M::Measure,
640        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
641    ) -> usize {
642        self.try_end_measure_to_index(measure, cmp).unwrap()
643    }
644
645    //-----------------------------------------------------------------------
646    // Fetch methods
647
648    /// Returns the [`M`][Measurable] at `index` and the starting measure sum of
649    /// that element.
650    ///
651    /// Runs in O(log N) time.
652    ///
653    /// # Panics
654    ///
655    /// Panics if the `index` is out of bounds (i.e. `index > Rope::len()`).
656    #[inline]
657    pub fn from_index(&self, index: usize) -> (M::Measure, M) {
658        // Bounds check
659        if let Some(out) = self.get_from_index(index) {
660            out
661        } else {
662            panic!(
663                "Attempt to index past end of Rope: index {}, Rope length {}",
664                index,
665                self.len()
666            );
667        }
668    }
669
670    /// Returns the [`M`][Measurable] at `measure` and the starting measure sum
671    /// of that element.
672    ///
673    /// Runs in O(log N) time.
674    ///
675    /// # Panics
676    ///
677    /// Panics if the `measure` is out of bounds (i.e. `measure >
678    /// Rope::measure()`).
679    #[inline]
680    pub fn from_measure(
681        &self,
682        measure: M::Measure,
683        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
684    ) -> (M::Measure, M) {
685        if let Some(out) = self.get_from_measure(measure, cmp) {
686            out
687        } else {
688            panic!(
689                "Attempt to index past end of Rope: measure {:?}, Total rope measure is {:?}",
690                measure,
691                self.measure()
692            );
693        }
694    }
695
696    /// Returns the chunk containing the given index.
697    ///
698    /// Also returns the index and widht of the beginning of the chunk.
699    ///
700    /// Note: for convenience, a one-past-the-end `index` returns the last
701    /// chunk of the `RopeSlice`.
702    ///
703    /// The return value is organized as
704    /// `(chunk, chunk_index, chunk_measure)`.
705    ///
706    /// Runs in O(log N) time.
707    ///
708    /// # Panics
709    ///
710    /// Panics if the `index` is out of bounds (i.e. `index > Rope::len()`).
711    #[inline]
712    pub fn chunk_at_index(&self, index: usize) -> (&[M], usize, M::Measure) {
713        // Bounds check
714        if let Some(out) = self.get_chunk_at_index(index) {
715            out
716        } else {
717            panic!(
718                "Attempt to index past end of Rope: index {}, Rope length {}",
719                index,
720                self.len()
721            );
722        }
723    }
724
725    /// Returns the chunk containing the given measure.
726    ///
727    /// Also returns the index and measure of the beginning of the chunk.
728    ///
729    /// Note: for convenience, a one-past-the-end `measure` returns the last
730    /// chunk of the `RopeSlice`.
731    ///
732    /// The return value is organized as
733    /// `(chunk, chunk_index, chunk_measure)`.
734    ///
735    /// Runs in O(log N) time.
736    ///
737    /// # Panics
738    ///
739    /// Panics if the `measure` is out of bounds (i.e. `measure >
740    /// Rope::measure()`).
741    #[inline]
742    pub fn chunk_at_measure(
743        &self,
744        measure: M::Measure,
745        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
746    ) -> (&[M], usize, M::Measure) {
747        if let Some(out) = self.get_chunk_at_measure(measure, &cmp) {
748            out
749        } else {
750            panic!(
751                "Attempt to index past end of Rope: measure {:?}, Rope measure {:?}",
752                measure,
753                self.measure()
754            );
755        }
756    }
757
758    //-----------------------------------------------------------------------
759    // Slicing
760
761    /// Gets an immutable slice of the [`Rope<M>`], using a measure range.
762    ///
763    /// Uses range syntax, e.g. `2..7`, `2..`, etc.
764    ///
765    /// # Example
766    ///
767    /// ```rust
768    /// # use any_rope::{Rope, Width};
769    /// let mut rope = Rope::from_slice(&[
770    ///     Width(1),
771    ///     Width(2),
772    ///     Width(3),
773    ///     Width(0),
774    ///     Width(0),
775    ///     Width(2),
776    ///     Width(1),
777    /// ]);
778    /// let slice = rope.measure_slice(..5, usize::cmp);
779    ///
780    /// assert_eq!(slice, [Width(1), Width(2), Width(3)].as_slice());
781    /// ```
782    ///
783    /// Runs in O(log N) time.
784    ///
785    /// # Panics
786    ///
787    /// Panics if the start of the range is greater than the end, or if the
788    /// end is out of bounds (i.e. `end > Rope::measure()`).
789    #[inline]
790    pub fn measure_slice(
791        &self,
792        measure_range: impl MeasureRange<M>,
793        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
794    ) -> RopeSlice<M> {
795        self.get_measure_slice(measure_range, cmp).unwrap()
796    }
797
798    /// Gets and immutable slice of the [`Rope<M>`], using an index range.
799    ///
800    /// Uses range syntax, e.g. `2..7`, `2..`, etc.
801    ///
802    /// Runs in O(log N) time.
803    ///
804    /// # Panics
805    ///
806    /// Panics if:
807    /// - The start of the range is greater than the end.
808    /// - The end is out of bounds (i.e. `end > Rope::len()`).
809    #[inline]
810    pub fn index_slice(&self, index_range: impl RangeBounds<usize>) -> RopeSlice<M> {
811        match self.get_index_slice_impl(index_range) {
812            Ok(s) => return s,
813            Err(e) => panic!("index_slice(): {}", e),
814        }
815    }
816
817    //-----------------------------------------------------------------------
818    // Iterator methods
819
820    /// Creates an iterator over the [`Rope<M>`].
821    ///
822    /// This iterator will return values of type [Option<(usize, M)>], where the
823    /// `usize` is the measure sum where the given [`M`][Measurable] starts.
824    ///
825    /// Runs in O(log N) time.
826    #[inline]
827    pub fn iter(&self) -> Iter<M> {
828        Iter::new(&self.root)
829    }
830
831    /// Creates an iterator over the  [`Rope<M>`], starting at `measure`.
832    ///
833    /// This iterator will return values of type [`Option<(usize, M)>`], where
834    /// the `usize` is the measure where the given [`M`][Measurable] starts.
835    /// Since one can iterate in between an [`M`][Measurable]s start and end
836    /// measure sums. the first `usize` may not actually corelate to the
837    /// `measure` given to the function.
838    ///
839    /// If `measure == Rope::measure()` then an iterator at the end of the
840    /// [`Rope<M>`] is created (i.e. [`next()`][crate::iter::Iter::next] will
841    /// return [`None`]).
842    ///
843    /// Runs in O(log N) time.
844    ///
845    /// # Panics
846    ///
847    /// Panics if the `measure` is out of bounds (i.e. `measure >
848    /// Rope::measure()`).
849    #[inline]
850    pub fn iter_at_measure(
851        &self,
852        measure: M::Measure,
853        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
854    ) -> Iter<M> {
855        if let Some(out) = self.get_iter_at_measure(measure, cmp) {
856            out
857        } else {
858            panic!(
859                "Attempt to index past end of Rope: measure {:?}, Rope measure {:?}",
860                measure,
861                self.measure()
862            );
863        }
864    }
865
866    /// Creates an iterator over the chunks of the [`Rope<M>`].
867    ///
868    /// Runs in O(log N) time.
869    #[inline]
870    pub fn chunks(&self) -> Chunks<M> {
871        Chunks::new(&self.root)
872    }
873
874    /// Creates an iterator over the chunks of the [`Rope<M>`], with the
875    /// iterator starting at the chunk containing the `index`.
876    ///
877    /// Also returns the index and measure of the beginning of the first
878    /// chunk to be yielded.
879    ///
880    /// If `index == Rope::len()` an iterator at the end of the [`Rope<M>`]
881    /// (yielding [`None`] on a call to [`next()`][crate::iter::Iter::next]) is
882    /// created.
883    ///
884    /// The return value is organized as `(iterator, chunk_index,
885    /// chunk_measure)`.
886    ///
887    /// Runs in O(log N) time.
888    ///
889    /// # Panics
890    ///
891    /// Panics if the `index` is out of bounds (i.e. `index > Rope::len()`).
892    #[inline]
893    pub fn chunks_at_index(&self, index: usize) -> (Chunks<M>, usize, M::Measure) {
894        if let Some(out) = self.get_chunks_at_index(index) {
895            out
896        } else {
897            panic!(
898                "Attempt to index past end of Rope: index {}, Rope length {}",
899                index,
900                self.len()
901            );
902        }
903    }
904
905    /// Creates an iterator over the chunks of the [`Rope<M>`], with the
906    /// iterator starting at the chunk containing the `measure`.
907    ///
908    /// Also returns the index and measure of the beginning of the first
909    /// chunk to be yielded.
910    ///
911    /// If `measure == Rope::measure()` an iterator at the end of the
912    /// [`Rope<M>`] (yielding [`None`] on a call to
913    /// [`next()`][crate::iter::Iter::next]) is created.
914    ///
915    /// The return value is organized as `(iterator, chunk_index,
916    /// chunk_measure)`.
917    ///
918    /// Runs in O(log N) time.
919    ///
920    /// # Panics
921    ///
922    /// Panics if the `measure` is out of bounds (i.e. `measure >
923    /// Rope::measure()`).
924    #[inline]
925    pub fn chunks_at_measure(
926        &self,
927        measure: M::Measure,
928        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
929    ) -> (Chunks<M>, usize, M::Measure) {
930        if let Some(out) = self.get_chunks_at_measure(measure, &cmp) {
931            out
932        } else {
933            panic!(
934                "Attempt to index past end of Rope: measure {:?}, Rope measure {:?}",
935                measure,
936                self.measure()
937            );
938        }
939    }
940
941    /// Returns true if this rope and `other` point to precisely the same
942    /// in-memory data.
943    ///
944    /// This happens when one of the ropes is a clone of the other and
945    /// neither have been modified since then. Because clones initially
946    /// share all the same data, it can be useful to check if they still
947    /// point to precisely the same memory as a way of determining
948    /// whether they are both still unmodified.
949    ///
950    /// Note: this is distinct from checking for equality: two ropes can
951    /// have the same *contents* (equal) but be stored in different
952    /// memory locations (not instances). Importantly, two clones that
953    /// post-cloning are modified identically will *not* be instances
954    /// anymore, even though they will have equal contents.
955    ///
956    /// Runs in O(1) time.
957    #[inline]
958    pub fn is_instance(&self, other: &Self) -> bool {
959        Arc::ptr_eq(&self.root, &other.root)
960    }
961
962    //-----------------------------------------------------------------------
963    // Debugging
964
965    /// NOT PART OF THE PUBLIC API (hidden from docs for a reason!)
966    ///
967    /// Debugging tool to make sure that all of the meta-data of the
968    /// tree is consistent with the actual data.
969    #[doc(hidden)]
970    pub fn assert_integrity(&self) {
971        self.root.assert_integrity();
972    }
973
974    /// NOT PART OF THE PUBLIC API (hidden from docs for a reason!)
975    ///
976    /// Debugging tool to make sure that all of the following invariants
977    /// hold true throughout the tree:
978    ///
979    /// - The tree is the same height everywhere.
980    /// - All internal nodes have the minimum number of children.
981    /// - All leaf nodes are non-empty.
982    #[doc(hidden)]
983    pub fn assert_invariants(&self) {
984        self.root.assert_balance();
985        self.root.assert_node_size(true);
986    }
987
988    //-----------------------------------------------------------------------
989    // Internal utilities
990
991    /// Iteratively replaces the root node with its child if it only has
992    /// one child.
993    #[inline]
994    pub(crate) fn pull_up_singular_nodes(&mut self) {
995        while (!self.root.is_leaf()) && self.root.child_count() == 1 {
996            let child = if let Node::Branch(ref children) = *self.root {
997                Arc::clone(&children.nodes()[0])
998            } else {
999                unreachable!()
1000            };
1001
1002            self.root = child;
1003        }
1004    }
1005}
1006
1007/// # Non-Panicking
1008///
1009/// The methods in this impl block provide non-panicking versions of
1010/// [`Rope<M>`]'s panicking methods. They return either `Option::None` or
1011/// `Result::Err()` when their panicking counterparts would have panicked.
1012impl<M> Rope<M>
1013where
1014    M: Measurable,
1015    [(); max_len::<M, M::Measure>()]: Sized,
1016    [(); max_children::<M, M::Measure>()]: Sized,
1017{
1018    /// Non-panicking version of [`insert()`][Rope::insert].
1019    #[inline]
1020    pub fn try_insert_slice(
1021        &mut self,
1022        measure: M::Measure,
1023        mut slice: &[M],
1024        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
1025    ) -> Result<(), M> {
1026        // Bounds check
1027        if cmp(&measure, &self.measure()).is_le() {
1028            // We have three cases here:
1029            // 1. The insertion slice is very large, in which case building a new Rope out
1030            //    of it and splicing it into the existing Rope is most efficient.
1031            // 2. The insertion slice is somewhat large, in which case splitting it up into
1032            //    chunks and repeatedly inserting them is the most efficient. The splitting
1033            //    is necessary because the insertion code only works correctly below a
1034            //    certain insertion size.
1035            // 3. The insertion slice is small, in which case we can simply insert it.
1036            //
1037            // Cases #2 and #3 are rolled into one case here, where case #3 just
1038            // results in the slice being "split" into only one chunk.
1039            //
1040            // The boundary for what constitutes "very large" slice was arrived at
1041            // experimentally, by testing at what point Rope build + splice becomes
1042            // faster than split + repeated insert.
1043            if slice.len() > max_len::<M, M::Measure>() * 6 {
1044                // Case #1: very large slice, build rope and splice it in.
1045                let rope = Rope::from_slice(slice);
1046                let right = self.split_off(measure, &cmp);
1047                self.append(rope);
1048                self.append(right);
1049            } else {
1050                // Cases #2 and #3: split into chunks and repeatedly insert.
1051                while !slice.is_empty() {
1052                    // Split a chunk off from the end of the slice.
1053                    // We do this from the end instead of the front so that
1054                    // the repeated insertions can keep re-using the same
1055                    // insertion point.
1056                    let split_index = slice.len().saturating_sub(max_len::<M, M::Measure>() - 4);
1057                    let ins_slice = &slice[split_index..];
1058                    slice = &slice[..split_index];
1059
1060                    // Do the insertion.
1061                    self.insert_internal(measure, ins_slice, &cmp);
1062                }
1063            }
1064            Ok(())
1065        } else {
1066            Err(Error::MeasureOutOfBounds(measure, self.measure()))
1067        }
1068    }
1069
1070    /// Non-panicking version of [`insert()`][Rope::insert].
1071    #[inline]
1072    pub fn try_insert(
1073        &mut self,
1074        measure: M::Measure,
1075        measurable: M,
1076        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
1077    ) -> Result<(), M> {
1078        // Bounds check
1079        if cmp(&measure, &self.measure()).is_le() {
1080            self.insert_internal(measure, &[measurable], &cmp);
1081            Ok(())
1082        } else {
1083            Err(Error::MeasureOutOfBounds(measure, self.measure()))
1084        }
1085    }
1086
1087    /// Non-panicking version of [`remove_inclusive()`][Rope::remove_inclusive].
1088    #[inline]
1089    pub fn try_remove_inclusive(
1090        &mut self,
1091        range: impl MeasureRange<M>,
1092        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
1093    ) -> Result<(), M> {
1094        self.try_remove_internal(range, &cmp, true)
1095    }
1096
1097    /// Non-panicking version of [`remove_exclusive()`][Rope::remove_exclusive].
1098    #[inline]
1099    pub fn try_remove_exclusive(
1100        &mut self,
1101        range: impl MeasureRange<M>,
1102        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
1103    ) -> Result<(), M> {
1104        self.try_remove_internal(range, &cmp, false)
1105    }
1106
1107    fn try_remove_internal(
1108        &mut self,
1109        range: impl MeasureRange<M>,
1110        cmp: &impl Fn(&M::Measure, &M::Measure) -> Ordering,
1111        inclusive: bool,
1112    ) -> Result<(), M> {
1113        let (start, end) = measures_from_range(&range, self.measure())?;
1114
1115        if cmp(&start, &M::Measure::default()).is_eq()
1116            && cmp(&end, &self.measure()).is_eq()
1117            && inclusive
1118        {
1119            self.root = Arc::new(Node::new());
1120            Ok(())
1121        } else {
1122            let root = Arc::make_mut(&mut self.root);
1123
1124            let (_, needs_fix) = root.remove_range(start, end, &cmp, inclusive, inclusive);
1125
1126            if needs_fix {
1127                root.fix_tree_seam(start, &cmp);
1128            }
1129
1130            self.pull_up_singular_nodes();
1131            Ok(())
1132        }
1133    }
1134
1135    /// Non-panicking version of [`split_off()`][Rope::split_off].
1136    #[inline]
1137    pub fn try_split_off(
1138        &mut self,
1139        measure: M::Measure,
1140        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
1141    ) -> Result<Self, M> {
1142        // Bounds check
1143        if cmp(&measure, &self.measure()).is_le() {
1144            if measure == M::Measure::default() {
1145                // Special case 1
1146                let mut new_rope = Rope::new();
1147                std::mem::swap(self, &mut new_rope);
1148                Ok(new_rope)
1149            } else if measure == self.measure() {
1150                // Special case 2
1151                Ok(Rope::new())
1152            } else {
1153                // Do the split
1154                let mut new_rope = Rope {
1155                    root: Arc::new(Arc::make_mut(&mut self.root).end_split(measure, &cmp)),
1156                };
1157
1158                // Fix up the edges
1159                Arc::make_mut(&mut self.root).zip_fix_right();
1160                Arc::make_mut(&mut new_rope.root).zip_fix_left();
1161                self.pull_up_singular_nodes();
1162                new_rope.pull_up_singular_nodes();
1163
1164                Ok(new_rope)
1165            }
1166        } else {
1167            Err(Error::MeasureOutOfBounds(measure, self.measure()))
1168        }
1169    }
1170
1171    /// Non-panicking version of [`index_to_measure()`][Rope::index_to_measure].
1172    #[inline]
1173    pub fn try_index_to_measure(&self, index: usize) -> Result<M::Measure, M> {
1174        // Bounds check
1175        if index <= self.len() {
1176            let (chunk, b, c) = self.chunk_at_index(index);
1177            Ok(c + index_to_measure(chunk, index - b))
1178        } else {
1179            Err(Error::IndexOutOfBounds(index, self.len()))
1180        }
1181    }
1182
1183    /// Non-panicking version of
1184    /// [`start_measure_to_index()`][Rope::start_measure_to_index].
1185    #[inline]
1186    pub fn try_start_measure_to_index(
1187        &self,
1188        measure: M::Measure,
1189        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
1190    ) -> Result<usize, M> {
1191        // Bounds check
1192        if cmp(&measure, &self.measure()).is_le() {
1193            let (chunk, b, c) = self.chunk_at_measure(measure, &cmp);
1194            Ok(b + start_measure_to_index(chunk, measure - c, cmp))
1195        } else {
1196            Err(Error::MeasureOutOfBounds(measure, self.measure()))
1197        }
1198    }
1199
1200    /// Non-panicking version of
1201    /// [`end_measure_to_index()`][Rope::end_measure_to_index].
1202    #[inline]
1203    pub fn try_end_measure_to_index(
1204        &self,
1205        measure: M::Measure,
1206        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
1207    ) -> Result<usize, M> {
1208        // Bounds check
1209        if cmp(&measure, &self.measure()).is_le() {
1210            let (chunk, b, c) = self.chunk_at_measure(measure, &cmp);
1211            Ok(b + end_measure_to_index(chunk, measure - c, cmp))
1212        } else {
1213            Err(Error::MeasureOutOfBounds(measure, self.measure()))
1214        }
1215    }
1216
1217    /// Non-panicking version of [`from_index()`][Rope::from_index].
1218    #[inline]
1219    pub fn get_from_index(&self, index: usize) -> Option<(M::Measure, M)> {
1220        // Bounds check
1221        if index < self.len() {
1222            let (chunk, chunk_index, chunk_measure) = self.chunk_at_index(index);
1223            let index = index - chunk_index;
1224            let measure = index_to_measure(chunk, index);
1225            Some((measure + chunk_measure, chunk[index].clone()))
1226        } else {
1227            None
1228        }
1229    }
1230
1231    /// Non-panicking version of [`from_measure()`][Rope::from_measure].
1232    #[inline]
1233    pub fn get_from_measure(
1234        &self,
1235        measure: M::Measure,
1236        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
1237    ) -> Option<(M::Measure, M)> {
1238        // Bounds check
1239        if cmp(&measure, &self.measure()).is_lt() && !self.is_empty() {
1240            let (chunk, _, chunk_measure) = self.chunk_at_measure(measure, &cmp);
1241            let index = start_measure_to_index(chunk, measure - chunk_measure, cmp);
1242            let measure = index_to_measure(chunk, index);
1243            Some((measure + chunk_measure, chunk[index.min(chunk.len() - 1)].clone()))
1244        } else {
1245            None
1246        }
1247    }
1248
1249    /// Non-panicking version of [`chunk_at_index()`][Rope::chunk_at_index].
1250    #[inline]
1251    pub fn get_chunk_at_index(&self, index: usize) -> Option<(&[M], usize, M::Measure)> {
1252        // Bounds check
1253        if index <= self.len() {
1254            let (chunk, info) = self.root.get_chunk_at_index(index);
1255            Some((chunk, info.len as usize, info.measure))
1256        } else {
1257            None
1258        }
1259    }
1260
1261    /// Non-panicking version of [`chunk_at_measure()`][Rope::chunk_at_measure].
1262    #[inline]
1263    pub fn get_chunk_at_measure(
1264        &self,
1265        measure: M::Measure,
1266        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
1267    ) -> Option<(&[M], usize, M::Measure)> {
1268        // Bounds check
1269        if cmp(&measure, &self.measure()).is_lt() && !self.is_empty() {
1270            let (chunk, info) = self.root.get_first_chunk_at_measure(measure, &cmp);
1271            Some((chunk, info.len as usize, info.measure))
1272        } else {
1273            None
1274        }
1275    }
1276
1277    /// Non-panicking version of [`measure_slice()`][Rope::measure_slice].
1278    #[inline]
1279    pub fn get_measure_slice(
1280        &self,
1281        range: impl MeasureRange<M>,
1282        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
1283    ) -> Result<RopeSlice<M>, M> {
1284        let (start, end) = measures_from_range(&range, self.measure())?;
1285
1286        // Bounds check
1287        Ok(RopeSlice::new_with_range(&self.root, start, end, &cmp))
1288    }
1289
1290    /// Non-panicking version of [`index_slice()`][Rope::index_slice].
1291    #[inline]
1292    pub fn get_index_slice(&self, index_range: impl RangeBounds<usize>) -> Option<RopeSlice<M>> {
1293        self.get_index_slice_impl(index_range).ok()
1294    }
1295
1296    pub(crate) fn get_index_slice_impl(
1297        &self,
1298        index_range: impl RangeBounds<usize>,
1299    ) -> Result<RopeSlice<M>, M> {
1300        let start_range = start_bound_to_num(index_range.start_bound());
1301        let end_range = end_bound_to_num(index_range.end_bound());
1302
1303        // Bounds checks.
1304        match (start_range, end_range) {
1305            (Some(start), Some(end)) => {
1306                if start > end {
1307                    return Err(Error::IndexRangeInvalid(start, end));
1308                } else if end > self.len() {
1309                    return Err(Error::IndexRangeOutOfBounds(
1310                        start_range,
1311                        end_range,
1312                        self.len(),
1313                    ));
1314                }
1315            }
1316            (Some(s), None) => {
1317                if s > self.len() {
1318                    return Err(Error::IndexRangeOutOfBounds(
1319                        start_range,
1320                        end_range,
1321                        self.len(),
1322                    ));
1323                }
1324            }
1325            (None, Some(e)) => {
1326                if e > self.len() {
1327                    return Err(Error::IndexRangeOutOfBounds(None, end_range, self.len()));
1328                }
1329            }
1330            _ => {}
1331        }
1332
1333        let (start, end) = (
1334            start_range.unwrap_or(0),
1335            end_range.unwrap_or_else(|| self.len()),
1336        );
1337
1338        RopeSlice::new_with_index_range(&self.root, start, end)
1339    }
1340
1341    /// Non-panicking version of [`iter_at_measure()`][Rope::iter_at_measure].
1342    #[inline]
1343    pub fn get_iter_at_measure(
1344        &self,
1345        measure: M::Measure,
1346        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
1347    ) -> Option<Iter<M>> {
1348        // Bounds check
1349        if cmp(&measure, &self.measure()).is_le() {
1350            Some(Iter::new_with_range_at_measure(
1351                &self.root,
1352                measure,
1353                (0, self.len()),
1354                (M::Measure::default(), self.measure()),
1355                cmp,
1356            ))
1357        } else {
1358            None
1359        }
1360    }
1361
1362    /// Non-panicking version of [`chunks_at_index()`][Rope::chunks_at_index].
1363    #[inline]
1364    pub fn get_chunks_at_index(&self, index: usize) -> Option<(Chunks<M>, usize, M::Measure)> {
1365        // Bounds check
1366        if index <= self.len() {
1367            Some(Chunks::new_with_range_at_index(
1368                &self.root,
1369                index,
1370                (0, self.len()),
1371                (M::Measure::default(), self.measure()),
1372            ))
1373        } else {
1374            None
1375        }
1376    }
1377
1378    /// Non-panicking version of
1379    /// [`chunks_at_measure()`][Rope::chunks_at_measure].
1380    #[inline]
1381    pub fn get_chunks_at_measure(
1382        &self,
1383        measure: M::Measure,
1384        cmp: impl Fn(&M::Measure, &M::Measure) -> Ordering,
1385    ) -> Option<(Chunks<M>, usize, M::Measure)> {
1386        // Bounds check
1387        if cmp(&measure, &self.measure()).is_le() {
1388            Some(Chunks::new_with_range_at_measure(
1389                &self.root,
1390                measure,
1391                (0, self.len()),
1392                (M::Measure::default(), self.measure()),
1393                cmp,
1394            ))
1395        } else {
1396            None
1397        }
1398    }
1399}
1400
1401//==============================================================
1402// Conversion impls
1403
1404impl<'a, M> From<&'a [M]> for Rope<M>
1405where
1406    M: Measurable,
1407    [(); max_len::<M, M::Measure>()]: Sized,
1408    [(); max_children::<M, M::Measure>()]: Sized,
1409{
1410    #[inline]
1411    fn from(slice: &'a [M]) -> Self {
1412        Rope::from_slice(slice)
1413    }
1414}
1415
1416impl<'a, M> From<std::borrow::Cow<'a, [M]>> for Rope<M>
1417where
1418    M: Measurable,
1419    [(); max_len::<M, M::Measure>()]: Sized,
1420    [(); max_children::<M, M::Measure>()]: Sized,
1421{
1422    #[inline]
1423    fn from(slice: std::borrow::Cow<'a, [M]>) -> Self {
1424        Rope::from_slice(&slice)
1425    }
1426}
1427
1428impl<M> From<Vec<M>> for Rope<M>
1429where
1430    M: Measurable,
1431    [(); max_len::<M, M::Measure>()]: Sized,
1432    [(); max_children::<M, M::Measure>()]: Sized,
1433{
1434    #[inline]
1435    fn from(slice: Vec<M>) -> Self {
1436        Rope::from_slice(&slice)
1437    }
1438}
1439
1440/// Will share data where possible.
1441///
1442/// Runs in O(log N) time.
1443impl<'a, M> From<RopeSlice<'a, M>> for Rope<M>
1444where
1445    M: Measurable,
1446    [(); max_len::<M, M::Measure>()]: Sized,
1447    [(); max_children::<M, M::Measure>()]: Sized,
1448{
1449    fn from(s: RopeSlice<'a, M>) -> Self {
1450        use crate::slice::RSEnum;
1451        match s {
1452            RopeSlice(RSEnum::Full {
1453                node,
1454                start_info,
1455                end_info,
1456            }) => {
1457                let mut rope = Rope {
1458                    root: Arc::clone(node),
1459                };
1460
1461                // Chop off right end if needed
1462                if end_info.measure.fallible_cmp(&node.info().measure).is_lt() {
1463                    {
1464                        let root = Arc::make_mut(&mut rope.root);
1465                        root.end_split(end_info.measure, &M::Measure::fallible_cmp);
1466                        root.zip_fix_right();
1467                    }
1468                    rope.pull_up_singular_nodes();
1469                }
1470
1471                // Chop off left end if needed
1472                if start_info
1473                    .measure
1474                    .fallible_cmp(&M::Measure::default())
1475                    .is_gt()
1476                {
1477                    {
1478                        let root = Arc::make_mut(&mut rope.root);
1479                        *root = root.start_split(start_info.measure, &M::Measure::fallible_cmp);
1480                        root.zip_fix_left();
1481                    }
1482                    rope.pull_up_singular_nodes();
1483                }
1484
1485                // Return the rope
1486                rope
1487            }
1488            RopeSlice(RSEnum::Light { slice, .. }) => Rope::from_slice(slice),
1489        }
1490    }
1491}
1492
1493impl<M> From<Rope<M>> for Vec<M>
1494where
1495    M: Measurable,
1496    [(); max_len::<M, M::Measure>()]: Sized,
1497    [(); max_children::<M, M::Measure>()]: Sized,
1498{
1499    #[inline]
1500    fn from(r: Rope<M>) -> Self {
1501        Vec::from(&r)
1502    }
1503}
1504
1505impl<'a, M> From<&'a Rope<M>> for Vec<M>
1506where
1507    M: Measurable,
1508    [(); max_len::<M, M::Measure>()]: Sized,
1509    [(); max_children::<M, M::Measure>()]: Sized,
1510{
1511    #[inline]
1512    fn from(r: &'a Rope<M>) -> Self {
1513        let mut vec = Vec::with_capacity(r.len());
1514        vec.extend(r.chunks().flat_map(|chunk| chunk.iter()).cloned());
1515        vec
1516    }
1517}
1518
1519impl<'a, M> From<Rope<M>> for std::borrow::Cow<'a, [M]>
1520where
1521    M: Measurable,
1522    [(); max_len::<M, M::Measure>()]: Sized,
1523    [(); max_children::<M, M::Measure>()]: Sized,
1524{
1525    #[inline]
1526    fn from(r: Rope<M>) -> Self {
1527        std::borrow::Cow::Owned(Vec::from(r))
1528    }
1529}
1530
1531/// Attempts to borrow the contents of the [`Rope<M>`], but will convert to an
1532/// owned [`[M]`][Measurable] if the contents is not contiguous in memory.
1533///
1534/// Runs in best case O(1), worst case O(N).
1535impl<'a, M> From<&'a Rope<M>> for std::borrow::Cow<'a, [M]>
1536where
1537    M: Measurable,
1538    [(); max_len::<M, M::Measure>()]: Sized,
1539    [(); max_children::<M, M::Measure>()]: Sized,
1540{
1541    #[inline]
1542    fn from(r: &'a Rope<M>) -> Self {
1543        if let Node::Leaf(ref slice) = *r.root {
1544            std::borrow::Cow::Borrowed(slice)
1545        } else {
1546            std::borrow::Cow::Owned(Vec::from(r))
1547        }
1548    }
1549}
1550
1551impl<'a, M> FromIterator<&'a [M]> for Rope<M>
1552where
1553    M: Measurable,
1554    [(); max_len::<M, M::Measure>()]: Sized,
1555    [(); max_children::<M, M::Measure>()]: Sized,
1556{
1557    fn from_iter<T>(iter: T) -> Self
1558    where
1559        T: IntoIterator<Item = &'a [M]>,
1560    {
1561        let mut builder = RopeBuilder::new();
1562        for chunk in iter {
1563            builder.append_slice(chunk);
1564        }
1565        builder.finish()
1566    }
1567}
1568
1569impl<'a, M> FromIterator<std::borrow::Cow<'a, [M]>> for Rope<M>
1570where
1571    M: Measurable,
1572    [(); max_len::<M, M::Measure>()]: Sized,
1573    [(); max_children::<M, M::Measure>()]: Sized,
1574{
1575    fn from_iter<T>(iter: T) -> Self
1576    where
1577        T: IntoIterator<Item = std::borrow::Cow<'a, [M]>>,
1578    {
1579        let mut builder = RopeBuilder::new();
1580        for chunk in iter {
1581            builder.append_slice(&chunk);
1582        }
1583        builder.finish()
1584    }
1585}
1586
1587impl<M> FromIterator<Vec<M>> for Rope<M>
1588where
1589    M: Measurable,
1590    [(); max_len::<M, M::Measure>()]: Sized,
1591    [(); max_children::<M, M::Measure>()]: Sized,
1592{
1593    fn from_iter<T>(iter: T) -> Self
1594    where
1595        T: IntoIterator<Item = Vec<M>>,
1596    {
1597        let mut builder = RopeBuilder::new();
1598        for chunk in iter {
1599            builder.append_slice(&chunk);
1600        }
1601        builder.finish()
1602    }
1603}
1604
1605//==============================================================
1606// Other impls
1607
1608impl<M> std::fmt::Debug for Rope<M>
1609where
1610    M: Measurable + std::fmt::Debug,
1611    [(); max_len::<M, M::Measure>()]: Sized,
1612    [(); max_children::<M, M::Measure>()]: Sized,
1613{
1614    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1615        f.debug_list().entries(self.chunks()).finish()
1616    }
1617}
1618
1619impl<M> std::fmt::Display for Rope<M>
1620where
1621    M: Measurable + std::fmt::Display,
1622    [(); max_len::<M, M::Measure>()]: Sized,
1623    [(); max_children::<M, M::Measure>()]: Sized,
1624{
1625    #[inline]
1626    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1627        f.write_str("[")?;
1628
1629        let mut iter = self.iter();
1630        iter.next()
1631            .map(|(_, measurable)| f.write_fmt(format_args!("{}", measurable)))
1632            .transpose()?;
1633
1634        for (_, measurable) in iter {
1635            f.write_fmt(format_args!(", {}", measurable))?;
1636        }
1637        f.write_str("]")
1638    }
1639}
1640
1641impl<M> std::default::Default for Rope<M>
1642where
1643    M: Measurable,
1644    [(); max_len::<M, M::Measure>()]: Sized,
1645    [(); max_children::<M, M::Measure>()]: Sized,
1646{
1647    #[inline]
1648    fn default() -> Self {
1649        Self::new()
1650    }
1651}
1652
1653impl<M> std::cmp::Eq for Rope<M>
1654where
1655    M: Measurable + Eq,
1656    [(); max_len::<M, M::Measure>()]: Sized,
1657    [(); max_children::<M, M::Measure>()]: Sized,
1658{
1659}
1660
1661impl<M> std::cmp::PartialEq<Rope<M>> for Rope<M>
1662where
1663    M: Measurable + PartialEq,
1664    [(); max_len::<M, M::Measure>()]: Sized,
1665    [(); max_children::<M, M::Measure>()]: Sized,
1666{
1667    #[inline]
1668    fn eq(&self, other: &Rope<M>) -> bool {
1669        self.measure_slice(.., M::Measure::fallible_cmp)
1670            == other.measure_slice(.., M::Measure::fallible_cmp)
1671    }
1672}
1673
1674impl<'a, M> std::cmp::PartialEq<&'a [M]> for Rope<M>
1675where
1676    M: Measurable + PartialEq,
1677    [(); max_len::<M, M::Measure>()]: Sized,
1678    [(); max_children::<M, M::Measure>()]: Sized,
1679{
1680    #[inline]
1681    fn eq(&self, other: &&'a [M]) -> bool {
1682        self.measure_slice(.., M::Measure::fallible_cmp) == *other
1683    }
1684}
1685
1686impl<'a, M> std::cmp::PartialEq<Rope<M>> for &'a [M]
1687where
1688    M: Measurable + PartialEq,
1689    [(); max_len::<M, M::Measure>()]: Sized,
1690    [(); max_children::<M, M::Measure>()]: Sized,
1691{
1692    #[inline]
1693    fn eq(&self, other: &Rope<M>) -> bool {
1694        *self == other.measure_slice(.., M::Measure::fallible_cmp)
1695    }
1696}
1697
1698impl<M> std::cmp::PartialEq<[M]> for Rope<M>
1699where
1700    M: Measurable + PartialEq,
1701    [(); max_len::<M, M::Measure>()]: Sized,
1702    [(); max_children::<M, M::Measure>()]: Sized,
1703{
1704    #[inline]
1705    fn eq(&self, other: &[M]) -> bool {
1706        self.measure_slice(.., M::Measure::fallible_cmp) == other
1707    }
1708}
1709
1710impl<M> std::cmp::PartialEq<Rope<M>> for [M]
1711where
1712    M: Measurable + PartialEq,
1713    [(); max_len::<M, M::Measure>()]: Sized,
1714    [(); max_children::<M, M::Measure>()]: Sized,
1715{
1716    #[inline]
1717    fn eq(&self, other: &Rope<M>) -> bool {
1718        self == other.measure_slice(.., M::Measure::fallible_cmp)
1719    }
1720}
1721
1722impl<M> std::cmp::PartialEq<Vec<M>> for Rope<M>
1723where
1724    M: Measurable + PartialEq,
1725    [(); max_len::<M, M::Measure>()]: Sized,
1726    [(); max_children::<M, M::Measure>()]: Sized,
1727{
1728    #[inline]
1729    fn eq(&self, other: &Vec<M>) -> bool {
1730        self.measure_slice(.., M::Measure::fallible_cmp) == other.as_slice()
1731    }
1732}
1733
1734impl<M> std::cmp::PartialEq<Rope<M>> for Vec<M>
1735where
1736    M: Measurable + PartialEq,
1737    [(); max_len::<M, M::Measure>()]: Sized,
1738    [(); max_children::<M, M::Measure>()]: Sized,
1739{
1740    #[inline]
1741    fn eq(&self, other: &Rope<M>) -> bool {
1742        self.as_slice() == other.measure_slice(.., M::Measure::fallible_cmp)
1743    }
1744}
1745
1746impl<'a, M> std::cmp::PartialEq<std::borrow::Cow<'a, [M]>> for Rope<M>
1747where
1748    M: Measurable + PartialEq,
1749    [(); max_len::<M, M::Measure>()]: Sized,
1750    [(); max_children::<M, M::Measure>()]: Sized,
1751{
1752    #[inline]
1753    fn eq(&self, other: &std::borrow::Cow<'a, [M]>) -> bool {
1754        self.measure_slice(.., M::Measure::fallible_cmp) == **other
1755    }
1756}
1757
1758impl<'a, M> std::cmp::PartialEq<Rope<M>> for std::borrow::Cow<'a, [M]>
1759where
1760    M: Measurable + PartialEq,
1761    [(); max_len::<M, M::Measure>()]: Sized,
1762    [(); max_children::<M, M::Measure>()]: Sized,
1763{
1764    #[inline]
1765    fn eq(&self, other: &Rope<M>) -> bool {
1766        **self == other.measure_slice(.., M::Measure::fallible_cmp)
1767    }
1768}
1769
1770impl<M> std::cmp::Ord for Rope<M>
1771where
1772    M: Measurable + Ord,
1773    [(); max_len::<M, M::Measure>()]: Sized,
1774    [(); max_children::<M, M::Measure>()]: Sized,
1775{
1776    #[inline]
1777    fn cmp(&self, other: &Rope<M>) -> std::cmp::Ordering {
1778        self.measure_slice(.., M::Measure::fallible_cmp)
1779            .cmp(&other.measure_slice(.., M::Measure::fallible_cmp))
1780    }
1781}
1782
1783impl<M> std::cmp::PartialOrd<Rope<M>> for Rope<M>
1784where
1785    M: Measurable + PartialOrd + Ord,
1786    [(); max_len::<M, M::Measure>()]: Sized,
1787    [(); max_children::<M, M::Measure>()]: Sized,
1788{
1789    #[inline]
1790    fn partial_cmp(&self, other: &Rope<M>) -> Option<std::cmp::Ordering> {
1791        Some(self.cmp(other))
1792    }
1793}
1794
1795//==============================================================
1796
1797#[cfg(test)]
1798mod tests {
1799    use super::*;
1800    use crate::Width;
1801
1802    /// 70 elements, total measure of 135.
1803    fn pseudo_random() -> Vec<Width> {
1804        (0..70)
1805            .map(|num| match num % 14 {
1806                0 | 7 => Width(1),
1807                1 | 8 => Width(2),
1808                2 => Width(4),
1809                3 | 10 => Width(0),
1810                4 | 11 => Width(0),
1811                5 => Width(5),
1812                6 => Width(1),
1813                9 => Width(8),
1814                12 => Width(3),
1815                13 => Width(0),
1816                _ => unreachable!(),
1817            })
1818            .collect()
1819    }
1820
1821    /// 5 elements, total measure of 6.
1822    const SHORT_LOREM: &[Width] = &[Width(1), Width(2), Width(3), Width(0), Width(0)];
1823
1824    #[test]
1825    fn new_01() {
1826        let rope: Rope<Width> = Rope::new();
1827        assert_eq!(rope, [].as_slice());
1828
1829        rope.assert_integrity();
1830        rope.assert_invariants();
1831    }
1832
1833    #[test]
1834    fn from_slice() {
1835        let rope = Rope::from(pseudo_random());
1836        assert_eq!(rope, pseudo_random());
1837
1838        rope.assert_integrity();
1839        rope.assert_invariants();
1840    }
1841
1842    #[test]
1843    fn len_01() {
1844        let rope = Rope::from(pseudo_random());
1845        assert_eq!(rope.len(), 70);
1846    }
1847
1848    #[test]
1849    fn measure_02() {
1850        let rope: Rope<Width> = Rope::from_slice(&[]);
1851        assert_eq!(rope.len(), 0);
1852    }
1853
1854    #[test]
1855    fn len_from_measures_01() {
1856        let rope = Rope::from(pseudo_random());
1857        assert_eq!(rope.measure(), 135);
1858    }
1859
1860    #[test]
1861    fn len_from_measures_02() {
1862        let rope: Rope<Width> = Rope::from_slice(&[]);
1863        assert_eq!(rope.measure(), 0);
1864    }
1865
1866    #[test]
1867    fn insert_01() {
1868        let mut rope = Rope::from_slice(SHORT_LOREM);
1869        rope.insert_slice(3, &[Width(1), Width(2), Width(3)], usize::cmp);
1870
1871        assert_eq!(
1872            rope,
1873            [
1874                Width(1),
1875                Width(2),
1876                Width(1),
1877                Width(2),
1878                Width(3),
1879                Width(3),
1880                Width(0),
1881                Width(0)
1882            ]
1883            .as_slice()
1884        );
1885
1886        rope.assert_integrity();
1887        rope.assert_invariants();
1888    }
1889
1890    #[test]
1891    fn insert_02() {
1892        let mut rope = Rope::from_slice(SHORT_LOREM);
1893        rope.insert_slice(0, &[Width(1), Width(2), Width(3)], usize::cmp);
1894
1895        assert_eq!(
1896            rope,
1897            [
1898                Width(1),
1899                Width(2),
1900                Width(3),
1901                Width(1),
1902                Width(2),
1903                Width(3),
1904                Width(0),
1905                Width(0)
1906            ]
1907            .as_slice()
1908        );
1909
1910        rope.assert_integrity();
1911        rope.assert_invariants();
1912    }
1913
1914    #[test]
1915    fn insert_03() {
1916        let mut rope = Rope::from_slice(SHORT_LOREM);
1917        rope.insert_slice(6, &[Width(1), Width(2), Width(3)], usize::cmp);
1918
1919        assert_eq!(
1920            rope,
1921            [
1922                Width(1),
1923                Width(2),
1924                Width(3),
1925                Width(0),
1926                Width(0),
1927                Width(1),
1928                Width(2),
1929                Width(3)
1930            ]
1931            .as_slice()
1932        );
1933
1934        rope.assert_integrity();
1935        rope.assert_invariants();
1936    }
1937
1938    #[test]
1939    fn insert_04() {
1940        let mut rope = Rope::new();
1941        rope.insert_slice(0, &[Width(1), Width(2)], usize::cmp);
1942        rope.insert_slice(2, &[Width(5)], usize::cmp);
1943        rope.insert_slice(3, &[Width(0)], usize::cmp);
1944        rope.insert_slice(4, &[Width(4)], usize::cmp);
1945        rope.insert_slice(11, &[Width(3)], usize::cmp);
1946
1947        // NOTE: Inserting in the middle of an item'slice measure range, makes it so
1948        // you actually place it at the end of said item.
1949        assert_eq!(
1950            rope,
1951            [Width(1), Width(2), Width(0), Width(5), Width(4), Width(3)].as_slice()
1952        );
1953
1954        rope.assert_integrity();
1955        rope.assert_invariants();
1956    }
1957
1958    #[test]
1959    fn insert_05() {
1960        let mut rope = Rope::new();
1961        rope.insert_slice(0, &[Width(15), Width(20)], usize::cmp);
1962        rope.insert_slice(7, &[Width(0), Width(0)], usize::cmp);
1963        assert_eq!(rope, [Width(15), Width(0), Width(0), Width(20)].as_slice());
1964
1965        rope.assert_integrity();
1966        rope.assert_invariants();
1967    }
1968
1969    #[test]
1970    fn insert_06() {
1971        let mut rope = Rope::new();
1972        rope.insert(0, Width(15), usize::cmp);
1973        rope.insert(1, Width(20), usize::cmp);
1974        rope.insert(2, Width(10), usize::cmp);
1975        rope.insert(3, Width(4), usize::cmp);
1976        rope.insert_slice(20, &[Width(0), Width(0)], usize::cmp);
1977        assert_eq!(
1978            rope,
1979            [
1980                Width(15),
1981                Width(4),
1982                Width(10),
1983                Width(0),
1984                Width(0),
1985                Width(20)
1986            ]
1987            .as_slice()
1988        );
1989
1990        rope.assert_integrity();
1991        rope.assert_invariants();
1992    }
1993
1994    #[test]
1995    fn remove_01() {
1996        let slice = &[
1997            Width(15),
1998            Width(0),
1999            Width(0),
2000            Width(24),
2001            Width(1),
2002            Width(2),
2003            Width(7),
2004        ];
2005        let mut rope = Rope::from_slice(slice);
2006
2007        rope.remove_inclusive(0..11, usize::cmp);
2008        rope.remove_inclusive(24..31, usize::cmp);
2009        rope.remove_inclusive(0..0, usize::cmp);
2010        assert_eq!(rope, [Width(24)].as_slice());
2011
2012        rope.assert_integrity();
2013        rope.assert_invariants();
2014    }
2015
2016    #[test]
2017    fn remove_02() {
2018        let slice = &[Width(1); 15];
2019        let mut rope = Rope::from_slice(slice);
2020
2021        // assert_invariants() below.
2022        rope.remove_inclusive(3..6, usize::cmp);
2023        assert_eq!(rope, [Width(1); 12].as_slice());
2024
2025        rope.assert_integrity();
2026        rope.assert_invariants();
2027    }
2028
2029    #[test]
2030    fn remove_03() {
2031        let mut rope = Rope::from(pseudo_random());
2032
2033        // Make sure removing an empty range, on a non 0 measure element, does nothing.
2034        rope.remove_inclusive(45..45, usize::cmp);
2035        assert_eq!(rope, pseudo_random());
2036
2037        rope.assert_integrity();
2038        rope.assert_invariants();
2039    }
2040
2041    #[test]
2042    fn remove_04() {
2043        let mut rope = Rope::from(pseudo_random());
2044
2045        // Make sure removing everything works.
2046        rope.remove_inclusive(0..135, usize::cmp);
2047        assert_eq!(rope, [].as_slice());
2048
2049        rope.assert_integrity();
2050        rope.assert_invariants();
2051    }
2052
2053    #[test]
2054    fn remove_05() {
2055        let mut rope = Rope::from(pseudo_random());
2056
2057        // Make sure removing a large range works.
2058        rope.remove_inclusive(3..135, usize::cmp);
2059        assert_eq!(rope, &pseudo_random()[..2]);
2060
2061        rope.assert_integrity();
2062        rope.assert_invariants();
2063    }
2064
2065    #[test]
2066    fn remove_06() {
2067        let mut vec = Vec::from([Width(1); 2]);
2068        vec.extend_from_slice(&[Width(0); 300]);
2069        vec.extend_from_slice(&[Width(2); 3]);
2070
2071        let mut rope = Rope::from(vec);
2072        rope.remove_inclusive(2..2, usize::cmp);
2073
2074        assert_eq!(
2075            rope,
2076            [Width(1), Width(1), Width(2), Width(2), Width(2)].as_slice()
2077        );
2078    }
2079
2080    #[test]
2081    #[should_panic]
2082    fn remove_07() {
2083        let mut rope = Rope::from(pseudo_random());
2084        #[allow(clippy::reversed_empty_ranges)]
2085        rope.remove_inclusive(56..55, usize::cmp); // Wrong ordering of start/end on purpose.
2086    }
2087
2088    #[test]
2089    #[should_panic]
2090    fn remove_08() {
2091        let mut rope = Rope::from(pseudo_random());
2092        rope.remove_inclusive(134..136, usize::cmp); // Removing past the end
2093    }
2094
2095    #[test]
2096    fn split_off_01() {
2097        let mut rope = Rope::from(pseudo_random());
2098
2099        let split = rope.split_off(50, usize::cmp);
2100        assert_eq!(rope, &pseudo_random()[..24]);
2101        assert_eq!(split, &pseudo_random()[24..]);
2102
2103        rope.assert_integrity();
2104        split.assert_integrity();
2105        rope.assert_invariants();
2106        split.assert_invariants();
2107    }
2108
2109    #[test]
2110    fn split_off_02() {
2111        let mut rope = Rope::from(pseudo_random());
2112
2113        let split = rope.split_off(1, usize::cmp);
2114        assert_eq!(rope, [Width(1)].as_slice());
2115        assert_eq!(split, &pseudo_random()[1..]);
2116
2117        rope.assert_integrity();
2118        split.assert_integrity();
2119        rope.assert_invariants();
2120        split.assert_invariants();
2121    }
2122
2123    #[test]
2124    fn split_off_03() {
2125        let mut rope = Rope::from(pseudo_random());
2126
2127        let split = rope.split_off(134, usize::cmp);
2128        assert_eq!(rope, &pseudo_random()[..69]);
2129        assert_eq!(split, [Width(0)].as_slice());
2130
2131        rope.assert_integrity();
2132        split.assert_integrity();
2133        rope.assert_invariants();
2134        split.assert_invariants();
2135    }
2136
2137    #[test]
2138    fn split_off_04() {
2139        let mut rope = Rope::from(pseudo_random());
2140
2141        let split = rope.split_off(0, usize::cmp);
2142        assert_eq!(rope, [].as_slice());
2143        assert_eq!(split, pseudo_random().as_slice());
2144
2145        rope.assert_integrity();
2146        split.assert_integrity();
2147        rope.assert_invariants();
2148        split.assert_invariants();
2149    }
2150
2151    #[test]
2152    fn split_off_05() {
2153        let mut rope = Rope::from(pseudo_random());
2154
2155        let split = rope.split_off(135, usize::cmp);
2156        assert_eq!(rope, pseudo_random().as_slice());
2157        assert_eq!(split, [].as_slice());
2158
2159        rope.assert_integrity();
2160        split.assert_integrity();
2161        rope.assert_invariants();
2162        split.assert_invariants();
2163    }
2164
2165    #[test]
2166    #[should_panic]
2167    fn split_off_06() {
2168        let mut rope = Rope::from(pseudo_random());
2169        rope.split_off(136, usize::cmp); // One past the end of the rope
2170    }
2171
2172    #[test]
2173    fn append_01() {
2174        let mut rope = Rope::from_slice(&pseudo_random()[..35]);
2175        let append = Rope::from_slice(&pseudo_random()[35..]);
2176
2177        rope.append(append);
2178        assert_eq!(rope, pseudo_random().as_slice());
2179
2180        rope.assert_integrity();
2181        rope.assert_invariants();
2182    }
2183
2184    #[test]
2185    fn append_02() {
2186        let mut rope = Rope::from_slice(&pseudo_random()[..68]);
2187        let append = Rope::from_slice(&[Width(3), Width(0)]);
2188
2189        rope.append(append);
2190        assert_eq!(rope, pseudo_random());
2191
2192        rope.assert_integrity();
2193        rope.assert_invariants();
2194    }
2195
2196    #[test]
2197    fn append_03() {
2198        let mut rope = Rope::from_slice(&[Width(1), Width(2)]);
2199        let append = Rope::from_slice(&pseudo_random()[2..]);
2200
2201        rope.append(append);
2202        assert_eq!(rope, pseudo_random());
2203
2204        rope.assert_integrity();
2205        rope.assert_invariants();
2206    }
2207
2208    #[test]
2209    fn append_04() {
2210        let mut rope = Rope::from(pseudo_random());
2211        let append = Rope::from_slice([].as_slice());
2212
2213        rope.append(append);
2214        assert_eq!(rope, pseudo_random());
2215
2216        rope.assert_integrity();
2217        rope.assert_invariants();
2218    }
2219
2220    #[test]
2221    fn append_05() {
2222        let mut rope = Rope::from_slice([].as_slice());
2223        let append = Rope::from(pseudo_random());
2224
2225        rope.append(append);
2226        assert_eq!(rope, pseudo_random());
2227
2228        rope.assert_integrity();
2229        rope.assert_invariants();
2230    }
2231
2232    #[test]
2233    fn measure_to_index_01() {
2234        let rope = Rope::from(pseudo_random());
2235
2236        assert_eq!(rope.start_measure_to_index(0, usize::cmp), 0);
2237        assert_eq!(rope.start_measure_to_index(1, usize::cmp), 1);
2238        assert_eq!(rope.start_measure_to_index(2, usize::cmp), 1);
2239
2240        assert_eq!(rope.start_measure_to_index(91, usize::cmp), 47);
2241        assert_eq!(rope.start_measure_to_index(92, usize::cmp), 47);
2242        assert_eq!(rope.start_measure_to_index(93, usize::cmp), 48);
2243        assert_eq!(rope.start_measure_to_index(94, usize::cmp), 49);
2244
2245        assert_eq!(rope.start_measure_to_index(102, usize::cmp), 51);
2246        assert_eq!(rope.start_measure_to_index(103, usize::cmp), 51);
2247    }
2248
2249    #[test]
2250    fn from_index_01() {
2251        let rope = Rope::from(pseudo_random());
2252
2253        assert_eq!(rope.from_index(0), (0, Width(1)));
2254
2255        assert_eq!(rope.from_index(67), (132, Width(0)));
2256        assert_eq!(rope.from_index(68), (132, Width(3)));
2257        assert_eq!(rope.from_index(69), (135, Width(0)));
2258    }
2259
2260    #[test]
2261    #[should_panic]
2262    fn from_index_02() {
2263        let rope = Rope::from(pseudo_random());
2264        rope.from_index(70);
2265    }
2266
2267    #[test]
2268    #[should_panic]
2269    fn from_index_03() {
2270        let rope: Rope<Width> = Rope::from_slice(&[]);
2271        rope.from_index(0);
2272    }
2273
2274    #[test]
2275    fn from_measure_01() {
2276        let rope = Rope::from(pseudo_random());
2277
2278        assert_eq!(rope.from_measure(0, usize::cmp), (0, Width(1)));
2279        assert_eq!(rope.from_measure(10, usize::cmp), (7, Width(5)));
2280        assert_eq!(rope.from_measure(18, usize::cmp), (16, Width(8)));
2281        assert_eq!(rope.from_measure(108, usize::cmp), (108, Width(0)));
2282    }
2283
2284    #[test]
2285    #[should_panic]
2286    fn from_measure_02() {
2287        let rope = Rope::from(pseudo_random());
2288        rope.from_measure(136, usize::cmp);
2289    }
2290
2291    #[test]
2292    #[should_panic]
2293    fn from_measure_03() {
2294        let rope: Rope<Width> = Rope::from_slice(&[]);
2295        rope.from_measure(0, usize::cmp);
2296    }
2297
2298    #[test]
2299    fn chunk_at_index() {
2300        let rope = Rope::from(pseudo_random());
2301        let lorem_ipsum = pseudo_random();
2302        let mut total = lorem_ipsum.as_slice();
2303
2304        let mut last_chunk = [].as_slice();
2305        for i in 0..rope.len() {
2306            let (chunk, index, measure) = rope.chunk_at_index(i);
2307            assert_eq!(measure, index_to_measure(&lorem_ipsum, index));
2308            if chunk != last_chunk {
2309                assert_eq!(chunk, &total[..chunk.len()]);
2310                total = &total[chunk.len()..];
2311                last_chunk = chunk;
2312            }
2313
2314            let measure_1 = lorem_ipsum.get(i).unwrap();
2315            let measure_2 = {
2316                let i2 = i - index;
2317                chunk.get(i2).unwrap()
2318            };
2319            assert_eq!(measure_1, measure_2);
2320        }
2321        assert_eq!(total.len(), 0);
2322    }
2323
2324    #[test]
2325    fn chunk_at_measure() {
2326        let rope = Rope::from(pseudo_random());
2327        let lorem_ipsum = pseudo_random();
2328        let mut total = lorem_ipsum.as_slice();
2329
2330        let mut last_chunk = [].as_slice();
2331        for i in 0..rope.measure() {
2332            let (chunk, _, measure) = rope.chunk_at_measure(i, usize::cmp);
2333            if chunk != last_chunk {
2334                assert_eq!(chunk, &total[..chunk.len()]);
2335                total = &total[chunk.len()..];
2336                last_chunk = chunk;
2337            }
2338
2339            let measure_1 = {
2340                let index_1 = start_measure_to_index(&lorem_ipsum, i, usize::cmp);
2341                lorem_ipsum.get(index_1).unwrap()
2342            };
2343            let measure_2 = {
2344                let index_2 = start_measure_to_index(chunk, i - measure, usize::cmp);
2345                chunk.get(index_2)
2346            };
2347            if let Some(measure_2) = measure_2 {
2348                assert_eq!(measure_1, measure_2);
2349            }
2350        }
2351        assert_eq!(total.len(), 0);
2352    }
2353
2354    #[test]
2355    fn measure_slice_01() {
2356        let rope = Rope::from(pseudo_random());
2357
2358        let slice = rope.measure_slice(0..rope.measure(), usize::cmp);
2359
2360        assert_eq!(slice, pseudo_random());
2361    }
2362
2363    #[test]
2364    fn measure_slice_02() {
2365        let rope = Rope::from(pseudo_random());
2366
2367        let slice = rope.measure_slice(5..21, usize::cmp);
2368
2369        assert_eq!(slice, &pseudo_random()[2..10]);
2370    }
2371
2372    #[test]
2373    fn measure_slice_03() {
2374        let rope = Rope::from(pseudo_random());
2375
2376        let slice = rope.measure_slice(31..135, usize::cmp);
2377
2378        assert_eq!(slice, &pseudo_random()[16..70]);
2379    }
2380
2381    #[test]
2382    fn measure_slice_04() {
2383        let rope = Rope::from(pseudo_random());
2384
2385        let slice = rope.measure_slice(53..53, usize::cmp);
2386
2387        assert_eq!([].as_slice(), slice);
2388    }
2389
2390    #[test]
2391    #[should_panic]
2392    fn measure_slice_05() {
2393        let rope = Rope::from(pseudo_random());
2394        #[allow(clippy::reversed_empty_ranges)]
2395        rope.measure_slice(53..52, usize::cmp); // Wrong ordering on purpose.
2396    }
2397
2398    #[test]
2399    #[should_panic]
2400    fn measure_slice_06() {
2401        let rope = Rope::from(pseudo_random());
2402        rope.measure_slice(134..136, usize::cmp);
2403    }
2404
2405    #[test]
2406    fn index_slice_01() {
2407        let rope = Rope::from(pseudo_random());
2408
2409        let slice = rope.index_slice(0..rope.len());
2410
2411        assert_eq!(pseudo_random(), slice);
2412    }
2413
2414    #[test]
2415    fn index_slice_02() {
2416        let rope = Rope::from(pseudo_random());
2417
2418        let slice = rope.index_slice(5..21);
2419
2420        assert_eq!(&pseudo_random()[5..21], slice);
2421    }
2422
2423    #[test]
2424    fn index_slice_03() {
2425        let rope = Rope::from(pseudo_random());
2426
2427        let slice = rope.index_slice(31..55);
2428
2429        assert_eq!(&pseudo_random()[31..55], slice);
2430    }
2431
2432    #[test]
2433    fn index_slice_04() {
2434        let rope = Rope::from(pseudo_random());
2435
2436        let slice = rope.index_slice(53..53);
2437
2438        assert_eq!([].as_slice(), slice);
2439    }
2440
2441    #[test]
2442    #[should_panic]
2443    fn index_slice_05() {
2444        let rope = Rope::from(pseudo_random());
2445        #[allow(clippy::reversed_empty_ranges)]
2446        rope.index_slice(53..52); // Wrong ordering on purpose.
2447    }
2448
2449    #[test]
2450    #[should_panic]
2451    fn index_slice_06() {
2452        let rope = Rope::from(pseudo_random());
2453        rope.index_slice(20..72);
2454    }
2455
2456    #[test]
2457    fn eq_rope_01() {
2458        let rope: Rope<Width> = Rope::from_slice([].as_slice());
2459
2460        assert_eq!(rope, rope);
2461    }
2462
2463    #[test]
2464    fn eq_rope_02() {
2465        let rope = Rope::from(pseudo_random());
2466
2467        assert_eq!(rope, rope);
2468    }
2469
2470    #[test]
2471    fn eq_rope_03() {
2472        let rope_1 = Rope::from(pseudo_random());
2473        let mut rope_2 = rope_1.clone();
2474        rope_2.remove_inclusive(26..27, usize::cmp);
2475        rope_2.insert(26, Width(1000), usize::cmp);
2476
2477        assert_ne!(rope_1, rope_2);
2478    }
2479
2480    #[test]
2481    fn eq_rope_04() {
2482        let rope: Rope<Width> = Rope::from_slice([].as_slice());
2483
2484        assert_eq!(rope, [].as_slice());
2485        assert_eq!([].as_slice(), rope);
2486    }
2487
2488    #[test]
2489    fn eq_rope_05() {
2490        let rope = Rope::from(pseudo_random());
2491
2492        assert_eq!(rope, pseudo_random());
2493        assert_eq!(pseudo_random(), rope);
2494    }
2495
2496    #[test]
2497    fn eq_rope_06() {
2498        let mut rope = Rope::from(pseudo_random());
2499        rope.remove_inclusive(26..27, usize::cmp);
2500        rope.insert(26, Width(5000), usize::cmp);
2501
2502        assert_ne!(rope, pseudo_random());
2503        assert_ne!(pseudo_random(), rope);
2504    }
2505
2506    #[test]
2507    fn eq_rope_07() {
2508        let rope = Rope::from(pseudo_random());
2509        let slice: Vec<Width> = pseudo_random();
2510
2511        assert_eq!(rope, slice);
2512        assert_eq!(slice, rope);
2513    }
2514
2515    #[test]
2516    fn to_vec_01() {
2517        let rope = Rope::from(pseudo_random());
2518        let slice: Vec<Width> = (&rope).into();
2519
2520        assert_eq!(rope, slice);
2521    }
2522
2523    #[test]
2524    fn to_cow_01() {
2525        use std::borrow::Cow;
2526        let rope = Rope::from(pseudo_random());
2527        let cow: Cow<[Width]> = (&rope).into();
2528
2529        assert_eq!(rope, cow);
2530    }
2531
2532    #[test]
2533    fn to_cow_02() {
2534        use std::borrow::Cow;
2535        let rope = Rope::from(pseudo_random());
2536        let cow: Cow<[Width]> = (rope.clone()).into();
2537
2538        assert_eq!(rope, cow);
2539    }
2540
2541    #[test]
2542    fn to_cow_03() {
2543        use std::borrow::Cow;
2544        let rope = Rope::from_slice(&[Width(1)]);
2545        let cow: Cow<[Width]> = (&rope).into();
2546
2547        // Make sure it'slice borrowed.
2548        if let Cow::Owned(_) = cow {
2549            panic!("Small Cow conversions should result in a borrow.");
2550        }
2551
2552        assert_eq!(rope, cow);
2553    }
2554
2555    #[test]
2556    fn from_rope_slice_01() {
2557        let rope_1 = Rope::from(pseudo_random());
2558        let slice = rope_1.measure_slice(.., usize::cmp);
2559        let rope_2: Rope<Width> = slice.into();
2560
2561        assert_eq!(rope_1, rope_2);
2562        assert_eq!(slice, rope_2);
2563    }
2564
2565    #[test]
2566    fn from_rope_slice_02() {
2567        let rope_1 = Rope::from(pseudo_random());
2568        let slice = rope_1.measure_slice(0..24, usize::cmp);
2569        let rope_2: Rope<Width> = slice.into();
2570
2571        assert_eq!(slice, rope_2);
2572    }
2573
2574    #[test]
2575    fn from_rope_slice_03() {
2576        let rope_1 = Rope::from(pseudo_random());
2577        let slice = rope_1.measure_slice(13..89, usize::cmp);
2578        let rope_2: Rope<Width> = slice.into();
2579
2580        assert_eq!(slice, rope_2);
2581    }
2582
2583    #[test]
2584    fn from_rope_slice_04() {
2585        let rope_1 = Rope::from(pseudo_random());
2586        let slice = rope_1.measure_slice(13..41, usize::cmp);
2587        let rope_2: Rope<Width> = slice.into();
2588
2589        assert_eq!(slice, rope_2);
2590    }
2591
2592    #[test]
2593    fn from_iter_01() {
2594        let rope_1 = Rope::from(pseudo_random());
2595        let rope_2 = Rope::from_iter(rope_1.chunks());
2596
2597        assert_eq!(rope_1, rope_2);
2598    }
2599
2600    #[test]
2601    fn is_instance_01() {
2602        let rope = Rope::from_slice(&[Width(1), Width(2), Width(10), Width(0), Width(0)]);
2603        let mut c1 = rope.clone();
2604        let c2 = c1.clone();
2605
2606        assert!(rope.is_instance(&c1));
2607        assert!(rope.is_instance(&c2));
2608        assert!(c1.is_instance(&c2));
2609
2610        c1.insert_slice(0, &[Width(8)], usize::cmp);
2611
2612        assert!(!rope.is_instance(&c1));
2613        assert!(rope.is_instance(&c2));
2614        assert!(!c1.is_instance(&c2));
2615    }
2616}