[go: up one dir, main page]

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, A: Clone, P: SharedPointerKind> Add for &'a 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<'s, 'a, A, OA, P1, P2> From<&'s GenericVector<&'a 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, A: Clone, P: SharedPointerKind> From<&'a [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, A: Clone, P: SharedPointerKind> From<&'a 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 focus: &'a mut Focus<'a, A, P> = unsafe { &mut *(&mut self.focus as *mut _) };
2037        let value = focus.get(self.front_index);
2038        self.front_index += 1;
2039        value
2040    }
2041
2042    fn size_hint(&self) -> (usize, Option<usize>) {
2043        let remaining = self.back_index - self.front_index;
2044        (remaining, Some(remaining))
2045    }
2046}
2047
2048impl<'a, A, P: SharedPointerKind + 'a> DoubleEndedIterator for Iter<'a, A, P> {
2049    /// Advance the iterator and return the next value.
2050    ///
2051    /// Time: O(1)*
2052    fn next_back(&mut self) -> Option<Self::Item> {
2053        if self.front_index >= self.back_index {
2054            return None;
2055        }
2056        self.back_index -= 1;
2057        let focus: &'a mut Focus<'a, A, P> = unsafe { &mut *(&mut self.focus as *mut _) };
2058        focus.get(self.back_index)
2059    }
2060}
2061
2062impl<'a, A, P: SharedPointerKind + 'a> ExactSizeIterator for Iter<'a, A, P> {}
2063
2064impl<'a, A, P: SharedPointerKind + 'a> FusedIterator for Iter<'a, A, P> {}
2065
2066/// A mutable iterator over vectors with values of type `A`.
2067///
2068/// To obtain one, use [`Vector::iter_mut()`][iter_mut].
2069///
2070/// [iter_mut]: type.Vector.html#method.iter_mut
2071pub struct IterMut<'a, A, P: SharedPointerKind> {
2072    focus: FocusMut<'a, A, P>,
2073    front_index: usize,
2074    back_index: usize,
2075}
2076
2077impl<'a, A, P: SharedPointerKind> IterMut<'a, A, P> {
2078    fn from_focus(focus: FocusMut<'a, A, P>) -> Self {
2079        IterMut {
2080            front_index: 0,
2081            back_index: focus.len(),
2082            focus,
2083        }
2084    }
2085}
2086
2087impl<'a, A: Clone, P: SharedPointerKind> IterMut<'a, A, P> {
2088    fn new(seq: &'a mut GenericVector<A, P>) -> Self {
2089        let focus = seq.focus_mut();
2090        let len = focus.len();
2091        IterMut {
2092            focus,
2093            front_index: 0,
2094            back_index: len,
2095        }
2096    }
2097}
2098
2099impl<'a, A, P: SharedPointerKind> Iterator for IterMut<'a, A, P>
2100where
2101    A: 'a + Clone,
2102{
2103    type Item = &'a mut A;
2104
2105    /// Advance the iterator and return the next value.
2106    ///
2107    /// Time: O(1)*
2108    fn next(&mut self) -> Option<Self::Item> {
2109        if self.front_index >= self.back_index {
2110            return None;
2111        }
2112        let focus: &'a mut FocusMut<'a, A, P> = unsafe { &mut *(&mut self.focus as *mut _) };
2113        let value = focus.get_mut(self.front_index);
2114        self.front_index += 1;
2115        value
2116    }
2117
2118    fn size_hint(&self) -> (usize, Option<usize>) {
2119        let remaining = self.back_index - self.front_index;
2120        (remaining, Some(remaining))
2121    }
2122}
2123
2124impl<'a, A, P: SharedPointerKind> DoubleEndedIterator for IterMut<'a, A, P>
2125where
2126    A: 'a + Clone,
2127{
2128    /// Remove and return an element from the back of the iterator.
2129    ///
2130    /// Time: O(1)*
2131    fn next_back(&mut self) -> Option<Self::Item> {
2132        if self.front_index >= self.back_index {
2133            return None;
2134        }
2135        self.back_index -= 1;
2136        let focus: &'a mut FocusMut<'a, A, P> = unsafe { &mut *(&mut self.focus as *mut _) };
2137        focus.get_mut(self.back_index)
2138    }
2139}
2140
2141impl<'a, A: Clone, P: SharedPointerKind> ExactSizeIterator for IterMut<'a, A, P> {}
2142
2143impl<'a, A: Clone, P: SharedPointerKind> FusedIterator for IterMut<'a, A, P> {}
2144
2145/// A consuming iterator over vectors with values of type `A`.
2146pub struct ConsumingIter<A, P: SharedPointerKind> {
2147    vector: GenericVector<A, P>,
2148}
2149
2150impl<A, P: SharedPointerKind> ConsumingIter<A, P> {
2151    fn new(vector: GenericVector<A, P>) -> Self {
2152        Self { vector }
2153    }
2154}
2155
2156impl<A: Clone, P: SharedPointerKind> Iterator for ConsumingIter<A, P> {
2157    type Item = A;
2158
2159    /// Advance the iterator and return the next value.
2160    ///
2161    /// Time: O(1)*
2162    fn next(&mut self) -> Option<Self::Item> {
2163        self.vector.pop_front()
2164    }
2165
2166    fn size_hint(&self) -> (usize, Option<usize>) {
2167        let len = self.vector.len();
2168        (len, Some(len))
2169    }
2170}
2171
2172impl<A: Clone, P: SharedPointerKind> DoubleEndedIterator for ConsumingIter<A, P> {
2173    /// Remove and return an element from the back of the iterator.
2174    ///
2175    /// Time: O(1)*
2176    fn next_back(&mut self) -> Option<Self::Item> {
2177        self.vector.pop_back()
2178    }
2179}
2180
2181impl<A: Clone, P: SharedPointerKind> ExactSizeIterator for ConsumingIter<A, P> {}
2182
2183impl<A: Clone, P: SharedPointerKind> FusedIterator for ConsumingIter<A, P> {}
2184
2185/// An iterator over the leaf nodes of a vector.
2186///
2187/// To obtain one, use [`Vector::chunks()`][chunks].
2188///
2189/// [chunks]: type.Vector.html#method.chunks
2190pub struct Chunks<'a, A, P: SharedPointerKind> {
2191    focus: Focus<'a, A, P>,
2192    front_index: usize,
2193    back_index: usize,
2194}
2195
2196impl<'a, A, P: SharedPointerKind> Chunks<'a, A, P> {
2197    fn new(seq: &'a GenericVector<A, P>) -> Self {
2198        Chunks {
2199            focus: seq.focus(),
2200            front_index: 0,
2201            back_index: seq.len(),
2202        }
2203    }
2204}
2205
2206impl<'a, A, P: SharedPointerKind + 'a> Iterator for Chunks<'a, A, P> {
2207    type Item = &'a [A];
2208
2209    /// Advance the iterator and return the next value.
2210    ///
2211    /// Time: O(1)*
2212    fn next(&mut self) -> Option<Self::Item> {
2213        if self.front_index >= self.back_index {
2214            return None;
2215        }
2216        let focus: &'a mut Focus<'a, A, P> = unsafe { &mut *(&mut self.focus as *mut _) };
2217        let (range, value) = focus.chunk_at(self.front_index);
2218        self.front_index = range.end;
2219        Some(value)
2220    }
2221}
2222
2223impl<'a, A, P: SharedPointerKind + 'a> DoubleEndedIterator for Chunks<'a, A, P> {
2224    /// Remove and return an element from the back of the iterator.
2225    ///
2226    /// Time: O(1)*
2227    fn next_back(&mut self) -> Option<Self::Item> {
2228        if self.front_index >= self.back_index {
2229            return None;
2230        }
2231        self.back_index -= 1;
2232        let focus: &'a mut Focus<'a, A, P> = unsafe { &mut *(&mut self.focus as *mut _) };
2233        let (range, value) = focus.chunk_at(self.back_index);
2234        self.back_index = range.start;
2235        Some(value)
2236    }
2237}
2238
2239impl<'a, A, P: SharedPointerKind + 'a> FusedIterator for Chunks<'a, A, P> {}
2240
2241/// A mutable iterator over the leaf nodes of a vector.
2242///
2243/// To obtain one, use [`Vector::chunks_mut()`][chunks_mut].
2244///
2245/// [chunks_mut]: type.Vector.html#method.chunks_mut
2246pub struct ChunksMut<'a, A, P: SharedPointerKind> {
2247    focus: FocusMut<'a, A, P>,
2248    front_index: usize,
2249    back_index: usize,
2250}
2251
2252impl<'a, A: Clone, P: SharedPointerKind> ChunksMut<'a, A, P> {
2253    fn new(seq: &'a mut GenericVector<A, P>) -> Self {
2254        let len = seq.len();
2255        ChunksMut {
2256            focus: seq.focus_mut(),
2257            front_index: 0,
2258            back_index: len,
2259        }
2260    }
2261}
2262
2263impl<'a, A: Clone, P: SharedPointerKind> Iterator for ChunksMut<'a, A, P> {
2264    type Item = &'a mut [A];
2265
2266    /// Advance the iterator and return the next value.
2267    ///
2268    /// Time: O(1)*
2269    fn next(&mut self) -> Option<Self::Item> {
2270        if self.front_index >= self.back_index {
2271            return None;
2272        }
2273        let focus: &'a mut FocusMut<'a, A, P> = unsafe { &mut *(&mut self.focus as *mut _) };
2274        let (range, value) = focus.chunk_at(self.front_index);
2275        self.front_index = range.end;
2276        Some(value)
2277    }
2278}
2279
2280impl<'a, A: Clone, P: SharedPointerKind> DoubleEndedIterator for ChunksMut<'a, A, P> {
2281    /// Remove and return an element from the back of the iterator.
2282    ///
2283    /// Time: O(1)*
2284    fn next_back(&mut self) -> Option<Self::Item> {
2285        if self.front_index >= self.back_index {
2286            return None;
2287        }
2288        self.back_index -= 1;
2289        let focus: &'a mut FocusMut<'a, A, P> = unsafe { &mut *(&mut self.focus as *mut _) };
2290        let (range, value) = focus.chunk_at(self.back_index);
2291        self.back_index = range.start;
2292        Some(value)
2293    }
2294}
2295
2296impl<'a, A: Clone, P: SharedPointerKind> FusedIterator for ChunksMut<'a, A, P> {}
2297
2298// Proptest
2299#[cfg(any(test, feature = "proptest"))]
2300#[doc(hidden)]
2301pub mod proptest {
2302    #[deprecated(
2303        since = "14.3.0",
2304        note = "proptest strategies have moved to imbl::proptest"
2305    )]
2306    pub use crate::proptest::vector;
2307}
2308
2309// Tests
2310
2311#[cfg(test)]
2312mod test {
2313    use super::*;
2314    use crate::proptest::vector;
2315    use ::proptest::collection::vec;
2316    use ::proptest::num::{i32, usize};
2317    use ::proptest::proptest;
2318    use static_assertions::{assert_impl_all, assert_not_impl_any};
2319
2320    assert_impl_all!(Vector<i32>: Send, Sync);
2321    assert_not_impl_any!(Vector<*const i32>: Send, Sync);
2322    assert_covariant!(Vector<T> in T);
2323
2324    #[test]
2325    fn macro_allows_trailing_comma() {
2326        let vec1 = vector![1, 2, 3];
2327        let vec2 = vector![1, 2, 3,];
2328        assert_eq!(vec1, vec2);
2329    }
2330
2331    #[test]
2332    fn indexing() {
2333        let mut vec: Vector<_> = vector![0, 1, 2, 3, 4, 5];
2334        vec.push_front(0);
2335        assert_eq!(0, *vec.get(0).unwrap());
2336        assert_eq!(0, vec[0]);
2337    }
2338
2339    #[test]
2340    fn test_vector_focus_split_at() {
2341        for (data, split_points) in [
2342            (0..0, vec![0]),
2343            (0..3, vec![0, 1, 2, 3]),
2344            (0..128, vec![0, 1, 64, 127, 128]),
2345            #[cfg(not(miri))]
2346            (0..100_000, vec![0, 1, 50_000, 99_999, 100_000]),
2347        ] {
2348            let imbl_vec = Vector::from_iter(data.clone());
2349            let vec = Vec::from_iter(data);
2350            let focus = imbl_vec.focus();
2351            for split_point in split_points {
2352                let (left, right) = focus.clone().split_at(split_point);
2353                let (expected_left, expected_right) = vec.split_at(split_point);
2354                assert_eq!(
2355                    left.clone().into_iter().copied().collect::<Vec<_>>(),
2356                    expected_left
2357                );
2358                assert_eq!(
2359                    right.clone().into_iter().copied().collect::<Vec<_>>(),
2360                    expected_right
2361                );
2362            }
2363        }
2364    }
2365
2366    #[test]
2367    #[should_panic(expected = "range out of bounds")]
2368    fn test_vector_focus_narrow_out_of_range() {
2369        let vec = Vector::from_iter(0..100);
2370        _ = vec.focus().narrow(..1000);
2371    }
2372
2373    #[test]
2374    fn test_vector_focus_narrow() {
2375        macro_rules! testcase {
2376            ($data:expr, $range:expr) => {{
2377                let imbl_vector = Vector::<_>::from_iter($data);
2378                let vec = Vec::from_iter($data);
2379                let focus = imbl_vector.focus();
2380                assert_eq!(
2381                    focus
2382                        .narrow($range)
2383                        .into_iter()
2384                        .copied()
2385                        .collect::<Vec<_>>(),
2386                    vec[$range]
2387                );
2388            }};
2389        }
2390        // exhaustively test small cases
2391        for len in 0..=3 {
2392            testcase!(0..len, ..);
2393            for start in 0..=len {
2394                testcase!(0..len, start..);
2395                testcase!(0..len, ..start);
2396                for end in start..=len {
2397                    testcase!(0..len, start..end);
2398                }
2399            }
2400        }
2401    }
2402
2403    #[cfg_attr(miri, ignore)]
2404    #[test]
2405    fn large_vector_focus() {
2406        let input = Vector::from_iter(0..100_000);
2407        let vec = input.clone();
2408        let mut sum: i64 = 0;
2409        let mut focus = vec.focus();
2410        for i in 0..input.len() {
2411            sum += *focus.index(i);
2412        }
2413        let expected: i64 = (0..100_000).sum();
2414        assert_eq!(expected, sum);
2415    }
2416
2417    #[cfg_attr(miri, ignore)]
2418    #[test]
2419    fn large_vector_focus_mut() {
2420        let input = Vector::from_iter(0..100_000);
2421        let mut vec = input.clone();
2422        {
2423            let mut focus = vec.focus_mut();
2424            for i in 0..input.len() {
2425                let p = focus.index_mut(i);
2426                *p += 1;
2427            }
2428        }
2429        let expected: Vector<_> = input.into_iter().map(|i| i + 1).collect();
2430        assert_eq!(expected, vec);
2431    }
2432
2433    #[cfg_attr(miri, ignore)]
2434    #[test]
2435    fn issue_55_fwd() {
2436        let mut l = Vector::new();
2437        for i in 0..4098 {
2438            l.append(GenericVector::unit(i));
2439        }
2440        l.append(GenericVector::unit(4098));
2441        assert_eq!(Some(&4097), l.get(4097));
2442        assert_eq!(Some(&4096), l.get(4096));
2443    }
2444
2445    #[cfg_attr(miri, ignore)]
2446    #[test]
2447    fn issue_55_back() {
2448        let mut l = Vector::unit(0);
2449        for i in 0..4099 {
2450            let mut tmp = GenericVector::unit(i + 1);
2451            tmp.append(l);
2452            l = tmp;
2453        }
2454        assert_eq!(Some(&4098), l.get(1));
2455        assert_eq!(Some(&4097), l.get(2));
2456        let len = l.len();
2457        let _ = l.slice(2..len);
2458    }
2459
2460    #[test]
2461    fn issue_55_append() {
2462        let mut vec1 = Vector::from_iter(0..92);
2463        let vec2 = GenericVector::from_iter(0..165);
2464        vec1.append(vec2);
2465    }
2466
2467    #[test]
2468    fn issue_70() {
2469        // This test assumes that chunks are of size 64.
2470        if CHUNK_SIZE != 64 {
2471            return;
2472        }
2473        let mut x = Vector::new();
2474        for _ in 0..262 {
2475            x.push_back(0);
2476        }
2477        for _ in 0..97 {
2478            x.pop_front();
2479        }
2480        for &offset in &[160, 163, 160] {
2481            x.remove(offset);
2482        }
2483        for _ in 0..64 {
2484            x.push_back(0);
2485        }
2486        // At this point middle contains three chunks of size 64, 64 and 1
2487        // respectively. Previously the next `push_back()` would append another
2488        // zero-sized chunk to middle even though there is enough space left.
2489        match x.vector {
2490            VectorInner::Full(ref tree) => {
2491                assert_eq!(129, tree.middle.len());
2492                assert_eq!(3, tree.middle.number_of_children());
2493            }
2494            _ => unreachable!(),
2495        }
2496        x.push_back(0);
2497        match x.vector {
2498            VectorInner::Full(ref tree) => {
2499                assert_eq!(131, tree.middle.len());
2500                assert_eq!(3, tree.middle.number_of_children())
2501            }
2502            _ => unreachable!(),
2503        }
2504        for _ in 0..64 {
2505            x.push_back(0);
2506        }
2507        for _ in x.iter() {}
2508    }
2509
2510    #[cfg_attr(miri, ignore)]
2511    #[test]
2512    fn issue_67() {
2513        let mut l = Vector::unit(4100);
2514        for i in (0..4099).rev() {
2515            let mut tmp = GenericVector::unit(i);
2516            tmp.append(l);
2517            l = tmp;
2518        }
2519        assert_eq!(4100, l.len());
2520        let len = l.len();
2521        let tail = l.slice(1..len);
2522        assert_eq!(1, l.len());
2523        assert_eq!(4099, tail.len());
2524        assert_eq!(Some(&0), l.get(0));
2525        assert_eq!(Some(&1), tail.get(0));
2526    }
2527
2528    #[test]
2529    fn issue_74_simple_size() {
2530        use crate::nodes::rrb::NODE_SIZE;
2531        let mut x = Vector::new();
2532        for _ in 0..(CHUNK_SIZE
2533            * (
2534                1 // inner_f
2535                + (2 * NODE_SIZE) // middle: two full Entry::Nodes (4096 elements each)
2536                + 1 // inner_b
2537                + 1
2538                // outer_b
2539            ))
2540        {
2541            x.push_back(0u32);
2542        }
2543        let middle_first_node_start = CHUNK_SIZE;
2544        let middle_second_node_start = middle_first_node_start + NODE_SIZE * CHUNK_SIZE;
2545        // This reduces the size of the second node to 4095.
2546        x.remove(middle_second_node_start);
2547        // As outer_b is full, this will cause inner_b (length 64) to be pushed
2548        // to middle. The first element will be merged into the second node, the
2549        // remaining 63 elements will end up in a new node.
2550        x.push_back(0u32);
2551        match x.vector {
2552            VectorInner::Full(tree) => {
2553                if CHUNK_SIZE == 64 {
2554                    assert_eq!(3, tree.middle.number_of_children());
2555                }
2556                assert_eq!(
2557                    2 * NODE_SIZE * CHUNK_SIZE + CHUNK_SIZE - 1,
2558                    tree.middle.len()
2559                );
2560            }
2561            _ => unreachable!(),
2562        }
2563    }
2564
2565    #[test]
2566    fn issue_77() {
2567        let mut x = Vector::new();
2568        for _ in 0..44 {
2569            x.push_back(0);
2570        }
2571        for _ in 0..20 {
2572            x.insert(0, 0);
2573        }
2574        x.insert(1, 0);
2575        for _ in 0..441 {
2576            x.push_back(0);
2577        }
2578        for _ in 0..58 {
2579            x.insert(0, 0);
2580        }
2581        x.insert(514, 0);
2582        for _ in 0..73 {
2583            x.push_back(0);
2584        }
2585        for _ in 0..10 {
2586            x.insert(0, 0);
2587        }
2588        x.insert(514, 0);
2589    }
2590
2591    #[cfg_attr(miri, ignore)]
2592    #[test]
2593    fn issue_105() {
2594        let mut v = Vector::<_>::new();
2595
2596        for i in 0..270_000 {
2597            v.push_front(i);
2598        }
2599
2600        while !v.is_empty() {
2601            v = v.take(v.len() - 1);
2602        }
2603    }
2604
2605    #[cfg_attr(miri, ignore)]
2606    #[test]
2607    fn issue_107_split_off_causes_overflow() {
2608        let mut vec = Vector::from_iter(0..4289);
2609        let mut control = Vec::from_iter(0..4289);
2610        let chunk = 64;
2611
2612        while vec.len() >= chunk {
2613            vec = vec.split_off(chunk);
2614            control = control.split_off(chunk);
2615            assert_eq!(vec.len(), control.len());
2616            assert_eq!(control, vec.iter().cloned().collect::<Vec<_>>());
2617        }
2618    }
2619
2620    #[cfg_attr(miri, ignore)]
2621    #[test]
2622    fn collect_crash() {
2623        let _vector: Vector<i32> = (0..5953).collect();
2624        // let _vector: Vector<i32> = (0..16384).collect();
2625    }
2626
2627    #[test]
2628    fn issue_116() {
2629        let vec = Vector::from_iter(0..300);
2630        let rev_vec: Vector<_> = vec.clone().into_iter().rev().collect();
2631        assert_eq!(vec.len(), rev_vec.len());
2632    }
2633
2634    #[test]
2635    fn issue_131() {
2636        let smol = std::iter::repeat(42).take(64).collect::<Vector<_>>();
2637        let mut smol2 = smol.clone();
2638        assert!(smol.ptr_eq(&smol2));
2639        smol2.set(63, 420);
2640        assert!(!smol.ptr_eq(&smol2));
2641
2642        let huge = std::iter::repeat(42).take(65).collect::<Vector<_>>();
2643        let mut huge2 = huge.clone();
2644        assert!(huge.ptr_eq(&huge2));
2645        huge2.set(63, 420);
2646        assert!(!huge.ptr_eq(&huge2));
2647    }
2648
2649    #[test]
2650    fn ptr_eq() {
2651        const MAX: usize = if cfg!(miri) { 64 } else { 256 };
2652        for len in 32..MAX {
2653            let input = std::iter::repeat(42).take(len).collect::<Vector<_>>();
2654            let mut inp2 = input.clone();
2655            assert!(input.ptr_eq(&inp2));
2656            inp2.set(len - 1, 98);
2657            assert_ne!(inp2.get(len - 1), input.get(len - 1));
2658            assert!(!input.ptr_eq(&inp2));
2659        }
2660    }
2661
2662    #[test]
2663    fn full_retain() {
2664        let mut a = Vector::from_iter(0..128);
2665        let b = Vector::from_iter(128..256);
2666        a.append(b);
2667        assert!(matches!(a.vector, Full(_)));
2668        a.retain(|i| *i % 2 == 0);
2669        assert_eq!(a.len(), 128);
2670    }
2671
2672    proptest! {
2673        // Miri is slow, so we ignore long-ish tests to keep the test
2674        // time manageable. For some property tests, it may be worthwhile
2675        // enabling them in miri with reduced iteration counts.
2676        #[cfg_attr(miri, ignore)]
2677        #[test]
2678        fn iter(ref vec in vec(i32::ANY, 0..1000)) {
2679            let seq = Vector::from_iter(vec.iter().cloned());
2680            for (index, item) in seq.iter().enumerate() {
2681                assert_eq!(&vec[index], item);
2682            }
2683            assert_eq!(vec.len(), seq.len());
2684        }
2685
2686        #[cfg_attr(miri, ignore)]
2687        #[test]
2688        fn push_front_mut(ref input in vec(i32::ANY, 0..1000)) {
2689            let mut vector = Vector::new();
2690            for (count, value) in input.iter().cloned().enumerate() {
2691                assert_eq!(count, vector.len());
2692                vector.push_front(value);
2693                assert_eq!(count + 1, vector.len());
2694            }
2695            let input2 = Vec::from_iter(input.iter().rev().cloned());
2696            assert_eq!(input2, Vec::from_iter(vector.iter().cloned()));
2697        }
2698
2699        #[cfg_attr(miri, ignore)]
2700        #[test]
2701        fn push_back_mut(ref input in vec(i32::ANY, 0..1000)) {
2702            let mut vector = Vector::new();
2703            for (count, value) in input.iter().cloned().enumerate() {
2704                assert_eq!(count, vector.len());
2705                vector.push_back(value);
2706                assert_eq!(count + 1, vector.len());
2707            }
2708            assert_eq!(input, &Vec::from_iter(vector.iter().cloned()));
2709        }
2710
2711        #[cfg_attr(miri, ignore)]
2712        #[test]
2713        fn pop_back_mut(ref input in vec(i32::ANY, 0..1000)) {
2714            let mut vector = Vector::from_iter(input.iter().cloned());
2715            assert_eq!(input.len(), vector.len());
2716            for (index, value) in input.iter().cloned().enumerate().rev() {
2717                match vector.pop_back() {
2718                    None => panic!("vector emptied unexpectedly"),
2719                    Some(item) => {
2720                        assert_eq!(index, vector.len());
2721                        assert_eq!(value, item);
2722                    }
2723                }
2724            }
2725            assert_eq!(0, vector.len());
2726        }
2727
2728        #[cfg_attr(miri, ignore)]
2729        #[test]
2730        fn pop_front_mut(ref input in vec(i32::ANY, 0..1000)) {
2731            let mut vector = Vector::from_iter(input.iter().cloned());
2732            assert_eq!(input.len(), vector.len());
2733            for (index, value) in input.iter().cloned().rev().enumerate().rev() {
2734                match vector.pop_front() {
2735                    None => panic!("vector emptied unexpectedly"),
2736                    Some(item) => {
2737                        assert_eq!(index, vector.len());
2738                        assert_eq!(value, item);
2739                    }
2740                }
2741            }
2742            assert_eq!(0, vector.len());
2743        }
2744
2745        // #[test]
2746        // fn push_and_pop(ref input in vec(i32::ANY, 0..1000)) {
2747        //     let mut vector = Vector::new();
2748        //     for (count, value) in input.iter().cloned().enumerate() {
2749        //         assert_eq!(count, vector.len());
2750        //         vector.push_back(value);
2751        //         assert_eq!(count + 1, vector.len());
2752        //     }
2753        //     for (index, value) in input.iter().cloned().rev().enumerate().rev() {
2754        //         match vector.pop_front() {
2755        //             None => panic!("vector emptied unexpectedly"),
2756        //             Some(item) => {
2757        //                 assert_eq!(index, vector.len());
2758        //                 assert_eq!(value, item);
2759        //             }
2760        //         }
2761        //     }
2762        //     assert_eq!(true, vector.is_empty());
2763        // }
2764
2765        #[cfg_attr(miri, ignore)]
2766        #[test]
2767        fn skip(ref vec in vec(i32::ANY, 1..2000), count in usize::ANY) {
2768            let count = count % (vec.len() + 1);
2769            let old = Vector::from_iter(vec.iter().cloned());
2770            let new = old.skip(count);
2771            assert_eq!(old.len(), vec.len());
2772            assert_eq!(new.len(), vec.len() - count);
2773            for (index, item) in old.iter().enumerate() {
2774                assert_eq!(& vec[index], item);
2775            }
2776            for (index, item) in new.iter().enumerate() {
2777                assert_eq!(&vec[count + index], item);
2778            }
2779        }
2780
2781        #[cfg_attr(miri, ignore)]
2782        #[test]
2783        fn split_off(ref vec in vec(i32::ANY, 1..2000), split_pos in usize::ANY) {
2784            let split_index = split_pos % (vec.len() + 1);
2785            let mut left = Vector::from_iter(vec.iter().cloned());
2786            let right = left.split_off(split_index);
2787            assert_eq!(left.len(), split_index);
2788            assert_eq!(right.len(), vec.len() - split_index);
2789            for (index, item) in left.iter().enumerate() {
2790                assert_eq!(& vec[index], item);
2791            }
2792            for (index, item) in right.iter().enumerate() {
2793                assert_eq!(&vec[split_index + index], item);
2794            }
2795        }
2796
2797        #[cfg_attr(miri, ignore)]
2798        #[test]
2799        fn append(ref vec1 in vec(i32::ANY, 0..1000), ref vec2 in vec(i32::ANY, 0..1000)) {
2800            let mut seq1 = Vector::from_iter(vec1.iter().cloned());
2801            let seq2 = Vector::from_iter(vec2.iter().cloned());
2802            assert_eq!(seq1.len(), vec1.len());
2803            assert_eq!(seq2.len(), vec2.len());
2804            seq1.append(seq2);
2805            let mut vec = vec1.clone();
2806            vec.extend(vec2);
2807            assert_eq!(seq1.len(), vec.len());
2808            for (index, item) in seq1.into_iter().enumerate() {
2809                assert_eq!(vec[index], item);
2810            }
2811        }
2812
2813        #[cfg_attr(miri, ignore)]
2814        #[test]
2815        fn iter_mut(ref input in vector(i32::ANY, 0..10000)) {
2816            let mut vec = input.clone();
2817            {
2818                for p in vec.iter_mut() {
2819                    *p = p.overflowing_add(1).0;
2820                }
2821            }
2822            let expected: Vector<i32> = input.clone().into_iter().map(|i| i.overflowing_add(1).0).collect();
2823            assert_eq!(expected, vec);
2824        }
2825
2826        #[cfg_attr(miri, ignore)]
2827        #[test]
2828        fn focus(ref input in vector(i32::ANY, 0..10000)) {
2829            let mut vec = input.clone();
2830            {
2831                let mut focus = vec.focus_mut();
2832                for i in 0..input.len() {
2833                    let p = focus.index_mut(i);
2834                    *p = p.overflowing_add(1).0;
2835                }
2836            }
2837            let expected: Vector<i32> = input.clone().into_iter().map(|i| i.overflowing_add(1).0).collect();
2838            assert_eq!(expected, vec);
2839        }
2840
2841        #[cfg_attr(miri, ignore)]
2842        #[test]
2843        fn focus_mut_split(ref input in vector(i32::ANY, 0..10000)) {
2844            let mut vec = input.clone();
2845
2846            fn split_down(focus: FocusMut<'_, i32, DefaultSharedPtr>) {
2847                let len = focus.len();
2848                if len < 8 {
2849                    for p in focus {
2850                        *p = p.overflowing_add(1).0;
2851                    }
2852                } else {
2853                    let (left, right) = focus.split_at(len / 2);
2854                    split_down(left);
2855                    split_down(right);
2856                }
2857            }
2858
2859            split_down(vec.focus_mut());
2860
2861            let expected: Vector<_> = input.clone().into_iter().map(|i| i.overflowing_add(1).0).collect();
2862            assert_eq!(expected, vec);
2863        }
2864
2865        #[cfg_attr(miri, ignore)]
2866        #[test]
2867        fn chunks(ref input in vector(i32::ANY, 0..10000)) {
2868            let output: Vector<_> = input.leaves().flatten().cloned().collect();
2869            assert_eq!(input, &output);
2870            let rev_in: Vector<_> = input.iter().rev().cloned().collect();
2871            let rev_out: Vector<_> = input.leaves().rev().flat_map(|c| c.iter().rev()).cloned().collect();
2872            assert_eq!(rev_in, rev_out);
2873        }
2874
2875        #[cfg_attr(miri, ignore)]
2876        #[test]
2877        fn chunks_mut(ref mut input_src in vector(i32::ANY, 0..10000)) {
2878            let mut input = input_src.clone();
2879            #[allow(clippy::map_clone)]
2880            let output: Vector<_> = input.leaves_mut().flatten().map(|v| *v).collect();
2881            assert_eq!(input, output);
2882            let rev_in: Vector<_> = input.iter().rev().cloned().collect();
2883            let rev_out: Vector<_> = input.leaves_mut().rev().flat_map(|c| c.iter().rev()).cloned().collect();
2884            assert_eq!(rev_in, rev_out);
2885        }
2886
2887        // The following two tests are very slow and there are unit tests above
2888        // which test for regression of issue #55.  It would still be good to
2889        // run them occasionally.
2890
2891        // #[test]
2892        // fn issue55_back(count in 0..10000, slice_at in usize::ANY) {
2893        //     let count = count as usize;
2894        //     let slice_at = slice_at % count;
2895        //     let mut l = Vector::unit(0);
2896        //     for _ in 0..count {
2897        //         let mut tmp = Vector::unit(0);
2898        //         tmp.append(l);
2899        //         l = tmp;
2900        //     }
2901        //     let len = l.len();
2902        //     l.slice(slice_at..len);
2903        // }
2904
2905        // #[test]
2906        // fn issue55_fwd(count in 0..10000, slice_at in usize::ANY) {
2907        //     let count = count as usize;
2908        //     let slice_at = slice_at % count;
2909        //     let mut l = Vector::new();
2910        //     for i in 0..count {
2911        //         l.append(Vector::unit(i));
2912        //     }
2913        //     assert_eq!(Some(&slice_at), l.get(slice_at));
2914        // }
2915    }
2916}