Skip to main content

imbl/vector/
mod.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
5//! A persistent vector.
6//!
7//! This is a sequence of elements in insertion order - if you need a
8//! list of things, any kind of list of things, this is what you're
9//! looking for.
10//!
11//! It's implemented as an [RRB vector][rrbpaper] with [smart
12//! head/tail chunking][chunkedseq]. In performance terms, this means
13//! that practically every operation is O(log n), except push/pop on
14//! both sides, which will be O(1) amortised, and O(log n) in the
15//! worst case. In practice, the push/pop operations will be
16//! blindingly fast, nearly on par with the native
17//! [`VecDeque`][VecDeque], and other operations will have decent, if
18//! not high, performance, but they all have more or less the same
19//! O(log n) complexity, so you don't need to keep their performance
20//! characteristics in mind - everything, even splitting and merging,
21//! is safe to use and never too slow.
22//!
23//! ## Performance Notes
24//!
25//! Because of the head/tail chunking technique, until you push a
26//! number of items above double the tree's branching factor (that's
27//! `self.len()` = 2 × *k* (where *k* = 64) = 128) on either side, the
28//! data structure is still just a handful of arrays, not yet an RRB
29//! tree, so you'll see performance and memory characteristics fairly
30//! close to [`Vec`][Vec] or [`VecDeque`][VecDeque].
31//!
32//! This means that the structure always preallocates four chunks of
33//! size *k* (*k* being the tree's branching factor), equivalent to a
34//! [`Vec`][Vec] with an initial capacity of 256. Beyond that, it will
35//! allocate tree nodes of capacity *k* as needed.
36//!
37//! In addition, vectors start out as single chunks, and only expand into the
38//! full data structure once you go past the chunk size. This makes them
39//! perform identically to [`Vec`][Vec] at small sizes.
40//!
41//! [rrbpaper]: https://infoscience.epfl.ch/record/213452/files/rrbvector.pdf
42//! [chunkedseq]: http://deepsea.inria.fr/pasl/chunkedseq.pdf
43//! [Vec]: https://doc.rust-lang.org/std/vec/struct.Vec.html
44//! [VecDeque]: https://doc.rust-lang.org/std/collections/struct.VecDeque.html
45
46#![allow(unsafe_code)]
47
48use std::borrow::Borrow;
49use std::cmp::Ordering;
50use std::fmt::{Debug, Error, Formatter};
51use std::hash::{Hash, Hasher};
52use std::iter::Sum;
53use std::iter::{FromIterator, FusedIterator};
54use std::mem::{replace, swap};
55use std::ops::{Add, Index, IndexMut, RangeBounds};
56
57use archery::{SharedPointer, SharedPointerKind};
58use imbl_sized_chunks::InlineArray;
59
60use crate::nodes::chunk::{Chunk, CHUNK_SIZE};
61use crate::nodes::rrb::{Node, PopResult, PushResult, SplitResult};
62use crate::shared_ptr::DefaultSharedPtr;
63use crate::sort;
64use crate::util::{clone_ref, to_range, Side};
65
66use self::VectorInner::{Full, Inline, Single};
67
68mod focus;
69
70pub use self::focus::{Focus, FocusMut};
71
72#[cfg(any(test, feature = "rayon"))]
73pub mod rayon;
74
75/// Construct a vector from a sequence of elements.
76///
77/// # Examples
78///
79/// ```
80/// # #[macro_use] extern crate imbl;
81/// # use imbl::Vector;
82/// # fn main() {
83/// assert_eq!(
84///   vector![1, 2, 3],
85///   Vector::from(vec![1, 2, 3])
86/// );
87/// # }
88/// ```
89#[macro_export]
90macro_rules! vector {
91    () => { $crate::vector::Vector::new() };
92
93    ( $($x:expr),* ) => {{
94        let mut l = $crate::vector::Vector::new();
95        $(
96            l.push_back($x);
97        )*
98            l
99    }};
100
101    ( $($x:expr ,)* ) => {{
102        let mut l = $crate::vector::Vector::new();
103        $(
104            l.push_back($x);
105        )*
106            l
107    }};
108}
109
110/// Type alias for [`GenericVector`] that uses [`DefaultSharedPtr`] as the pointer type.
111///
112/// [GenericVector]: ./struct.GenericVector.html
113/// [DefaultSharedPtr]: ../shared_ptr/type.DefaultSharedPtr.html
114pub type Vector<A> = GenericVector<A, DefaultSharedPtr>;
115
116/// A persistent vector.
117///
118/// This is a sequence of elements in insertion order - if you need a list of
119/// things, any kind of list of things, this is what you're looking for.
120///
121/// It's implemented as an [RRB vector][rrbpaper] with [smart head/tail
122/// chunking][chunkedseq]. In performance terms, this means that practically
123/// every operation is O(log n), except push/pop on both sides, which will be
124/// O(1) amortised, and O(log n) in the worst case. In practice, the push/pop
125/// operations will be blindingly fast, nearly on par with the native
126/// [`VecDeque`][VecDeque], and other operations will have decent, if not high,
127/// performance, but they all have more or less the same O(log n) complexity, so
128/// you don't need to keep their performance characteristics in mind -
129/// everything, even splitting and merging, is safe to use and never too slow.
130///
131/// ## Performance Notes
132///
133/// Because of the head/tail chunking technique, until you push a number of
134/// items above double the tree's branching factor (that's `self.len()` = 2 ×
135/// *k* (where *k* = 64) = 128) on either side, the data structure is still just
136/// a handful of arrays, not yet an RRB tree, so you'll see performance and
137/// memory characteristics similar to [`Vec`][Vec] or [`VecDeque`][VecDeque].
138///
139/// This means that the structure always preallocates four chunks of size *k*
140/// (*k* being the tree's branching factor), equivalent to a [`Vec`][Vec] with
141/// an initial capacity of 256. Beyond that, it will allocate tree nodes of
142/// capacity *k* as needed.
143///
144/// In addition, vectors start out as single chunks, and only expand into the
145/// full data structure once you go past the chunk size. This makes them
146/// perform identically to [`Vec`][Vec] at small sizes.
147///
148/// [rrbpaper]: https://infoscience.epfl.ch/record/213452/files/rrbvector.pdf
149/// [chunkedseq]: http://deepsea.inria.fr/pasl/chunkedseq.pdf
150/// [Vec]: https://doc.rust-lang.org/std/vec/struct.Vec.html
151/// [VecDeque]: https://doc.rust-lang.org/std/collections/struct.VecDeque.html
152pub struct GenericVector<A, P: SharedPointerKind> {
153    vector: VectorInner<A, P>,
154}
155
156enum VectorInner<A, P: SharedPointerKind> {
157    Inline(InlineArray<A, RRB<A, P>>),
158    Single(SharedPointer<Chunk<A>, P>),
159    Full(RRB<A, P>),
160}
161
162#[doc(hidden)]
163pub struct RRB<A, P: SharedPointerKind> {
164    length: usize,
165    middle_level: usize,
166    outer_f: SharedPointer<Chunk<A>, P>,
167    inner_f: SharedPointer<Chunk<A>, P>,
168    middle: SharedPointer<Node<A, P>, P>,
169    inner_b: SharedPointer<Chunk<A>, P>,
170    outer_b: SharedPointer<Chunk<A>, P>,
171}
172
173impl<A, P: SharedPointerKind> Clone for RRB<A, P> {
174    fn clone(&self) -> Self {
175        RRB {
176            length: self.length,
177            middle_level: self.middle_level,
178            outer_f: self.outer_f.clone(),
179            inner_f: self.inner_f.clone(),
180            middle: self.middle.clone(),
181            inner_b: self.inner_b.clone(),
182            outer_b: self.outer_b.clone(),
183        }
184    }
185}
186
187impl<A, P: SharedPointerKind> GenericVector<A, P> {
188    /// True if a vector is a full inline or single chunk, ie. must be promoted
189    /// to grow further.
190    fn needs_promotion(&self) -> bool {
191        match &self.vector {
192            // Prevent the inline array from getting bigger than a single chunk. This means that we
193            // can always promote `Inline` to `Single`, even when we're configured to have a small
194            // chunk size. (TODO: it might be better to just never use `Single` in this situation,
195            // but that's a more invasive change.)
196            Inline(chunk) => chunk.is_full() || chunk.len() + 1 >= CHUNK_SIZE,
197            Single(chunk) => chunk.is_full(),
198            _ => false,
199        }
200    }
201
202    /// Promote an inline to a single.
203    fn promote_inline(&mut self) {
204        if let Inline(chunk) = &mut self.vector {
205            self.vector = Single(SharedPointer::new(chunk.into()));
206        }
207    }
208
209    /// Promote a single to a full, with the single chunk becoming inner_f, or
210    /// promote an inline to a single.
211    fn promote_front(&mut self) {
212        self.vector = match &mut self.vector {
213            Inline(chunk) => Single(SharedPointer::new(chunk.into())),
214            Single(chunk) => {
215                let chunk = chunk.clone();
216                Full(RRB {
217                    length: chunk.len(),
218                    middle_level: 0,
219                    outer_f: SharedPointer::default(),
220                    inner_f: chunk,
221                    middle: SharedPointer::new(Node::new()),
222                    inner_b: SharedPointer::default(),
223                    outer_b: SharedPointer::default(),
224                })
225            }
226            Full(_) => return,
227        }
228    }
229
230    /// Promote a single to a full, with the single chunk becoming inner_b, or
231    /// promote an inline to a single.
232    fn promote_back(&mut self) {
233        self.vector = match &mut self.vector {
234            Inline(chunk) => Single(SharedPointer::new(chunk.into())),
235            Single(chunk) => {
236                let chunk = chunk.clone();
237                Full(RRB {
238                    length: chunk.len(),
239                    middle_level: 0,
240                    outer_f: SharedPointer::default(),
241                    inner_f: SharedPointer::default(),
242                    middle: SharedPointer::new(Node::new()),
243                    inner_b: chunk,
244                    outer_b: SharedPointer::default(),
245                })
246            }
247            Full(_) => return,
248        }
249    }
250
251    /// Construct an empty vector.
252    #[must_use]
253    pub fn new() -> Self {
254        Self {
255            vector: Inline(InlineArray::new()),
256        }
257    }
258
259    /// Get the length of a vector.
260    ///
261    /// Time: O(1)
262    ///
263    /// # Examples
264    ///
265    /// ```
266    /// # #[macro_use] extern crate imbl;
267    /// # use imbl::Vector;
268    /// let vec: Vector<i64> = vector![1, 2, 3, 4, 5];
269    /// assert_eq!(5, vec.len());
270    /// ```
271    #[inline]
272    #[must_use]
273    pub fn len(&self) -> usize {
274        match &self.vector {
275            Inline(chunk) => chunk.len(),
276            Single(chunk) => chunk.len(),
277            Full(tree) => tree.length,
278        }
279    }
280
281    /// Test whether a vector is empty.
282    ///
283    /// Time: O(1)
284    ///
285    /// # Examples
286    ///
287    /// ```
288    /// # #[macro_use] extern crate imbl;
289    /// # use imbl::Vector;
290    /// let vec = vector!["Joe", "Mike", "Robert"];
291    /// assert_eq!(false, vec.is_empty());
292    /// assert_eq!(true, Vector::<i64>::new().is_empty());
293    /// ```
294    #[inline]
295    #[must_use]
296    pub fn is_empty(&self) -> bool {
297        self.len() == 0
298    }
299
300    /// Test whether a vector is currently inlined.
301    ///
302    /// Vectors small enough that their contents could be stored entirely inside
303    /// the space of `std::mem::size_of::<GenericVector<A, P>>()` bytes are stored inline on
304    /// the stack instead of allocating any chunks. This method returns `true` if
305    /// this vector is currently inlined, or `false` if it currently has chunks allocated
306    /// on the heap.
307    ///
308    /// This may be useful in conjunction with [`ptr_eq()`][ptr_eq], which checks if
309    /// two vectors' heap allocations are the same, and thus will never return `true`
310    /// for inlined vectors.
311    ///
312    /// Time: O(1)
313    ///
314    /// [ptr_eq]: #method.ptr_eq
315    #[inline]
316    #[must_use]
317    pub fn is_inline(&self) -> bool {
318        matches!(self.vector, Inline(_))
319    }
320
321    /// Test whether two vectors refer to the same content in memory.
322    ///
323    /// This uses the following rules to determine equality:
324    /// * If the two sides are references to the same vector, return true.
325    /// * If the two sides are single chunk vectors pointing to the same chunk, return true.
326    /// * If the two sides are full trees pointing to the same chunks, return true.
327    ///
328    /// This would return true if you're comparing a vector to itself, or
329    /// if you're comparing a vector to a fresh clone of itself. The exception to this is
330    /// if you've cloned an inline array (ie. an array with so few elements they can fit
331    /// inside the space a `Vector` allocates for its pointers, so there are no heap allocations
332    /// to compare).
333    ///
334    /// Time: O(1)
335    #[must_use]
336    pub fn ptr_eq(&self, other: &Self) -> bool {
337        fn cmp_chunk<A, P: SharedPointerKind>(
338            left: &SharedPointer<Chunk<A>, P>,
339            right: &SharedPointer<Chunk<A>, P>,
340        ) -> bool {
341            (left.is_empty() && right.is_empty()) || SharedPointer::ptr_eq(left, right)
342        }
343
344        if std::ptr::eq(self, other) {
345            return true;
346        }
347
348        match (&self.vector, &other.vector) {
349            (Single(left), Single(right)) => cmp_chunk(left, right),
350            (Full(left), Full(right)) => {
351                cmp_chunk(&left.outer_f, &right.outer_f)
352                    && cmp_chunk(&left.inner_f, &right.inner_f)
353                    && cmp_chunk(&left.inner_b, &right.inner_b)
354                    && cmp_chunk(&left.outer_b, &right.outer_b)
355                    && ((left.middle.is_empty() && right.middle.is_empty())
356                        || SharedPointer::ptr_eq(&left.middle, &right.middle))
357            }
358            _ => false,
359        }
360    }
361
362    /// Get an iterator over a vector.
363    ///
364    /// Time: O(1)
365    #[inline]
366    #[must_use]
367    pub fn iter(&self) -> Iter<'_, A, P> {
368        Iter::new(self)
369    }
370
371    /// Get an iterator over the leaf nodes of a vector.
372    ///
373    /// This returns an iterator over the [`Chunk`s][Chunk] at the leaves of the
374    /// RRB tree. These are useful for efficient parallelisation of work on
375    /// the vector, but should not be used for basic iteration.
376    ///
377    /// Time: O(1)
378    ///
379    /// [Chunk]: ../chunk/struct.Chunk.html
380    #[inline]
381    #[must_use]
382    pub fn leaves(&self) -> Chunks<'_, A, P> {
383        Chunks::new(self)
384    }
385
386    /// Construct a [`Focus`][Focus] for a vector.
387    ///
388    /// Time: O(1)
389    ///
390    /// [Focus]: enum.Focus.html
391    #[inline]
392    #[must_use]
393    pub fn focus(&self) -> Focus<'_, A, P> {
394        Focus::new(self)
395    }
396
397    /// Get a reference to the value at index `index` in a vector.
398    ///
399    /// Returns `None` if the index is out of bounds.
400    ///
401    /// Time: O(log n)
402    ///
403    /// # Examples
404    ///
405    /// ```
406    /// # #[macro_use] extern crate imbl;
407    /// let vec = vector!["Joe", "Mike", "Robert"];
408    /// assert_eq!(Some(&"Robert"), vec.get(2));
409    /// assert_eq!(None, vec.get(5));
410    /// ```
411    #[must_use]
412    pub fn get(&self, index: usize) -> Option<&A> {
413        if index >= self.len() {
414            return None;
415        }
416
417        match &self.vector {
418            Inline(chunk) => chunk.get(index),
419            Single(chunk) => chunk.get(index),
420            Full(tree) => {
421                let mut local_index = index;
422
423                if local_index < tree.outer_f.len() {
424                    return Some(&tree.outer_f[local_index]);
425                }
426                local_index -= tree.outer_f.len();
427
428                if local_index < tree.inner_f.len() {
429                    return Some(&tree.inner_f[local_index]);
430                }
431                local_index -= tree.inner_f.len();
432
433                if local_index < tree.middle.len() {
434                    return Some(tree.middle.index(tree.middle_level, local_index));
435                }
436                local_index -= tree.middle.len();
437
438                if local_index < tree.inner_b.len() {
439                    return Some(&tree.inner_b[local_index]);
440                }
441                local_index -= tree.inner_b.len();
442
443                Some(&tree.outer_b[local_index])
444            }
445        }
446    }
447
448    /// Get the first element of a vector.
449    ///
450    /// If the vector is empty, `None` is returned.
451    ///
452    /// Time: O(log n)
453    #[inline]
454    #[must_use]
455    pub fn front(&self) -> Option<&A> {
456        self.get(0)
457    }
458
459    /// Get the first element of a vector.
460    ///
461    /// If the vector is empty, `None` is returned.
462    ///
463    /// This is an alias for the [`front`][front] method.
464    ///
465    /// Time: O(log n)
466    ///
467    /// [front]: #method.front
468    #[inline]
469    #[must_use]
470    pub fn head(&self) -> Option<&A> {
471        self.get(0)
472    }
473
474    /// Get the last element of a vector.
475    ///
476    /// If the vector is empty, `None` is returned.
477    ///
478    /// Time: O(log n)
479    #[must_use]
480    pub fn back(&self) -> Option<&A> {
481        if self.is_empty() {
482            None
483        } else {
484            self.get(self.len() - 1)
485        }
486    }
487
488    /// Get the last element of a vector.
489    ///
490    /// If the vector is empty, `None` is returned.
491    ///
492    /// This is an alias for the [`back`][back] method.
493    ///
494    /// Time: O(log n)
495    ///
496    /// [back]: #method.back
497    #[inline]
498    #[must_use]
499    pub fn last(&self) -> Option<&A> {
500        self.back()
501    }
502
503    /// Get the index of a given element in the vector.
504    ///
505    /// Searches the vector for the first occurrence of a given value,
506    /// and returns the index of the value if it's there. Otherwise,
507    /// it returns `None`.
508    ///
509    /// Time: O(n)
510    ///
511    /// # Examples
512    ///
513    /// ```
514    /// # #[macro_use] extern crate imbl;
515    /// let mut vec = vector![1, 2, 3, 4, 5];
516    /// assert_eq!(Some(2), vec.index_of(&3));
517    /// assert_eq!(None, vec.index_of(&31337));
518    /// ```
519    #[must_use]
520    pub fn index_of(&self, value: &A) -> Option<usize>
521    where
522        A: PartialEq,
523    {
524        for (index, item) in self.iter().enumerate() {
525            if value == item {
526                return Some(index);
527            }
528        }
529        None
530    }
531
532    /// Test if a given element is in the vector.
533    ///
534    /// Searches the vector for the first occurrence of a given value,
535    /// and returns `true` if it's there. If it's nowhere to be found
536    /// in the vector, it returns `false`.
537    ///
538    /// Time: O(n)
539    ///
540    /// # Examples
541    ///
542    /// ```
543    /// # #[macro_use] extern crate imbl;
544    /// let mut vec = vector![1, 2, 3, 4, 5];
545    /// assert_eq!(true, vec.contains(&3));
546    /// assert_eq!(false, vec.contains(&31337));
547    /// ```
548    #[inline]
549    #[must_use]
550    pub fn contains(&self, value: &A) -> bool
551    where
552        A: PartialEq,
553    {
554        self.index_of(value).is_some()
555    }
556
557    /// Discard all elements from the vector.
558    ///
559    /// This leaves you with an empty vector, and all elements that
560    /// were previously inside it are dropped.
561    ///
562    /// Time: O(n)
563    pub fn clear(&mut self) {
564        if !self.is_empty() {
565            self.vector = Inline(InlineArray::new());
566        }
567    }
568
569    /// Binary search a sorted vector for a given element using a comparator
570    /// function.
571    ///
572    /// Assumes the vector has already been sorted using the same comparator
573    /// function, eg. by using [`sort_by`][sort_by].
574    ///
575    /// If the value is found, it returns `Ok(index)` where `index` is the index
576    /// of the element. If the value isn't found, it returns `Err(index)` where
577    /// `index` is the index at which the element would need to be inserted to
578    /// maintain sorted order.
579    ///
580    /// Time: O(log n)
581    ///
582    /// [sort_by]: #method.sort_by
583    pub fn binary_search_by<F>(&self, mut f: F) -> Result<usize, usize>
584    where
585        F: FnMut(&A) -> Ordering,
586    {
587        let mut size = self.len();
588        if size == 0 {
589            return Err(0);
590        }
591        let mut base = 0;
592        while size > 1 {
593            let half = size / 2;
594            let mid = base + half;
595            base = match f(&self[mid]) {
596                Ordering::Greater => base,
597                _ => mid,
598            };
599            size -= half;
600        }
601        match f(&self[base]) {
602            Ordering::Equal => Ok(base),
603            Ordering::Greater => Err(base),
604            Ordering::Less => Err(base + 1),
605        }
606    }
607
608    /// Binary search a sorted vector for a given element.
609    ///
610    /// If the value is found, it returns `Ok(index)` where `index` is the index
611    /// of the element. If the value isn't found, it returns `Err(index)` where
612    /// `index` is the index at which the element would need to be inserted to
613    /// maintain sorted order.
614    ///
615    /// Time: O(log n)
616    pub fn binary_search(&self, value: &A) -> Result<usize, usize>
617    where
618        A: Ord,
619    {
620        self.binary_search_by(|e| e.cmp(value))
621    }
622
623    /// Binary search a sorted vector for a given element with a key extract
624    /// function.
625    ///
626    /// Assumes the vector has already been sorted using the same key extract
627    /// function, eg. by using [`sort_by_key`][sort_by_key].
628    ///
629    /// If the value is found, it returns `Ok(index)` where `index` is the index
630    /// of the element. If the value isn't found, it returns `Err(index)` where
631    /// `index` is the index at which the element would need to be inserted to
632    /// maintain sorted order.
633    ///
634    /// Time: O(log n)
635    ///
636    /// [sort_by_key]: #method.sort_by_key
637    pub fn binary_search_by_key<B, F>(&self, b: &B, mut f: F) -> Result<usize, usize>
638    where
639        F: FnMut(&A) -> B,
640        B: Ord,
641    {
642        self.binary_search_by(|k| f(k).cmp(b))
643    }
644
645    /// Construct a vector with a single value.
646    ///
647    /// # Examples
648    ///
649    /// ```
650    /// # #[macro_use] extern crate imbl;
651    /// # use imbl::Vector;
652    /// let vec  = Vector::unit(1337);
653    /// assert_eq!(1, vec.len());
654    /// assert_eq!(
655    ///   vec.get(0),
656    ///   Some(&1337)
657    /// );
658    /// ```
659    #[inline]
660    #[must_use]
661    pub fn unit(a: A) -> Self {
662        if InlineArray::<A, RRB<A, P>>::CAPACITY > 0 {
663            let mut array = InlineArray::new();
664            array.push(a);
665            Self {
666                vector: Inline(array),
667            }
668        } else {
669            let chunk = SharedPointer::new(Chunk::unit(a));
670            Self {
671                vector: Single(chunk),
672            }
673        }
674    }
675
676    /// Dump the internal RRB tree into graphviz format.
677    ///
678    /// This method requires the `debug` feature flag.
679    #[cfg(any(test, feature = "debug"))]
680    pub fn dot<W: std::io::Write>(&self, write: W) -> std::io::Result<()> {
681        if let Full(ref tree) = self.vector {
682            tree.middle.dot(write)
683        } else {
684            Ok(())
685        }
686    }
687
688    /// Verify the internal consistency of a vector.
689    ///
690    /// This method walks the RRB tree making up the current `Vector`
691    /// (if it has one) and verifies that all the invariants hold.
692    /// If something is wrong, it will panic.
693    ///
694    /// This method requires the `debug` feature flag.
695    #[cfg(any(test, feature = "debug"))]
696    pub fn assert_invariants(&self) {
697        if let Full(ref tree) = self.vector {
698            tree.assert_invariants();
699        }
700    }
701}
702
703impl<A: Clone, P: SharedPointerKind> GenericVector<A, P> {
704    /// Get a mutable reference to the value at index `index` in a
705    /// vector.
706    ///
707    /// Returns `None` if the index is out of bounds.
708    ///
709    /// Time: O(log n)
710    ///
711    /// # Examples
712    ///
713    /// ```
714    /// # #[macro_use] extern crate imbl;
715    /// let mut vec = vector!["Joe", "Mike", "Robert"];
716    /// {
717    ///     let robert = vec.get_mut(2).unwrap();
718    ///     assert_eq!(&mut "Robert", robert);
719    ///     *robert = "Bjarne";
720    /// }
721    /// assert_eq!(vector!["Joe", "Mike", "Bjarne"], vec);
722    /// ```
723    #[must_use]
724    pub fn get_mut(&mut self, index: usize) -> Option<&mut A> {
725        if index >= self.len() {
726            return None;
727        }
728
729        match &mut self.vector {
730            Inline(chunk) => chunk.get_mut(index),
731            Single(chunk) => SharedPointer::make_mut(chunk).get_mut(index),
732            Full(tree) => {
733                let mut local_index = index;
734
735                if local_index < tree.outer_f.len() {
736                    let outer_f = SharedPointer::make_mut(&mut tree.outer_f);
737                    return Some(&mut outer_f[local_index]);
738                }
739                local_index -= tree.outer_f.len();
740
741                if local_index < tree.inner_f.len() {
742                    let inner_f = SharedPointer::make_mut(&mut tree.inner_f);
743                    return Some(&mut inner_f[local_index]);
744                }
745                local_index -= tree.inner_f.len();
746
747                if local_index < tree.middle.len() {
748                    let middle = SharedPointer::make_mut(&mut tree.middle);
749                    return Some(middle.index_mut(tree.middle_level, local_index));
750                }
751                local_index -= tree.middle.len();
752
753                if local_index < tree.inner_b.len() {
754                    let inner_b = SharedPointer::make_mut(&mut tree.inner_b);
755                    return Some(&mut inner_b[local_index]);
756                }
757                local_index -= tree.inner_b.len();
758
759                let outer_b = SharedPointer::make_mut(&mut tree.outer_b);
760                Some(&mut outer_b[local_index])
761            }
762        }
763    }
764
765    /// Get a mutable reference to the first element of a vector.
766    ///
767    /// If the vector is empty, `None` is returned.
768    ///
769    /// Time: O(log n)
770    #[inline]
771    #[must_use]
772    pub fn front_mut(&mut self) -> Option<&mut A> {
773        self.get_mut(0)
774    }
775
776    /// Get a mutable reference to the last element of a vector.
777    ///
778    /// If the vector is empty, `None` is returned.
779    ///
780    /// Time: O(log n)
781    #[must_use]
782    pub fn back_mut(&mut self) -> Option<&mut A> {
783        if self.is_empty() {
784            None
785        } else {
786            let len = self.len();
787            self.get_mut(len - 1)
788        }
789    }
790
791    /// Construct a [`FocusMut`][FocusMut] for a vector.
792    ///
793    /// Time: O(1)
794    ///
795    /// [FocusMut]: enum.FocusMut.html
796    #[inline]
797    #[must_use]
798    pub fn focus_mut(&mut self) -> FocusMut<'_, A, P> {
799        FocusMut::new(self)
800    }
801
802    /// Get a mutable iterator over a vector.
803    ///
804    /// Time: O(1)
805    #[inline]
806    #[must_use]
807    pub fn iter_mut(&mut self) -> IterMut<'_, A, P> {
808        IterMut::new(self)
809    }
810
811    /// Get a mutable iterator over the leaf nodes of a vector.
812    //
813    /// This returns an iterator over the [`Chunk`s][Chunk] at the leaves of the
814    /// RRB tree. These are useful for efficient parallelisation of work on
815    /// the vector, but should not be used for basic iteration.
816    ///
817    /// Time: O(1)
818    ///
819    /// [Chunk]: ../chunk/struct.Chunk.html
820    #[inline]
821    #[must_use]
822    pub fn leaves_mut(&mut self) -> ChunksMut<'_, A, P> {
823        ChunksMut::new(self)
824    }
825
826    /// Create a new vector with the value at index `index` updated.
827    ///
828    /// Panics if the index is out of bounds.
829    ///
830    /// Time: O(log n)
831    ///
832    /// # Examples
833    ///
834    /// ```
835    /// # #[macro_use] extern crate imbl;
836    /// let mut vec = vector![1, 2, 3];
837    /// assert_eq!(vector![1, 5, 3], vec.update(1, 5));
838    /// ```
839    #[must_use]
840    pub fn update(&self, index: usize, value: A) -> Self {
841        let mut out = self.clone();
842        out[index] = value;
843        out
844    }
845
846    /// Update the value at index `index` in a vector.
847    ///
848    /// Returns the previous value at the index.
849    ///
850    /// Panics if the index is out of bounds.
851    ///
852    /// Time: O(log n)
853    #[inline]
854    pub fn set(&mut self, index: usize, value: A) -> A {
855        replace(&mut self[index], value)
856    }
857
858    /// Swap the elements at indices `i` and `j`.
859    ///
860    /// Time: O(log n)
861    pub fn swap(&mut self, i: usize, j: usize) {
862        if i != j {
863            let a: *mut A = &mut self[i];
864            let b: *mut A = &mut self[j];
865
866            // Vector's implementation of IndexMut ensures that if `i` and `j` are different
867            // indices then `&mut self[i]` and `&mut self[j]` are non-overlapping.
868            unsafe {
869                std::ptr::swap(a, b);
870            }
871        }
872    }
873
874    /// Push a value to the front of a vector.
875    ///
876    /// Time: O(1)*
877    ///
878    /// # Examples
879    ///
880    /// ```
881    /// # #[macro_use] extern crate imbl;
882    /// let mut vec = vector![5, 6, 7];
883    /// vec.push_front(4);
884    /// assert_eq!(vector![4, 5, 6, 7], vec);
885    /// ```
886    pub fn push_front(&mut self, value: A) {
887        if self.needs_promotion() {
888            self.promote_back();
889        }
890        match &mut self.vector {
891            Inline(chunk) => {
892                chunk.insert(0, value);
893            }
894            Single(chunk) => SharedPointer::make_mut(chunk).push_front(value),
895            Full(tree) => tree.push_front(value),
896        }
897    }
898
899    /// Push a value to the back of a vector.
900    ///
901    /// Time: O(1)*
902    ///
903    /// # Examples
904    ///
905    /// ```
906    /// # #[macro_use] extern crate imbl;
907    /// let mut vec = vector![1, 2, 3];
908    /// vec.push_back(4);
909    /// assert_eq!(vector![1, 2, 3, 4], vec);
910    /// ```
911    pub fn push_back(&mut self, value: A) {
912        if self.needs_promotion() {
913            self.promote_front();
914        }
915        match &mut self.vector {
916            Inline(chunk) => {
917                chunk.push(value);
918            }
919            Single(chunk) => SharedPointer::make_mut(chunk).push_back(value),
920            Full(tree) => tree.push_back(value),
921        }
922    }
923
924    /// Remove the first element from a vector and return it.
925    ///
926    /// Time: O(1)*
927    ///
928    /// # Examples
929    ///
930    /// ```
931    /// # #[macro_use] extern crate imbl;
932    /// let mut vec = vector![1, 2, 3];
933    /// assert_eq!(Some(1), vec.pop_front());
934    /// assert_eq!(vector![2, 3], vec);
935    /// ```
936    pub fn pop_front(&mut self) -> Option<A> {
937        if self.is_empty() {
938            None
939        } else {
940            match &mut self.vector {
941                Inline(chunk) => chunk.remove(0),
942                Single(chunk) => Some(SharedPointer::make_mut(chunk).pop_front()),
943                Full(tree) => tree.pop_front(),
944            }
945        }
946    }
947
948    /// Remove the last element from a vector and return it.
949    ///
950    /// Time: O(1)*
951    ///
952    /// # Examples
953    ///
954    /// ```
955    /// # #[macro_use] extern crate imbl;
956    /// # use imbl::Vector;
957    /// let mut vec = vector![1, 2, 3];
958    /// assert_eq!(Some(3), vec.pop_back());
959    /// assert_eq!(vector![1, 2], vec);
960    /// ```
961    pub fn pop_back(&mut self) -> Option<A> {
962        if self.is_empty() {
963            None
964        } else {
965            match &mut self.vector {
966                Inline(chunk) => chunk.pop(),
967                Single(chunk) => Some(SharedPointer::make_mut(chunk).pop_back()),
968                Full(tree) => tree.pop_back(),
969            }
970        }
971    }
972
973    /// Append the vector `other` to the end of the current vector.
974    ///
975    /// Time: O(log n)
976    ///
977    /// # Examples
978    ///
979    /// ```
980    /// # #[macro_use] extern crate imbl;
981    /// let mut vec = vector![1, 2, 3];
982    /// vec.append(vector![7, 8, 9]);
983    /// assert_eq!(vector![1, 2, 3, 7, 8, 9], vec);
984    /// ```
985    pub fn append(&mut self, mut other: Self) {
986        if other.is_empty() {
987            return;
988        }
989
990        if self.is_empty() {
991            *self = other;
992            return;
993        }
994
995        self.promote_inline();
996        other.promote_inline();
997
998        let total_length = self
999            .len()
1000            .checked_add(other.len())
1001            .expect("Vector length overflow");
1002
1003        match &mut self.vector {
1004            Inline(_) => unreachable!("inline vecs should have been promoted"),
1005            Single(left) => {
1006                match &mut other.vector {
1007                    Inline(_) => unreachable!("inline vecs should have been promoted"),
1008                    // If both are single chunks and left has room for right: directly
1009                    // memcpy right into left
1010                    Single(ref mut right) if total_length <= CHUNK_SIZE => {
1011                        SharedPointer::make_mut(left).append(SharedPointer::make_mut(right));
1012                        return;
1013                    }
1014                    // If only left is a single chunk and has room for right: push
1015                    // right's elements into left
1016                    _ if total_length <= CHUNK_SIZE => {
1017                        while let Some(value) = other.pop_front() {
1018                            SharedPointer::make_mut(left).push_back(value);
1019                        }
1020                        return;
1021                    }
1022                    _ => {}
1023                }
1024            }
1025            Full(left) => {
1026                if let Full(mut right) = other.vector {
1027                    // If left and right are trees with empty middles, left has no back
1028                    // buffers, and right has no front buffers: copy right's back
1029                    // buffers over to left
1030                    if left.middle.is_empty()
1031                        && right.middle.is_empty()
1032                        && left.outer_b.is_empty()
1033                        && left.inner_b.is_empty()
1034                        && right.outer_f.is_empty()
1035                        && right.inner_f.is_empty()
1036                    {
1037                        left.inner_b = right.inner_b;
1038                        left.outer_b = right.outer_b;
1039                        left.length = total_length;
1040                        return;
1041                    }
1042                    // If left and right are trees with empty middles and left's buffers
1043                    // can fit right's buffers: push right's elements onto left
1044                    if left.middle.is_empty()
1045                        && right.middle.is_empty()
1046                        && total_length <= CHUNK_SIZE * 4
1047                    {
1048                        while let Some(value) = right.pop_front() {
1049                            left.push_back(value);
1050                        }
1051                        return;
1052                    }
1053                    // Both are full and big: do the full RRB join
1054                    let inner_b1 = left.inner_b.clone();
1055                    left.push_middle(Side::Right, inner_b1);
1056                    let outer_b1 = left.outer_b.clone();
1057                    left.push_middle(Side::Right, outer_b1);
1058                    let inner_f2 = right.inner_f.clone();
1059                    right.push_middle(Side::Left, inner_f2);
1060                    let outer_f2 = right.outer_f.clone();
1061                    right.push_middle(Side::Left, outer_f2);
1062
1063                    let mut middle1 =
1064                        clone_ref(replace(&mut left.middle, SharedPointer::new(Node::new())));
1065                    let mut middle2 = clone_ref(right.middle);
1066                    let normalised_middle = match left.middle_level.cmp(&right.middle_level) {
1067                        Ordering::Greater => {
1068                            middle2 = middle2.elevate(left.middle_level - right.middle_level);
1069                            left.middle_level
1070                        }
1071                        Ordering::Less => {
1072                            middle1 = middle1.elevate(right.middle_level - left.middle_level);
1073                            right.middle_level
1074                        }
1075                        Ordering::Equal => left.middle_level,
1076                    };
1077                    left.middle =
1078                        SharedPointer::new(Node::merge(middle1, middle2, normalised_middle));
1079                    left.middle_level = normalised_middle + 1;
1080
1081                    left.inner_b = right.inner_b;
1082                    left.outer_b = right.outer_b;
1083                    left.length = total_length;
1084                    left.prune();
1085                    return;
1086                }
1087            }
1088        }
1089        // No optimisations available, and either left, right or both are
1090        // single: promote both to full and retry
1091        self.promote_front();
1092        other.promote_back();
1093        self.append(other)
1094    }
1095
1096    /// Retain only the elements specified by the predicate.
1097    ///
1098    /// Remove all elements for which the provided function `f`
1099    /// returns false from the vector.
1100    ///
1101    /// Time: O(n)
1102    pub fn retain<F>(&mut self, mut f: F)
1103    where
1104        F: FnMut(&A) -> bool,
1105    {
1106        let len = self.len();
1107        let mut del = 0;
1108        {
1109            let mut focus = self.focus_mut();
1110            for i in 0..len {
1111                if !f(focus.index(i)) {
1112                    del += 1;
1113                } else if del > 0 {
1114                    focus.swap(i - del, i);
1115                }
1116            }
1117        }
1118        if del > 0 {
1119            let _ = self.split_off(len - del);
1120        }
1121    }
1122
1123    /// Split a vector at a given index.
1124    ///
1125    /// Split a vector at a given index, consuming the vector and
1126    /// returning a pair of the left hand side and the right hand side
1127    /// of the split.
1128    ///
1129    /// Time: O(log n)
1130    ///
1131    /// # Examples
1132    ///
1133    /// ```
1134    /// # #[macro_use] extern crate imbl;
1135    /// let mut vec = vector![1, 2, 3, 7, 8, 9];
1136    /// let (left, right) = vec.split_at(3);
1137    /// assert_eq!(vector![1, 2, 3], left);
1138    /// assert_eq!(vector![7, 8, 9], right);
1139    /// ```
1140    pub fn split_at(mut self, index: usize) -> (Self, Self) {
1141        let right = self.split_off(index);
1142        (self, right)
1143    }
1144
1145    /// Split a vector at a given index.
1146    ///
1147    /// Split a vector at a given index, leaving the left hand side in
1148    /// the current vector and returning a new vector containing the
1149    /// right hand side.
1150    ///
1151    /// Time: O(log n)
1152    ///
1153    /// # Examples
1154    ///
1155    /// ```
1156    /// # #[macro_use] extern crate imbl;
1157    /// let mut left = vector![1, 2, 3, 7, 8, 9];
1158    /// let right = left.split_off(3);
1159    /// assert_eq!(vector![1, 2, 3], left);
1160    /// assert_eq!(vector![7, 8, 9], right);
1161    /// ```
1162    #[must_use]
1163    pub fn split_off(&mut self, index: usize) -> Self {
1164        assert!(index <= self.len());
1165
1166        match &mut self.vector {
1167            Inline(chunk) => Self {
1168                vector: Inline(chunk.split_off(index)),
1169            },
1170            Single(chunk) => Self {
1171                vector: Single(SharedPointer::new(
1172                    SharedPointer::make_mut(chunk).split_off(index),
1173                )),
1174            },
1175            Full(tree) => {
1176                let mut local_index = index;
1177
1178                if local_index < tree.outer_f.len() {
1179                    let of2 = SharedPointer::make_mut(&mut tree.outer_f).split_off(local_index);
1180                    let right = RRB {
1181                        length: tree.length - index,
1182                        middle_level: tree.middle_level,
1183                        outer_f: SharedPointer::new(of2),
1184                        inner_f: replace_shared_pointer(&mut tree.inner_f),
1185                        middle: std::mem::take(&mut tree.middle),
1186                        inner_b: replace_shared_pointer(&mut tree.inner_b),
1187                        outer_b: replace_shared_pointer(&mut tree.outer_b),
1188                    };
1189                    tree.length = index;
1190                    tree.middle_level = 0;
1191                    return Self {
1192                        vector: Full(right),
1193                    };
1194                }
1195
1196                local_index -= tree.outer_f.len();
1197
1198                if local_index < tree.inner_f.len() {
1199                    let if2 = SharedPointer::make_mut(&mut tree.inner_f).split_off(local_index);
1200                    let right = RRB {
1201                        length: tree.length - index,
1202                        middle_level: tree.middle_level,
1203                        outer_f: SharedPointer::new(if2),
1204                        inner_f: SharedPointer::default(),
1205                        middle: std::mem::take(&mut tree.middle),
1206                        inner_b: replace_shared_pointer(&mut tree.inner_b),
1207                        outer_b: replace_shared_pointer(&mut tree.outer_b),
1208                    };
1209                    tree.length = index;
1210                    tree.middle_level = 0;
1211                    swap(&mut tree.outer_b, &mut tree.inner_f);
1212                    return Self {
1213                        vector: Full(right),
1214                    };
1215                }
1216
1217                local_index -= tree.inner_f.len();
1218
1219                if local_index < tree.middle.len() {
1220                    let mut right_middle = tree.middle.clone();
1221                    let (c1, c2) = {
1222                        let m1 = SharedPointer::make_mut(&mut tree.middle);
1223                        let m2 = SharedPointer::make_mut(&mut right_middle);
1224                        match m1.split(tree.middle_level, Side::Right, local_index) {
1225                            SplitResult::Dropped(_) => (),
1226                            SplitResult::OutOfBounds => unreachable!(),
1227                        };
1228                        match m2.split(tree.middle_level, Side::Left, local_index) {
1229                            SplitResult::Dropped(_) => (),
1230                            SplitResult::OutOfBounds => unreachable!(),
1231                        };
1232                        let c1 = match m1.pop_chunk(tree.middle_level, Side::Right) {
1233                            PopResult::Empty => SharedPointer::default(),
1234                            PopResult::Done(chunk) => chunk,
1235                            PopResult::Drained(chunk) => {
1236                                m1.clear_node();
1237                                chunk
1238                            }
1239                        };
1240                        let c2 = match m2.pop_chunk(tree.middle_level, Side::Left) {
1241                            PopResult::Empty => SharedPointer::default(),
1242                            PopResult::Done(chunk) => chunk,
1243                            PopResult::Drained(chunk) => {
1244                                m2.clear_node();
1245                                chunk
1246                            }
1247                        };
1248                        (c1, c2)
1249                    };
1250                    let mut right = RRB {
1251                        length: tree.length - index,
1252                        middle_level: tree.middle_level,
1253                        outer_f: c2,
1254                        inner_f: SharedPointer::default(),
1255                        middle: right_middle,
1256                        inner_b: replace_shared_pointer(&mut tree.inner_b),
1257                        outer_b: replace(&mut tree.outer_b, c1),
1258                    };
1259                    tree.length = index;
1260                    tree.prune();
1261                    right.prune();
1262                    return Self {
1263                        vector: Full(right),
1264                    };
1265                }
1266
1267                local_index -= tree.middle.len();
1268
1269                if local_index < tree.inner_b.len() {
1270                    let ib2 = SharedPointer::make_mut(&mut tree.inner_b).split_off(local_index);
1271                    let right = RRB {
1272                        length: tree.length - index,
1273                        outer_b: replace_shared_pointer(&mut tree.outer_b),
1274                        outer_f: SharedPointer::new(ib2),
1275                        ..RRB::new()
1276                    };
1277                    tree.length = index;
1278                    swap(&mut tree.outer_b, &mut tree.inner_b);
1279                    return Self {
1280                        vector: Full(right),
1281                    };
1282                }
1283
1284                local_index -= tree.inner_b.len();
1285
1286                let ob2 = SharedPointer::make_mut(&mut tree.outer_b).split_off(local_index);
1287                tree.length = index;
1288                Self {
1289                    vector: Single(SharedPointer::new(ob2)),
1290                }
1291            }
1292        }
1293    }
1294
1295    /// Construct a vector with `count` elements removed from the
1296    /// start of the current vector.
1297    ///
1298    /// Time: O(log n)
1299    #[must_use]
1300    pub fn skip(&self, count: usize) -> Self {
1301        match count {
1302            0 => self.clone(),
1303            count if count >= self.len() => Self::new(),
1304            count => {
1305                // FIXME can be made more efficient by dropping the unwanted side without constructing it
1306                self.clone().split_off(count)
1307            }
1308        }
1309    }
1310
1311    /// Construct a vector of the first `count` elements from the
1312    /// current vector.
1313    ///
1314    /// Time: O(log n)
1315    #[must_use]
1316    pub fn take(&self, count: usize) -> Self {
1317        // FIXME can be made more efficient by dropping the unwanted side without constructing it
1318        let mut left = self.clone();
1319        let _ = left.split_off(count);
1320        left
1321    }
1322
1323    /// Truncate a vector to the given size.
1324    ///
1325    /// Discards all elements in the vector beyond the given length.
1326    /// Does nothing if `len` is greater or equal to the length of the vector.
1327    ///
1328    /// Time: O(log n)
1329    pub fn truncate(&mut self, len: usize) {
1330        if len < self.len() {
1331            // FIXME can be made more efficient by dropping the unwanted side without constructing it
1332            let _ = self.split_off(len);
1333        }
1334    }
1335
1336    /// Extract a slice from a vector.
1337    ///
1338    /// Remove the elements from `start_index` until `end_index` in
1339    /// the current vector and return the removed slice as a new
1340    /// vector.
1341    ///
1342    /// Time: O(log n)
1343    #[must_use]
1344    pub fn slice<R>(&mut self, range: R) -> Self
1345    where
1346        R: RangeBounds<usize>,
1347    {
1348        let r = to_range(&range, self.len());
1349        if r.start >= r.end || r.start >= self.len() {
1350            return GenericVector::new();
1351        }
1352        let mut middle = self.split_off(r.start);
1353        let right = middle.split_off(r.end - r.start);
1354        self.append(right);
1355        middle
1356    }
1357
1358    /// Insert an element into a vector.
1359    ///
1360    /// Insert an element at position `index`, shifting all elements
1361    /// after it to the right.
1362    ///
1363    /// ## Performance Note
1364    ///
1365    /// While `push_front` and `push_back` are heavily optimised
1366    /// operations, `insert` in the middle of a vector requires a
1367    /// split, a push, and an append. Thus, if you want to insert
1368    /// many elements at the same location, instead of `insert`ing
1369    /// them one by one, you should rather create a new vector
1370    /// containing the elements to insert, split the vector at the
1371    /// insertion point, and append the left hand, the new vector and
1372    /// the right hand in order.
1373    ///
1374    /// Time: O(log n)
1375    pub fn insert(&mut self, index: usize, value: A) {
1376        if index == 0 {
1377            return self.push_front(value);
1378        }
1379        if index == self.len() {
1380            return self.push_back(value);
1381        }
1382        assert!(index < self.len());
1383        if matches!(&self.vector, Inline(_)) && self.needs_promotion() {
1384            self.promote_inline();
1385        }
1386        match &mut self.vector {
1387            Inline(chunk) => {
1388                chunk.insert(index, value);
1389            }
1390            Single(chunk) if chunk.len() < CHUNK_SIZE => {
1391                SharedPointer::make_mut(chunk).insert(index, value)
1392            }
1393            // TODO a lot of optimisations still possible here
1394            _ => {
1395                let right = self.split_off(index);
1396                self.push_back(value);
1397                self.append(right);
1398            }
1399        }
1400    }
1401
1402    /// Remove an element from a vector.
1403    ///
1404    /// Remove the element from position 'index', shifting all
1405    /// elements after it to the left, and return the removed element.
1406    ///
1407    /// ## Performance Note
1408    ///
1409    /// While `pop_front` and `pop_back` are heavily optimised
1410    /// operations, `remove` in the middle of a vector requires a
1411    /// split, a pop, and an append. Thus, if you want to remove many
1412    /// elements from the same location, instead of `remove`ing them
1413    /// one by one, it is much better to use [`slice`][slice].
1414    ///
1415    /// Time: O(log n)
1416    ///
1417    /// [slice]: #method.slice
1418    pub fn remove(&mut self, index: usize) -> A {
1419        assert!(index < self.len());
1420        match &mut self.vector {
1421            Inline(chunk) => chunk.remove(index).unwrap(),
1422            Single(chunk) => SharedPointer::make_mut(chunk).remove(index),
1423            _ => {
1424                if index == 0 {
1425                    return self.pop_front().unwrap();
1426                }
1427                if index == self.len() - 1 {
1428                    return self.pop_back().unwrap();
1429                }
1430                // TODO a lot of optimisations still possible here
1431                let mut right = self.split_off(index);
1432                let value = right.pop_front().unwrap();
1433                self.append(right);
1434                value
1435            }
1436        }
1437    }
1438
1439    /// Insert an element into a sorted vector.
1440    ///
1441    /// Insert an element into a vector in sorted order, assuming the vector is
1442    /// already in sorted order.
1443    ///
1444    /// Time: O(log n)
1445    ///
1446    /// # Examples
1447    ///
1448    /// ```
1449    /// # #[macro_use] extern crate imbl;
1450    /// let mut vec = vector![1, 2, 3, 7, 8, 9];
1451    /// vec.insert_ord(5);
1452    /// assert_eq!(vector![1, 2, 3, 5, 7, 8, 9], vec);
1453    /// ```
1454    pub fn insert_ord(&mut self, item: A)
1455    where
1456        A: Ord,
1457    {
1458        match self.binary_search(&item) {
1459            Ok(index) => self.insert(index, item),
1460            Err(index) => self.insert(index, item),
1461        }
1462    }
1463
1464    /// Insert an element into a sorted vector using a comparator function.
1465    ///
1466    /// Insert an element into a vector in sorted order using the given
1467    /// comparator function, assuming the vector is already in sorted order.
1468    ///
1469    /// Note that the ordering used to sort the vector must logically match
1470    /// the ordering in the comparison function provided to `insert_ord_by`.
1471    /// Incompatible definitions of the ordering won't result in memory
1472    /// unsafety, but will likely result in out-of-order insertions.
1473    ///
1474    ///
1475    /// Time: O(log n)
1476    ///
1477    /// # Examples
1478    ///
1479    /// ```
1480    /// # #[macro_use] extern crate imbl;
1481    /// let mut vec = vector![9, 8, 7, 3, 2, 1];
1482    /// vec.insert_ord_by(5, |a, b| a.cmp(b).reverse());
1483    /// assert_eq!(vector![9, 8, 7, 5, 3, 2, 1], vec);
1484    ///
1485    /// // Note that `insert_ord` does not work in this case because it uses
1486    /// // the default comparison function for the item type.
1487    /// vec.insert_ord(4);
1488    /// assert_eq!(vector![4, 9, 8, 7, 5, 3, 2, 1], vec);
1489    /// ```
1490    pub fn insert_ord_by<F>(&mut self, item: A, mut f: F)
1491    where
1492        F: FnMut(&A, &A) -> Ordering,
1493    {
1494        match self.binary_search_by(|scan_item| f(scan_item, &item)) {
1495            Ok(idx) | Err(idx) => self.insert(idx, item),
1496        }
1497    }
1498
1499    /// Insert an element into a sorted vector where the comparison function
1500    /// delegates to the Ord implementation for values calculated by a user-
1501    /// provided function defined on the item type.
1502    ///
1503    /// This function assumes the vector is already sorted. If it isn't sorted,
1504    /// this function may insert the provided value out of order.
1505    ///
1506    /// Note that the ordering of the sorted vector must logically match the
1507    /// `PartialOrd` implementation of the type returned by the passed comparator
1508    /// function `f`. Incompatible definitions of the ordering won't result in
1509    /// memory unsafety, but will likely result in out-of-order insertions.
1510    ///
1511    ///
1512    /// Time: O(log n)
1513    ///
1514    /// # Examples
1515    ///
1516    /// ```
1517    /// # #[macro_use] extern crate imbl;
1518    /// # use imbl::Vector;
1519    ///
1520    /// type A = (u8, &'static str);
1521    ///
1522    /// let mut vec: Vector<A> = vector![(3, "a"), (1, "c"), (0, "d")];
1523    ///
1524    /// // For the sake of this example, let's say that only the second element
1525    /// // of the A tuple is important in the context of comparison.
1526    /// vec.insert_ord_by_key((0, "b"), |a| a.1);
1527    /// assert_eq!(vector![(3, "a"), (0, "b"), (1, "c"), (0, "d")], vec);
1528    ///
1529    /// // Note that `insert_ord` does not work in this case because it uses
1530    /// // the default comparison function for the item type.
1531    /// vec.insert_ord((0, "e"));
1532    /// assert_eq!(vector![(3, "a"), (0, "b"), (0, "e"), (1, "c"), (0, "d")], vec);
1533    /// ```
1534    pub fn insert_ord_by_key<B, F>(&mut self, item: A, mut f: F)
1535    where
1536        B: Ord,
1537        F: FnMut(&A) -> B,
1538    {
1539        match self.binary_search_by_key(&f(&item), |scan_item| f(scan_item)) {
1540            Ok(idx) | Err(idx) => self.insert(idx, item),
1541        }
1542    }
1543
1544    /// Sort a vector.
1545    ///
1546    /// Time: O(n log n)
1547    ///
1548    /// # Examples
1549    ///
1550    /// ```
1551    /// # #[macro_use] extern crate imbl;
1552    /// let mut vec = vector![3, 2, 5, 4, 1];
1553    /// vec.sort();
1554    /// assert_eq!(vector![1, 2, 3, 4, 5], vec);
1555    /// ```
1556    pub fn sort(&mut self)
1557    where
1558        A: Ord,
1559    {
1560        self.sort_by(Ord::cmp)
1561    }
1562
1563    /// Sort a vector using a comparator function.
1564    ///
1565    /// Time: O(n log n)
1566    ///
1567    /// # Examples
1568    ///
1569    /// ```
1570    /// # #[macro_use] extern crate imbl;
1571    /// let mut vec = vector![3, 2, 5, 4, 1];
1572    /// vec.sort_by(|left, right| left.cmp(right));
1573    /// assert_eq!(vector![1, 2, 3, 4, 5], vec);
1574    /// ```
1575    pub fn sort_by<F>(&mut self, cmp: F)
1576    where
1577        F: Fn(&A, &A) -> Ordering,
1578    {
1579        let len = self.len();
1580        if len > 1 {
1581            sort::quicksort(self.focus_mut(), &cmp);
1582        }
1583    }
1584}
1585
1586// Implementation details
1587
1588impl<A, P: SharedPointerKind> RRB<A, P> {
1589    fn new() -> Self {
1590        RRB {
1591            length: 0,
1592            middle_level: 0,
1593            outer_f: SharedPointer::default(),
1594            inner_f: SharedPointer::default(),
1595            middle: SharedPointer::new(Node::new()),
1596            inner_b: SharedPointer::default(),
1597            outer_b: SharedPointer::default(),
1598        }
1599    }
1600
1601    #[cfg(any(test, feature = "debug"))]
1602    fn assert_invariants(&self) {
1603        let ml = self.middle.assert_invariants(self.middle_level);
1604        assert_eq!(
1605            self.length,
1606            self.outer_f.len() + self.inner_f.len() + ml + self.inner_b.len() + self.outer_b.len()
1607        );
1608    }
1609}
1610
1611impl<A: Clone, P: SharedPointerKind> RRB<A, P> {
1612    fn prune(&mut self) {
1613        if self.middle.is_empty() {
1614            self.middle = SharedPointer::new(Node::new());
1615            self.middle_level = 0;
1616        } else {
1617            while self.middle_level > 0 && self.middle.is_single() {
1618                // FIXME could be optimised, cloning the node is expensive
1619                self.middle = SharedPointer::new(self.middle.first_child().clone());
1620                self.middle_level -= 1;
1621            }
1622        }
1623    }
1624
1625    fn pop_front(&mut self) -> Option<A> {
1626        if self.length == 0 {
1627            return None;
1628        }
1629        if self.outer_f.is_empty() {
1630            if self.inner_f.is_empty() {
1631                if self.middle.is_empty() {
1632                    if self.inner_b.is_empty() {
1633                        swap(&mut self.outer_f, &mut self.outer_b);
1634                    } else {
1635                        swap(&mut self.outer_f, &mut self.inner_b);
1636                    }
1637                } else {
1638                    self.outer_f = self.pop_middle(Side::Left).unwrap();
1639                }
1640            } else {
1641                swap(&mut self.outer_f, &mut self.inner_f);
1642            }
1643        }
1644        self.length -= 1;
1645        let outer_f = SharedPointer::make_mut(&mut self.outer_f);
1646        Some(outer_f.pop_front())
1647    }
1648
1649    fn pop_back(&mut self) -> Option<A> {
1650        if self.length == 0 {
1651            return None;
1652        }
1653        if self.outer_b.is_empty() {
1654            if self.inner_b.is_empty() {
1655                if self.middle.is_empty() {
1656                    if self.inner_f.is_empty() {
1657                        swap(&mut self.outer_b, &mut self.outer_f);
1658                    } else {
1659                        swap(&mut self.outer_b, &mut self.inner_f);
1660                    }
1661                } else {
1662                    self.outer_b = self.pop_middle(Side::Right).unwrap();
1663                }
1664            } else {
1665                swap(&mut self.outer_b, &mut self.inner_b);
1666            }
1667        }
1668        self.length -= 1;
1669        let outer_b = SharedPointer::make_mut(&mut self.outer_b);
1670        Some(outer_b.pop_back())
1671    }
1672
1673    fn push_front(&mut self, value: A) {
1674        if self.outer_f.is_full() {
1675            swap(&mut self.outer_f, &mut self.inner_f);
1676            if !self.outer_f.is_empty() {
1677                let mut chunk = SharedPointer::new(Chunk::new());
1678                swap(&mut chunk, &mut self.outer_f);
1679                self.push_middle(Side::Left, chunk);
1680            }
1681        }
1682        self.length = self.length.checked_add(1).expect("Vector length overflow");
1683        let outer_f = SharedPointer::make_mut(&mut self.outer_f);
1684        outer_f.push_front(value)
1685    }
1686
1687    fn push_back(&mut self, value: A) {
1688        if self.outer_b.is_full() {
1689            swap(&mut self.outer_b, &mut self.inner_b);
1690            if !self.outer_b.is_empty() {
1691                let mut chunk = SharedPointer::new(Chunk::new());
1692                swap(&mut chunk, &mut self.outer_b);
1693                self.push_middle(Side::Right, chunk);
1694            }
1695        }
1696        self.length = self.length.checked_add(1).expect("Vector length overflow");
1697        let outer_b = SharedPointer::make_mut(&mut self.outer_b);
1698        outer_b.push_back(value)
1699    }
1700
1701    fn push_middle(&mut self, side: Side, chunk: SharedPointer<Chunk<A>, P>) {
1702        if chunk.is_empty() {
1703            return;
1704        }
1705        let new_middle = {
1706            let middle = SharedPointer::make_mut(&mut self.middle);
1707            match middle.push_chunk(self.middle_level, side, chunk) {
1708                PushResult::Done => return,
1709                PushResult::Full(chunk, _num_drained) => SharedPointer::new({
1710                    match side {
1711                        Side::Left => Node::from_chunk(self.middle_level, chunk)
1712                            .join_branches(middle.clone(), self.middle_level),
1713                        Side::Right => middle.clone().join_branches(
1714                            Node::from_chunk(self.middle_level, chunk),
1715                            self.middle_level,
1716                        ),
1717                    }
1718                }),
1719            }
1720        };
1721        self.middle_level += 1;
1722        self.middle = new_middle;
1723    }
1724
1725    fn pop_middle(&mut self, side: Side) -> Option<SharedPointer<Chunk<A>, P>> {
1726        let chunk = {
1727            let middle = SharedPointer::make_mut(&mut self.middle);
1728            match middle.pop_chunk(self.middle_level, side) {
1729                PopResult::Empty => return None,
1730                PopResult::Done(chunk) => chunk,
1731                PopResult::Drained(chunk) => {
1732                    middle.clear_node();
1733                    self.middle_level = 0;
1734                    chunk
1735                }
1736            }
1737        };
1738        Some(chunk)
1739    }
1740}
1741
1742#[inline]
1743fn replace_shared_pointer<A: Default, P: SharedPointerKind>(
1744    dest: &mut SharedPointer<A, P>,
1745) -> SharedPointer<A, P> {
1746    std::mem::take(dest)
1747}
1748
1749// Core traits
1750
1751impl<A, P: SharedPointerKind> Default for GenericVector<A, P> {
1752    fn default() -> Self {
1753        Self::new()
1754    }
1755}
1756
1757impl<A: Clone, P: SharedPointerKind> Clone for GenericVector<A, P> {
1758    /// Clone a vector.
1759    ///
1760    /// Time: O(1), or O(n) with a very small, bounded *n* for an inline vector.
1761    fn clone(&self) -> Self {
1762        Self {
1763            vector: match &self.vector {
1764                Inline(chunk) => Inline(chunk.clone()),
1765                Single(chunk) => Single(chunk.clone()),
1766                Full(tree) => Full(tree.clone()),
1767            },
1768        }
1769    }
1770}
1771
1772impl<A: Debug, P: SharedPointerKind> Debug for GenericVector<A, P> {
1773    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
1774        f.debug_list().entries(self.iter()).finish()
1775        // match self {
1776        //     Full(rrb) => {
1777        //         writeln!(f, "Head: {:?} {:?}", rrb.outer_f, rrb.inner_f)?;
1778        //         rrb.middle.print(f, 0, rrb.middle_level)?;
1779        //         writeln!(f, "Tail: {:?} {:?}", rrb.inner_b, rrb.outer_b)
1780        //     }
1781        //     Single(_) => write!(f, "nowt"),
1782        // }
1783    }
1784}
1785
1786impl<A: PartialEq, P: SharedPointerKind> PartialEq for GenericVector<A, P> {
1787    fn eq(&self, other: &Self) -> bool {
1788        self.len() == other.len() && self.iter().eq(other.iter())
1789    }
1790}
1791
1792impl<A: Eq, P: SharedPointerKind> Eq for GenericVector<A, P> {}
1793
1794impl<A: PartialOrd, P: SharedPointerKind> PartialOrd for GenericVector<A, P> {
1795    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1796        self.iter().partial_cmp(other.iter())
1797    }
1798}
1799
1800impl<A: Ord, P: SharedPointerKind> Ord for GenericVector<A, P> {
1801    fn cmp(&self, other: &Self) -> Ordering {
1802        self.iter().cmp(other.iter())
1803    }
1804}
1805
1806impl<A: Hash, P: SharedPointerKind> Hash for GenericVector<A, P> {
1807    fn hash<H: Hasher>(&self, state: &mut H) {
1808        for i in self {
1809            i.hash(state)
1810        }
1811    }
1812}
1813
1814impl<A: Clone, P: SharedPointerKind> Sum for GenericVector<A, P> {
1815    fn sum<I>(it: I) -> Self
1816    where
1817        I: Iterator<Item = Self>,
1818    {
1819        it.fold(Self::new(), |a, b| a + b)
1820    }
1821}
1822
1823impl<A: Clone, P: SharedPointerKind> Add for GenericVector<A, P> {
1824    type Output = GenericVector<A, P>;
1825
1826    /// Concatenate two vectors.
1827    ///
1828    /// Time: O(log n)
1829    fn add(mut self, other: Self) -> Self::Output {
1830        self.append(other);
1831        self
1832    }
1833}
1834
1835impl<A: Clone, P: SharedPointerKind> Add for &GenericVector<A, P> {
1836    type Output = GenericVector<A, P>;
1837
1838    /// Concatenate two vectors.
1839    ///
1840    /// Time: O(log n)
1841    fn add(self, other: Self) -> Self::Output {
1842        let mut out = self.clone();
1843        out.append(other.clone());
1844        out
1845    }
1846}
1847
1848impl<A: Clone, P: SharedPointerKind> Extend<A> for GenericVector<A, P> {
1849    /// Add values to the end of a vector by consuming an iterator.
1850    ///
1851    /// Time: O(n)
1852    fn extend<I>(&mut self, iter: I)
1853    where
1854        I: IntoIterator<Item = A>,
1855    {
1856        for item in iter {
1857            self.push_back(item)
1858        }
1859    }
1860}
1861
1862impl<A, P: SharedPointerKind> Index<usize> for GenericVector<A, P> {
1863    type Output = A;
1864    /// Get a reference to the value at index `index` in the vector.
1865    ///
1866    /// Time: O(log n)
1867    fn index(&self, index: usize) -> &Self::Output {
1868        match self.get(index) {
1869            Some(value) => value,
1870            None => panic!(
1871                "Vector::index: index out of bounds: {} < {}",
1872                index,
1873                self.len()
1874            ),
1875        }
1876    }
1877}
1878
1879impl<A: Clone, P: SharedPointerKind> IndexMut<usize> for GenericVector<A, P> {
1880    /// Get a mutable reference to the value at index `index` in the
1881    /// vector.
1882    ///
1883    /// Time: O(log n)
1884    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
1885        match self.get_mut(index) {
1886            Some(value) => value,
1887            None => panic!("Vector::index_mut: index out of bounds"),
1888        }
1889    }
1890}
1891
1892// Conversions
1893
1894impl<'a, A, P: SharedPointerKind> IntoIterator for &'a GenericVector<A, P> {
1895    type Item = &'a A;
1896    type IntoIter = Iter<'a, A, P>;
1897    fn into_iter(self) -> Self::IntoIter {
1898        self.iter()
1899    }
1900}
1901
1902impl<'a, A: Clone, P: SharedPointerKind> IntoIterator for &'a mut GenericVector<A, P> {
1903    type Item = &'a mut A;
1904    type IntoIter = IterMut<'a, A, P>;
1905    fn into_iter(self) -> Self::IntoIter {
1906        self.iter_mut()
1907    }
1908}
1909
1910impl<A: Clone, P: SharedPointerKind> IntoIterator for GenericVector<A, P> {
1911    type Item = A;
1912    type IntoIter = ConsumingIter<A, P>;
1913    fn into_iter(self) -> Self::IntoIter {
1914        ConsumingIter::new(self)
1915    }
1916}
1917
1918impl<A: Clone, P: SharedPointerKind> FromIterator<A> for GenericVector<A, P> {
1919    /// Create a vector from an iterator.
1920    ///
1921    /// Time: O(n)
1922    fn from_iter<I>(iter: I) -> Self
1923    where
1924        I: IntoIterator<Item = A>,
1925    {
1926        let mut seq = Self::new();
1927        for item in iter {
1928            seq.push_back(item)
1929        }
1930        seq
1931    }
1932}
1933
1934impl<A, OA, P1, P2> From<&GenericVector<&A, P2>> for GenericVector<OA, P1>
1935where
1936    A: ToOwned<Owned = OA>,
1937    OA: Borrow<A> + Clone,
1938    P1: SharedPointerKind,
1939    P2: SharedPointerKind,
1940{
1941    fn from(vec: &GenericVector<&A, P2>) -> Self {
1942        vec.iter().map(|a| (*a).to_owned()).collect()
1943    }
1944}
1945
1946impl<A, const N: usize, P: SharedPointerKind> From<[A; N]> for GenericVector<A, P>
1947where
1948    A: Clone,
1949{
1950    fn from(arr: [A; N]) -> Self {
1951        IntoIterator::into_iter(arr).collect()
1952    }
1953}
1954
1955impl<A: Clone, P: SharedPointerKind> From<&[A]> for GenericVector<A, P> {
1956    fn from(slice: &[A]) -> Self {
1957        slice.iter().cloned().collect()
1958    }
1959}
1960
1961impl<A: Clone, P: SharedPointerKind> From<Vec<A>> for GenericVector<A, P> {
1962    /// Create a vector from a [`std::vec::Vec`][vec].
1963    ///
1964    /// Time: O(n)
1965    ///
1966    /// [vec]: https://doc.rust-lang.org/std/vec/struct.Vec.html
1967    fn from(vec: Vec<A>) -> Self {
1968        vec.into_iter().collect()
1969    }
1970}
1971
1972impl<A: Clone, P: SharedPointerKind> From<&Vec<A>> for GenericVector<A, P> {
1973    /// Create a vector from a [`std::vec::Vec`][vec].
1974    ///
1975    /// Time: O(n)
1976    ///
1977    /// [vec]: https://doc.rust-lang.org/std/vec/struct.Vec.html
1978    fn from(vec: &Vec<A>) -> Self {
1979        vec.iter().cloned().collect()
1980    }
1981}
1982
1983// Iterators
1984
1985/// An iterator over vectors with values of type `A`.
1986///
1987/// To obtain one, use [`Vector::iter()`][iter].
1988///
1989/// [iter]: type.Vector.html#method.iter
1990// TODO: we'd like to support Clone even if A is not Clone, but it isn't trivial because
1991// the TreeFocus variant of Focus does need A to be Clone.
1992pub struct Iter<'a, A, P: SharedPointerKind> {
1993    focus: Focus<'a, A, P>,
1994    front_index: usize,
1995    back_index: usize,
1996}
1997
1998impl<'a, A, P: SharedPointerKind> Iter<'a, A, P> {
1999    fn new(seq: &'a GenericVector<A, P>) -> Self {
2000        Iter {
2001            focus: seq.focus(),
2002            front_index: 0,
2003            back_index: seq.len(),
2004        }
2005    }
2006
2007    fn from_focus(focus: Focus<'a, A, P>) -> Self {
2008        Iter {
2009            front_index: 0,
2010            back_index: focus.len(),
2011            focus,
2012        }
2013    }
2014}
2015
2016impl<A: Clone, P: SharedPointerKind> Clone for Iter<'_, A, P> {
2017    fn clone(&self) -> Self {
2018        Iter {
2019            focus: self.focus.clone(),
2020            front_index: self.front_index,
2021            back_index: self.back_index,
2022        }
2023    }
2024}
2025
2026impl<'a, A, P: SharedPointerKind + 'a> Iterator for Iter<'a, A, P> {
2027    type Item = &'a A;
2028
2029    /// Advance the iterator and return the next value.
2030    ///
2031    /// Time: O(1)*
2032    fn next(&mut self) -> Option<Self::Item> {
2033        if self.front_index >= self.back_index {
2034            return None;
2035        }
2036        let value = self.focus.get(self.front_index);
2037        self.front_index += 1;
2038        // Safety:
2039        // We ensure that everything reachable from a `Focus<'a, ..>` is valid
2040        // for `'a`. The trickier part is the `TreeFocus` branch, and here
2041        // are two ways we can construct a `TreeFocus`:
2042        // - through a reference `&'a RRB`. In this case, the actual tree that
2043        //   we store is a reference-counted copy of the `&'a RBB`, and so the
2044        //   data underlying our tree is valid for `'a`. If this were the only
2045        //   way to construct a `TreeFocus`, we'd just have `TreeFocus::tree` be a
2046        //   `&'a RRB`. Alas.
2047        // - from a `TreeFocusMut<'a, ..>`, which owns what is essentially a
2048        //   `Mutex<&'a mut Rc<Node>>`. Importantly, `TreeFocusMut` doesn't
2049        //   expose any methods to modify the tree *structure*, so we know
2050        //   that all the tree nodes are valid for `'a`. And because of our
2051        //   disjointness checks when splitting a `TreeFocusMut`, we won't take
2052        //   a reference to any of the elements that might be modified by the
2053        //   `TreeFocusMut`.
2054        //
2055        // This is all a bit complicated and it would be nice to push these
2056        // assertions down to the focus module. For example, I think we can
2057        // change `Focus<'a, A>::get` to return `&'a A`. Unfortunately, this
2058        // doesn't completely solve our problems in this module, because we
2059        // can't do the same for mutable references (for which we'd need to
2060        // guarantee that you can't as the focus for the same mutable reference
2061        // twice; true for iterators, but not in general).
2062        unsafe { extend_lifetime(value) }
2063    }
2064
2065    fn size_hint(&self) -> (usize, Option<usize>) {
2066        let remaining = self.back_index - self.front_index;
2067        (remaining, Some(remaining))
2068    }
2069}
2070
2071impl<'a, A, P: SharedPointerKind + 'a> DoubleEndedIterator for Iter<'a, A, P> {
2072    /// Advance the iterator and return the next value.
2073    ///
2074    /// Time: O(1)*
2075    fn next_back(&mut self) -> Option<Self::Item> {
2076        if self.front_index >= self.back_index {
2077            return None;
2078        }
2079        self.back_index -= 1;
2080        let value = self.focus.get(self.back_index);
2081        unsafe { extend_lifetime(value) }
2082    }
2083}
2084
2085impl<'a, A, P: SharedPointerKind + 'a> ExactSizeIterator for Iter<'a, A, P> {}
2086
2087impl<'a, A, P: SharedPointerKind + 'a> FusedIterator for Iter<'a, A, P> {}
2088
2089/// A mutable iterator over vectors with values of type `A`.
2090///
2091/// To obtain one, use [`Vector::iter_mut()`][iter_mut].
2092///
2093/// [iter_mut]: type.Vector.html#method.iter_mut
2094pub struct IterMut<'a, A, P: SharedPointerKind> {
2095    focus: FocusMut<'a, A, P>,
2096    front_index: usize,
2097    back_index: usize,
2098}
2099
2100impl<'a, A, P: SharedPointerKind> IterMut<'a, A, P> {
2101    fn from_focus(focus: FocusMut<'a, A, P>) -> Self {
2102        IterMut {
2103            front_index: 0,
2104            back_index: focus.len(),
2105            focus,
2106        }
2107    }
2108}
2109
2110impl<'a, A: Clone, P: SharedPointerKind> IterMut<'a, A, P> {
2111    fn new(seq: &'a mut GenericVector<A, P>) -> Self {
2112        let focus = seq.focus_mut();
2113        let len = focus.len();
2114        IterMut {
2115            focus,
2116            front_index: 0,
2117            back_index: len,
2118        }
2119    }
2120}
2121
2122impl<'a, A, P: SharedPointerKind> Iterator for IterMut<'a, A, P>
2123where
2124    A: 'a + Clone,
2125{
2126    type Item = &'a mut A;
2127
2128    /// Advance the iterator and return the next value.
2129    ///
2130    /// Time: O(1)*
2131    fn next(&mut self) -> Option<Self::Item> {
2132        if self.front_index >= self.back_index {
2133            return None;
2134        }
2135        let value = self.focus.get_mut(self.front_index);
2136        self.front_index += 1;
2137        unsafe { extend_lifetime_mut(value) }
2138    }
2139
2140    fn size_hint(&self) -> (usize, Option<usize>) {
2141        let remaining = self.back_index - self.front_index;
2142        (remaining, Some(remaining))
2143    }
2144}
2145
2146impl<'a, A, P: SharedPointerKind> DoubleEndedIterator for IterMut<'a, A, P>
2147where
2148    A: 'a + Clone,
2149{
2150    /// Remove and return an element from the back of the iterator.
2151    ///
2152    /// Time: O(1)*
2153    fn next_back(&mut self) -> Option<Self::Item> {
2154        if self.front_index >= self.back_index {
2155            return None;
2156        }
2157        self.back_index -= 1;
2158        let value = self.focus.get_mut(self.back_index);
2159        unsafe { extend_lifetime_mut(value) }
2160    }
2161}
2162
2163impl<'a, A: Clone, P: SharedPointerKind> ExactSizeIterator for IterMut<'a, A, P> {}
2164
2165impl<'a, A: Clone, P: SharedPointerKind> FusedIterator for IterMut<'a, A, P> {}
2166
2167/// A consuming iterator over vectors with values of type `A`.
2168pub struct ConsumingIter<A, P: SharedPointerKind> {
2169    vector: GenericVector<A, P>,
2170}
2171
2172impl<A: Clone, P: SharedPointerKind> Clone for ConsumingIter<A, P> {
2173    fn clone(&self) -> Self {
2174        Self {
2175            vector: self.vector.clone(),
2176        }
2177    }
2178}
2179
2180impl<A, P: SharedPointerKind> ConsumingIter<A, P> {
2181    fn new(vector: GenericVector<A, P>) -> Self {
2182        Self { vector }
2183    }
2184}
2185
2186impl<A: Clone, P: SharedPointerKind> Iterator for ConsumingIter<A, P> {
2187    type Item = A;
2188
2189    /// Advance the iterator and return the next value.
2190    ///
2191    /// Time: O(1)*
2192    fn next(&mut self) -> Option<Self::Item> {
2193        self.vector.pop_front()
2194    }
2195
2196    fn size_hint(&self) -> (usize, Option<usize>) {
2197        let len = self.vector.len();
2198        (len, Some(len))
2199    }
2200}
2201
2202impl<A: Clone, P: SharedPointerKind> DoubleEndedIterator for ConsumingIter<A, P> {
2203    /// Remove and return an element from the back of the iterator.
2204    ///
2205    /// Time: O(1)*
2206    fn next_back(&mut self) -> Option<Self::Item> {
2207        self.vector.pop_back()
2208    }
2209}
2210
2211impl<A: Clone, P: SharedPointerKind> ExactSizeIterator for ConsumingIter<A, P> {}
2212
2213impl<A: Clone, P: SharedPointerKind> FusedIterator for ConsumingIter<A, P> {}
2214
2215/// An iterator over the leaf nodes of a vector.
2216///
2217/// To obtain one, use [`Vector::chunks()`][chunks].
2218///
2219/// [chunks]: type.Vector.html#method.chunks
2220pub struct Chunks<'a, A, P: SharedPointerKind> {
2221    focus: Focus<'a, A, P>,
2222    front_index: usize,
2223    back_index: usize,
2224}
2225
2226impl<'a, A, P: SharedPointerKind> Chunks<'a, A, P> {
2227    fn new(seq: &'a GenericVector<A, P>) -> Self {
2228        Chunks {
2229            focus: seq.focus(),
2230            front_index: 0,
2231            back_index: seq.len(),
2232        }
2233    }
2234}
2235
2236impl<'a, A, P: SharedPointerKind + 'a> Iterator for Chunks<'a, A, P> {
2237    type Item = &'a [A];
2238
2239    /// Advance the iterator and return the next value.
2240    ///
2241    /// Time: O(1)*
2242    fn next(&mut self) -> Option<Self::Item> {
2243        if self.front_index >= self.back_index {
2244            return None;
2245        }
2246        let (range, value) = self.focus.chunk_at(self.front_index);
2247        self.front_index = range.end;
2248        unsafe { extend_lifetime(Some(value)) }
2249    }
2250}
2251
2252impl<'a, A, P: SharedPointerKind + 'a> DoubleEndedIterator for Chunks<'a, A, P> {
2253    /// Remove and return an element from the back of the iterator.
2254    ///
2255    /// Time: O(1)*
2256    fn next_back(&mut self) -> Option<Self::Item> {
2257        if self.front_index >= self.back_index {
2258            return None;
2259        }
2260        self.back_index -= 1;
2261        let (range, value) = self.focus.chunk_at(self.back_index);
2262        self.back_index = range.start;
2263        unsafe { extend_lifetime(Some(value)) }
2264    }
2265}
2266
2267impl<'a, A, P: SharedPointerKind + 'a> FusedIterator for Chunks<'a, A, P> {}
2268
2269/// A mutable iterator over the leaf nodes of a vector.
2270///
2271/// To obtain one, use [`Vector::chunks_mut()`][chunks_mut].
2272///
2273/// [chunks_mut]: type.Vector.html#method.chunks_mut
2274pub struct ChunksMut<'a, A, P: SharedPointerKind> {
2275    focus: FocusMut<'a, A, P>,
2276    front_index: usize,
2277    back_index: usize,
2278}
2279
2280impl<'a, A: Clone, P: SharedPointerKind> ChunksMut<'a, A, P> {
2281    fn new(seq: &'a mut GenericVector<A, P>) -> Self {
2282        let len = seq.len();
2283        ChunksMut {
2284            focus: seq.focus_mut(),
2285            front_index: 0,
2286            back_index: len,
2287        }
2288    }
2289}
2290
2291impl<'a, A: Clone, P: SharedPointerKind> Iterator for ChunksMut<'a, A, P> {
2292    type Item = &'a mut [A];
2293
2294    /// Advance the iterator and return the next value.
2295    ///
2296    /// Time: O(1)*
2297    fn next(&mut self) -> Option<Self::Item> {
2298        if self.front_index >= self.back_index {
2299            return None;
2300        }
2301        let (range, value) = self.focus.chunk_at(self.front_index);
2302        self.front_index = range.end;
2303        unsafe { extend_lifetime_mut(Some(value)) }
2304    }
2305}
2306
2307impl<'a, A: Clone, P: SharedPointerKind> DoubleEndedIterator for ChunksMut<'a, A, P> {
2308    /// Remove and return an element from the back of the iterator.
2309    ///
2310    /// Time: O(1)*
2311    fn next_back(&mut self) -> Option<Self::Item> {
2312        if self.front_index >= self.back_index {
2313            return None;
2314        }
2315        self.back_index -= 1;
2316        let (range, value) = self.focus.chunk_at(self.back_index);
2317        self.back_index = range.start;
2318        unsafe { extend_lifetime_mut(Some(value)) }
2319    }
2320}
2321
2322impl<'a, A: Clone, P: SharedPointerKind> FusedIterator for ChunksMut<'a, A, P> {}
2323
2324// Proptest
2325#[cfg(any(test, feature = "proptest"))]
2326#[doc(hidden)]
2327pub mod proptest {
2328    #[deprecated(
2329        since = "14.3.0",
2330        note = "proptest strategies have moved to imbl::proptest"
2331    )]
2332    pub use crate::proptest::vector;
2333}
2334
2335unsafe fn extend_lifetime<'a, T: ?Sized>(x: Option<&T>) -> Option<&'a T> {
2336    std::mem::transmute(x)
2337}
2338
2339unsafe fn extend_lifetime_mut<'a, T: ?Sized>(x: Option<&mut T>) -> Option<&'a mut T> {
2340    std::mem::transmute(x)
2341}
2342
2343// Tests
2344
2345#[cfg(test)]
2346mod test {
2347    use super::*;
2348    use crate::proptest::vector;
2349    use ::proptest::collection::vec;
2350    use ::proptest::num::{i32, usize};
2351    use ::proptest::proptest;
2352    use static_assertions::{assert_impl_all, assert_not_impl_any};
2353
2354    assert_impl_all!(Vector<i32>: Send, Sync);
2355    assert_not_impl_any!(Vector<*const i32>: Send, Sync);
2356    assert_covariant!(Vector<T> in T);
2357
2358    #[test]
2359    fn macro_allows_trailing_comma() {
2360        let vec1 = vector![1, 2, 3];
2361        let vec2 = vector![1, 2, 3,];
2362        assert_eq!(vec1, vec2);
2363    }
2364
2365    #[test]
2366    fn indexing() {
2367        let mut vec: Vector<_> = vector![0, 1, 2, 3, 4, 5];
2368        vec.push_front(0);
2369        assert_eq!(0, *vec.get(0).unwrap());
2370        assert_eq!(0, vec[0]);
2371    }
2372
2373    #[test]
2374    fn test_vector_focus_split_at() {
2375        for (data, split_points) in [
2376            (0..0, vec![0]),
2377            (0..3, vec![0, 1, 2, 3]),
2378            (0..128, vec![0, 1, 64, 127, 128]),
2379            #[cfg(not(miri))]
2380            (0..100_000, vec![0, 1, 50_000, 99_999, 100_000]),
2381        ] {
2382            let imbl_vec = Vector::from_iter(data.clone());
2383            let vec = Vec::from_iter(data);
2384            let focus = imbl_vec.focus();
2385            for split_point in split_points {
2386                let (left, right) = focus.clone().split_at(split_point);
2387                let (expected_left, expected_right) = vec.split_at(split_point);
2388                assert_eq!(
2389                    left.clone().into_iter().copied().collect::<Vec<_>>(),
2390                    expected_left
2391                );
2392                assert_eq!(
2393                    right.clone().into_iter().copied().collect::<Vec<_>>(),
2394                    expected_right
2395                );
2396            }
2397        }
2398    }
2399
2400    #[test]
2401    #[should_panic(expected = "range out of bounds")]
2402    fn test_vector_focus_narrow_out_of_range() {
2403        let vec = Vector::from_iter(0..100);
2404        _ = vec.focus().narrow(..1000);
2405    }
2406
2407    #[test]
2408    fn test_vector_focus_narrow() {
2409        macro_rules! testcase {
2410            ($data:expr, $range:expr) => {{
2411                let imbl_vector = Vector::<_>::from_iter($data);
2412                let vec = Vec::from_iter($data);
2413                let focus = imbl_vector.focus();
2414                assert_eq!(
2415                    focus
2416                        .narrow($range)
2417                        .into_iter()
2418                        .copied()
2419                        .collect::<Vec<_>>(),
2420                    vec[$range]
2421                );
2422            }};
2423        }
2424        // exhaustively test small cases
2425        for len in 0..=3 {
2426            testcase!(0..len, ..);
2427            for start in 0..=len {
2428                testcase!(0..len, start..);
2429                testcase!(0..len, ..start);
2430                for end in start..=len {
2431                    testcase!(0..len, start..end);
2432                }
2433            }
2434        }
2435    }
2436
2437    #[cfg_attr(miri, ignore)]
2438    #[test]
2439    fn large_vector_focus() {
2440        let input = Vector::from_iter(0..100_000);
2441        let vec = input.clone();
2442        let mut sum: i64 = 0;
2443        let mut focus = vec.focus();
2444        for i in 0..input.len() {
2445            sum += *focus.index(i);
2446        }
2447        let expected: i64 = (0..100_000).sum();
2448        assert_eq!(expected, sum);
2449    }
2450
2451    #[cfg_attr(miri, ignore)]
2452    #[test]
2453    fn large_vector_focus_mut() {
2454        let input = Vector::from_iter(0..100_000);
2455        let mut vec = input.clone();
2456        {
2457            let mut focus = vec.focus_mut();
2458            for i in 0..input.len() {
2459                let p = focus.index_mut(i);
2460                *p += 1;
2461            }
2462        }
2463        let expected: Vector<_> = input.into_iter().map(|i| i + 1).collect();
2464        assert_eq!(expected, vec);
2465    }
2466
2467    #[cfg_attr(miri, ignore)]
2468    #[test]
2469    fn issue_55_fwd() {
2470        let mut l = Vector::new();
2471        for i in 0..4098 {
2472            l.append(GenericVector::unit(i));
2473        }
2474        l.append(GenericVector::unit(4098));
2475        assert_eq!(Some(&4097), l.get(4097));
2476        assert_eq!(Some(&4096), l.get(4096));
2477    }
2478
2479    #[cfg_attr(miri, ignore)]
2480    #[test]
2481    fn issue_55_back() {
2482        let mut l = Vector::unit(0);
2483        for i in 0..4099 {
2484            let mut tmp = GenericVector::unit(i + 1);
2485            tmp.append(l);
2486            l = tmp;
2487        }
2488        assert_eq!(Some(&4098), l.get(1));
2489        assert_eq!(Some(&4097), l.get(2));
2490        let len = l.len();
2491        let _ = l.slice(2..len);
2492    }
2493
2494    #[test]
2495    fn issue_55_append() {
2496        let mut vec1 = Vector::from_iter(0..92);
2497        let vec2 = GenericVector::from_iter(0..165);
2498        vec1.append(vec2);
2499    }
2500
2501    #[test]
2502    fn issue_70() {
2503        // This test assumes that chunks are of size 64.
2504        if CHUNK_SIZE != 64 {
2505            return;
2506        }
2507        let mut x = Vector::new();
2508        for _ in 0..262 {
2509            x.push_back(0);
2510        }
2511        for _ in 0..97 {
2512            x.pop_front();
2513        }
2514        for &offset in &[160, 163, 160] {
2515            x.remove(offset);
2516        }
2517        for _ in 0..64 {
2518            x.push_back(0);
2519        }
2520        // At this point middle contains three chunks of size 64, 64 and 1
2521        // respectively. Previously the next `push_back()` would append another
2522        // zero-sized chunk to middle even though there is enough space left.
2523        match x.vector {
2524            VectorInner::Full(ref tree) => {
2525                assert_eq!(129, tree.middle.len());
2526                assert_eq!(3, tree.middle.number_of_children());
2527            }
2528            _ => unreachable!(),
2529        }
2530        x.push_back(0);
2531        match x.vector {
2532            VectorInner::Full(ref tree) => {
2533                assert_eq!(131, tree.middle.len());
2534                assert_eq!(3, tree.middle.number_of_children())
2535            }
2536            _ => unreachable!(),
2537        }
2538        for _ in 0..64 {
2539            x.push_back(0);
2540        }
2541        for _ in x.iter() {}
2542    }
2543
2544    #[cfg_attr(miri, ignore)]
2545    #[test]
2546    fn issue_67() {
2547        let mut l = Vector::unit(4100);
2548        for i in (0..4099).rev() {
2549            let mut tmp = GenericVector::unit(i);
2550            tmp.append(l);
2551            l = tmp;
2552        }
2553        assert_eq!(4100, l.len());
2554        let len = l.len();
2555        let tail = l.slice(1..len);
2556        assert_eq!(1, l.len());
2557        assert_eq!(4099, tail.len());
2558        assert_eq!(Some(&0), l.get(0));
2559        assert_eq!(Some(&1), tail.get(0));
2560    }
2561
2562    #[test]
2563    fn issue_74_simple_size() {
2564        use crate::nodes::rrb::NODE_SIZE;
2565        let mut x = Vector::new();
2566        for _ in 0..(CHUNK_SIZE
2567            * (
2568                1 // inner_f
2569                + (2 * NODE_SIZE) // middle: two full Entry::Nodes (4096 elements each)
2570                + 1 // inner_b
2571                + 1
2572                // outer_b
2573            ))
2574        {
2575            x.push_back(0u32);
2576        }
2577        let middle_first_node_start = CHUNK_SIZE;
2578        let middle_second_node_start = middle_first_node_start + NODE_SIZE * CHUNK_SIZE;
2579        // This reduces the size of the second node to 4095.
2580        x.remove(middle_second_node_start);
2581        // As outer_b is full, this will cause inner_b (length 64) to be pushed
2582        // to middle. The first element will be merged into the second node, the
2583        // remaining 63 elements will end up in a new node.
2584        x.push_back(0u32);
2585        match x.vector {
2586            VectorInner::Full(tree) => {
2587                if CHUNK_SIZE == 64 {
2588                    assert_eq!(3, tree.middle.number_of_children());
2589                }
2590                assert_eq!(
2591                    2 * NODE_SIZE * CHUNK_SIZE + CHUNK_SIZE - 1,
2592                    tree.middle.len()
2593                );
2594            }
2595            _ => unreachable!(),
2596        }
2597    }
2598
2599    #[test]
2600    fn issue_77() {
2601        let mut x = Vector::new();
2602        for _ in 0..44 {
2603            x.push_back(0);
2604        }
2605        for _ in 0..20 {
2606            x.insert(0, 0);
2607        }
2608        x.insert(1, 0);
2609        for _ in 0..441 {
2610            x.push_back(0);
2611        }
2612        for _ in 0..58 {
2613            x.insert(0, 0);
2614        }
2615        x.insert(514, 0);
2616        for _ in 0..73 {
2617            x.push_back(0);
2618        }
2619        for _ in 0..10 {
2620            x.insert(0, 0);
2621        }
2622        x.insert(514, 0);
2623    }
2624
2625    #[cfg_attr(miri, ignore)]
2626    #[test]
2627    fn issue_105() {
2628        let mut v = Vector::<_>::new();
2629
2630        for i in 0..270_000 {
2631            v.push_front(i);
2632        }
2633
2634        while !v.is_empty() {
2635            v = v.take(v.len() - 1);
2636        }
2637    }
2638
2639    #[cfg_attr(miri, ignore)]
2640    #[test]
2641    fn issue_107_split_off_causes_overflow() {
2642        let mut vec = Vector::from_iter(0..4289);
2643        let mut control = Vec::from_iter(0..4289);
2644        let chunk = 64;
2645
2646        while vec.len() >= chunk {
2647            vec = vec.split_off(chunk);
2648            control = control.split_off(chunk);
2649            assert_eq!(vec.len(), control.len());
2650            assert_eq!(control, vec.iter().cloned().collect::<Vec<_>>());
2651        }
2652    }
2653
2654    #[cfg_attr(miri, ignore)]
2655    #[test]
2656    fn collect_crash() {
2657        let _vector: Vector<i32> = (0..5953).collect();
2658        // let _vector: Vector<i32> = (0..16384).collect();
2659    }
2660
2661    #[test]
2662    fn issue_116() {
2663        let vec = Vector::from_iter(0..300);
2664        let rev_vec: Vector<_> = vec.clone().into_iter().rev().collect();
2665        assert_eq!(vec.len(), rev_vec.len());
2666    }
2667
2668    #[test]
2669    fn issue_131() {
2670        let smol = std::iter::repeat_n(42, 64).collect::<Vector<_>>();
2671        let mut smol2 = smol.clone();
2672        assert!(smol.ptr_eq(&smol2));
2673        smol2.set(63, 420);
2674        assert!(!smol.ptr_eq(&smol2));
2675
2676        let huge = std::iter::repeat_n(42, 65).collect::<Vector<_>>();
2677        let mut huge2 = huge.clone();
2678        assert!(huge.ptr_eq(&huge2));
2679        huge2.set(63, 420);
2680        assert!(!huge.ptr_eq(&huge2));
2681    }
2682
2683    #[test]
2684    fn ptr_eq() {
2685        const MAX: usize = if cfg!(miri) { 64 } else { 256 };
2686        for len in 32..MAX {
2687            let input = std::iter::repeat_n(42, len).collect::<Vector<_>>();
2688            let mut inp2 = input.clone();
2689            assert!(input.ptr_eq(&inp2));
2690            inp2.set(len - 1, 98);
2691            assert_ne!(inp2.get(len - 1), input.get(len - 1));
2692            assert!(!input.ptr_eq(&inp2));
2693        }
2694    }
2695
2696    #[test]
2697    fn full_retain() {
2698        let mut a = Vector::from_iter(0..128);
2699        let b = Vector::from_iter(128..256);
2700        a.append(b);
2701        assert!(matches!(a.vector, Full(_)));
2702        a.retain(|i| *i % 2 == 0);
2703        assert_eq!(a.len(), 128);
2704    }
2705
2706    proptest! {
2707        // Miri is slow, so we ignore long-ish tests to keep the test
2708        // time manageable. For some property tests, it may be worthwhile
2709        // enabling them in miri with reduced iteration counts.
2710        #[cfg_attr(miri, ignore)]
2711        #[test]
2712        fn iter(ref vec in vec(i32::ANY, 0..1000)) {
2713            let seq = Vector::from_iter(vec.iter().cloned());
2714            for (index, item) in seq.iter().enumerate() {
2715                assert_eq!(&vec[index], item);
2716            }
2717            assert_eq!(vec.len(), seq.len());
2718        }
2719
2720        #[cfg_attr(miri, ignore)]
2721        #[test]
2722        fn push_front_mut(ref input in vec(i32::ANY, 0..1000)) {
2723            let mut vector = Vector::new();
2724            for (count, value) in input.iter().cloned().enumerate() {
2725                assert_eq!(count, vector.len());
2726                vector.push_front(value);
2727                assert_eq!(count + 1, vector.len());
2728            }
2729            let input2 = Vec::from_iter(input.iter().rev().cloned());
2730            assert_eq!(input2, Vec::from_iter(vector.iter().cloned()));
2731        }
2732
2733        #[cfg_attr(miri, ignore)]
2734        #[test]
2735        fn push_back_mut(ref input in vec(i32::ANY, 0..1000)) {
2736            let mut vector = Vector::new();
2737            for (count, value) in input.iter().cloned().enumerate() {
2738                assert_eq!(count, vector.len());
2739                vector.push_back(value);
2740                assert_eq!(count + 1, vector.len());
2741            }
2742            assert_eq!(input, &Vec::from_iter(vector.iter().cloned()));
2743        }
2744
2745        #[cfg_attr(miri, ignore)]
2746        #[test]
2747        fn pop_back_mut(ref input in vec(i32::ANY, 0..1000)) {
2748            let mut vector = Vector::from_iter(input.iter().cloned());
2749            assert_eq!(input.len(), vector.len());
2750            for (index, value) in input.iter().cloned().enumerate().rev() {
2751                match vector.pop_back() {
2752                    None => panic!("vector emptied unexpectedly"),
2753                    Some(item) => {
2754                        assert_eq!(index, vector.len());
2755                        assert_eq!(value, item);
2756                    }
2757                }
2758            }
2759            assert_eq!(0, vector.len());
2760        }
2761
2762        #[cfg_attr(miri, ignore)]
2763        #[test]
2764        fn pop_front_mut(ref input in vec(i32::ANY, 0..1000)) {
2765            let mut vector = Vector::from_iter(input.iter().cloned());
2766            assert_eq!(input.len(), vector.len());
2767            for (index, value) in input.iter().cloned().rev().enumerate().rev() {
2768                match vector.pop_front() {
2769                    None => panic!("vector emptied unexpectedly"),
2770                    Some(item) => {
2771                        assert_eq!(index, vector.len());
2772                        assert_eq!(value, item);
2773                    }
2774                }
2775            }
2776            assert_eq!(0, vector.len());
2777        }
2778
2779        // #[test]
2780        // fn push_and_pop(ref input in vec(i32::ANY, 0..1000)) {
2781        //     let mut vector = Vector::new();
2782        //     for (count, value) in input.iter().cloned().enumerate() {
2783        //         assert_eq!(count, vector.len());
2784        //         vector.push_back(value);
2785        //         assert_eq!(count + 1, vector.len());
2786        //     }
2787        //     for (index, value) in input.iter().cloned().rev().enumerate().rev() {
2788        //         match vector.pop_front() {
2789        //             None => panic!("vector emptied unexpectedly"),
2790        //             Some(item) => {
2791        //                 assert_eq!(index, vector.len());
2792        //                 assert_eq!(value, item);
2793        //             }
2794        //         }
2795        //     }
2796        //     assert_eq!(true, vector.is_empty());
2797        // }
2798
2799        #[cfg_attr(miri, ignore)]
2800        #[test]
2801        fn skip(ref vec in vec(i32::ANY, 1..2000), count in usize::ANY) {
2802            let count = count % (vec.len() + 1);
2803            let old = Vector::from_iter(vec.iter().cloned());
2804            let new = old.skip(count);
2805            assert_eq!(old.len(), vec.len());
2806            assert_eq!(new.len(), vec.len() - count);
2807            for (index, item) in old.iter().enumerate() {
2808                assert_eq!(& vec[index], item);
2809            }
2810            for (index, item) in new.iter().enumerate() {
2811                assert_eq!(&vec[count + index], item);
2812            }
2813        }
2814
2815        #[cfg_attr(miri, ignore)]
2816        #[test]
2817        fn split_off(ref vec in vec(i32::ANY, 1..2000), split_pos in usize::ANY) {
2818            let split_index = split_pos % (vec.len() + 1);
2819            let mut left = Vector::from_iter(vec.iter().cloned());
2820            let right = left.split_off(split_index);
2821            assert_eq!(left.len(), split_index);
2822            assert_eq!(right.len(), vec.len() - split_index);
2823            for (index, item) in left.iter().enumerate() {
2824                assert_eq!(& vec[index], item);
2825            }
2826            for (index, item) in right.iter().enumerate() {
2827                assert_eq!(&vec[split_index + index], item);
2828            }
2829        }
2830
2831        #[cfg_attr(miri, ignore)]
2832        #[test]
2833        fn append(ref vec1 in vec(i32::ANY, 0..1000), ref vec2 in vec(i32::ANY, 0..1000)) {
2834            let mut seq1 = Vector::from_iter(vec1.iter().cloned());
2835            let seq2 = Vector::from_iter(vec2.iter().cloned());
2836            assert_eq!(seq1.len(), vec1.len());
2837            assert_eq!(seq2.len(), vec2.len());
2838            seq1.append(seq2);
2839            let mut vec = vec1.clone();
2840            vec.extend(vec2);
2841            assert_eq!(seq1.len(), vec.len());
2842            for (index, item) in seq1.into_iter().enumerate() {
2843                assert_eq!(vec[index], item);
2844            }
2845        }
2846
2847        #[cfg_attr(miri, ignore)]
2848        #[test]
2849        fn iter_mut(ref input in vector(i32::ANY, 0..10000)) {
2850            let mut vec = input.clone();
2851            {
2852                for p in vec.iter_mut() {
2853                    *p = p.overflowing_add(1).0;
2854                }
2855            }
2856            let expected: Vector<i32> = input.clone().into_iter().map(|i| i.overflowing_add(1).0).collect();
2857            assert_eq!(expected, vec);
2858        }
2859
2860        #[cfg_attr(miri, ignore)]
2861        #[test]
2862        fn focus(ref input in vector(i32::ANY, 0..10000)) {
2863            let mut vec = input.clone();
2864            {
2865                let mut focus = vec.focus_mut();
2866                for i in 0..input.len() {
2867                    let p = focus.index_mut(i);
2868                    *p = p.overflowing_add(1).0;
2869                }
2870            }
2871            let expected: Vector<i32> = input.clone().into_iter().map(|i| i.overflowing_add(1).0).collect();
2872            assert_eq!(expected, vec);
2873        }
2874
2875        #[cfg_attr(miri, ignore)]
2876        #[test]
2877        fn focus_mut_split(ref input in vector(i32::ANY, 0..10000)) {
2878            let mut vec = input.clone();
2879
2880            fn split_down(focus: FocusMut<'_, i32, DefaultSharedPtr>) {
2881                let len = focus.len();
2882                if len < 8 {
2883                    for p in focus {
2884                        *p = p.overflowing_add(1).0;
2885                    }
2886                } else {
2887                    let (left, right) = focus.split_at(len / 2);
2888                    split_down(left);
2889                    split_down(right);
2890                }
2891            }
2892
2893            split_down(vec.focus_mut());
2894
2895            let expected: Vector<_> = input.clone().into_iter().map(|i| i.overflowing_add(1).0).collect();
2896            assert_eq!(expected, vec);
2897        }
2898
2899        #[cfg_attr(miri, ignore)]
2900        #[test]
2901        fn chunks(ref input in vector(i32::ANY, 0..10000)) {
2902            let output: Vector<_> = input.leaves().flatten().cloned().collect();
2903            assert_eq!(input, &output);
2904            let rev_in: Vector<_> = input.iter().rev().cloned().collect();
2905            let rev_out: Vector<_> = input.leaves().rev().flat_map(|c| c.iter().rev()).cloned().collect();
2906            assert_eq!(rev_in, rev_out);
2907        }
2908
2909        #[cfg_attr(miri, ignore)]
2910        #[test]
2911        fn chunks_mut(ref mut input_src in vector(i32::ANY, 0..10000)) {
2912            let mut input = input_src.clone();
2913            #[allow(clippy::map_clone)]
2914            let output: Vector<_> = input.leaves_mut().flatten().map(|v| *v).collect();
2915            assert_eq!(input, output);
2916            let rev_in: Vector<_> = input.iter().rev().cloned().collect();
2917            let rev_out: Vector<_> = input.leaves_mut().rev().flat_map(|c| c.iter().rev()).cloned().collect();
2918            assert_eq!(rev_in, rev_out);
2919        }
2920
2921        // The following two tests are very slow and there are unit tests above
2922        // which test for regression of issue #55.  It would still be good to
2923        // run them occasionally.
2924
2925        // #[test]
2926        // fn issue55_back(count in 0..10000, slice_at in usize::ANY) {
2927        //     let count = count as usize;
2928        //     let slice_at = slice_at % count;
2929        //     let mut l = Vector::unit(0);
2930        //     for _ in 0..count {
2931        //         let mut tmp = Vector::unit(0);
2932        //         tmp.append(l);
2933        //         l = tmp;
2934        //     }
2935        //     let len = l.len();
2936        //     l.slice(slice_at..len);
2937        // }
2938
2939        // #[test]
2940        // fn issue55_fwd(count in 0..10000, slice_at in usize::ANY) {
2941        //     let count = count as usize;
2942        //     let slice_at = slice_at % count;
2943        //     let mut l = Vector::new();
2944        //     for i in 0..count {
2945        //         l.append(Vector::unit(i));
2946        //     }
2947        //     assert_eq!(Some(&slice_at), l.get(slice_at));
2948        // }
2949    }
2950}