[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        A: Ord,
1493        F: FnMut(&A, &A) -> Ordering,
1494    {
1495        match self.binary_search_by(|scan_item| f(scan_item, &item)) {
1496            Ok(idx) | Err(idx) => self.insert(idx, item),
1497        }
1498    }
1499
1500    /// Insert an element into a sorted vector where the comparison function
1501    /// delegates to the Ord implementation for values calculated by a user-
1502    /// provided function defined on the item type.
1503    ///
1504    /// This function assumes the vector is already sorted. If it isn't sorted,
1505    /// this function may insert the provided value out of order.
1506    ///
1507    /// Note that the ordering of the sorted vector must logically match the
1508    /// `PartialOrd` implementation of the type returned by the passed comparator
1509    /// function `f`. Incompatible definitions of the ordering won't result in
1510    /// memory unsafety, but will likely result in out-of-order insertions.
1511    ///
1512    ///
1513    /// Time: O(log n)
1514    ///
1515    /// # Examples
1516    ///
1517    /// ```
1518    /// # #[macro_use] extern crate imbl;
1519    /// # use imbl::Vector;
1520    ///
1521    /// type A = (u8, &'static str);
1522    ///
1523    /// let mut vec: Vector<A> = vector![(3, "a"), (1, "c"), (0, "d")];
1524    ///
1525    /// // For the sake of this example, let's say that only the second element
1526    /// // of the A tuple is important in the context of comparison.
1527    /// vec.insert_ord_by_key((0, "b"), |a| a.1);
1528    /// assert_eq!(vector![(3, "a"), (0, "b"), (1, "c"), (0, "d")], vec);
1529    ///
1530    /// // Note that `insert_ord` does not work in this case because it uses
1531    /// // the default comparison function for the item type.
1532    /// vec.insert_ord((0, "e"));
1533    /// assert_eq!(vector![(3, "a"), (0, "b"), (0, "e"), (1, "c"), (0, "d")], vec);
1534    /// ```
1535    pub fn insert_ord_by_key<B, F>(&mut self, item: A, mut f: F)
1536    where
1537        B: Ord,
1538        F: FnMut(&A) -> B,
1539    {
1540        match self.binary_search_by_key(&f(&item), |scan_item| f(scan_item)) {
1541            Ok(idx) | Err(idx) => self.insert(idx, item),
1542        }
1543    }
1544
1545    /// Sort a vector.
1546    ///
1547    /// Time: O(n log n)
1548    ///
1549    /// # Examples
1550    ///
1551    /// ```
1552    /// # #[macro_use] extern crate imbl;
1553    /// let mut vec = vector![3, 2, 5, 4, 1];
1554    /// vec.sort();
1555    /// assert_eq!(vector![1, 2, 3, 4, 5], vec);
1556    /// ```
1557    pub fn sort(&mut self)
1558    where
1559        A: Ord,
1560    {
1561        self.sort_by(Ord::cmp)
1562    }
1563
1564    /// Sort a vector using a comparator function.
1565    ///
1566    /// Time: O(n log n)
1567    ///
1568    /// # Examples
1569    ///
1570    /// ```
1571    /// # #[macro_use] extern crate imbl;
1572    /// let mut vec = vector![3, 2, 5, 4, 1];
1573    /// vec.sort_by(|left, right| left.cmp(right));
1574    /// assert_eq!(vector![1, 2, 3, 4, 5], vec);
1575    /// ```
1576    pub fn sort_by<F>(&mut self, cmp: F)
1577    where
1578        F: Fn(&A, &A) -> Ordering,
1579    {
1580        let len = self.len();
1581        if len > 1 {
1582            sort::quicksort(self.focus_mut(), &cmp);
1583        }
1584    }
1585}
1586
1587// Implementation details
1588
1589impl<A, P: SharedPointerKind> RRB<A, P> {
1590    fn new() -> Self {
1591        RRB {
1592            length: 0,
1593            middle_level: 0,
1594            outer_f: SharedPointer::default(),
1595            inner_f: SharedPointer::default(),
1596            middle: SharedPointer::new(Node::new()),
1597            inner_b: SharedPointer::default(),
1598            outer_b: SharedPointer::default(),
1599        }
1600    }
1601
1602    #[cfg(any(test, feature = "debug"))]
1603    fn assert_invariants(&self) {
1604        let ml = self.middle.assert_invariants(self.middle_level);
1605        assert_eq!(
1606            self.length,
1607            self.outer_f.len() + self.inner_f.len() + ml + self.inner_b.len() + self.outer_b.len()
1608        );
1609    }
1610}
1611
1612impl<A: Clone, P: SharedPointerKind> RRB<A, P> {
1613    fn prune(&mut self) {
1614        if self.middle.is_empty() {
1615            self.middle = SharedPointer::new(Node::new());
1616            self.middle_level = 0;
1617        } else {
1618            while self.middle_level > 0 && self.middle.is_single() {
1619                // FIXME could be optimised, cloning the node is expensive
1620                self.middle = SharedPointer::new(self.middle.first_child().clone());
1621                self.middle_level -= 1;
1622            }
1623        }
1624    }
1625
1626    fn pop_front(&mut self) -> Option<A> {
1627        if self.length == 0 {
1628            return None;
1629        }
1630        if self.outer_f.is_empty() {
1631            if self.inner_f.is_empty() {
1632                if self.middle.is_empty() {
1633                    if self.inner_b.is_empty() {
1634                        swap(&mut self.outer_f, &mut self.outer_b);
1635                    } else {
1636                        swap(&mut self.outer_f, &mut self.inner_b);
1637                    }
1638                } else {
1639                    self.outer_f = self.pop_middle(Side::Left).unwrap();
1640                }
1641            } else {
1642                swap(&mut self.outer_f, &mut self.inner_f);
1643            }
1644        }
1645        self.length -= 1;
1646        let outer_f = SharedPointer::make_mut(&mut self.outer_f);
1647        Some(outer_f.pop_front())
1648    }
1649
1650    fn pop_back(&mut self) -> Option<A> {
1651        if self.length == 0 {
1652            return None;
1653        }
1654        if self.outer_b.is_empty() {
1655            if self.inner_b.is_empty() {
1656                if self.middle.is_empty() {
1657                    if self.inner_f.is_empty() {
1658                        swap(&mut self.outer_b, &mut self.outer_f);
1659                    } else {
1660                        swap(&mut self.outer_b, &mut self.inner_f);
1661                    }
1662                } else {
1663                    self.outer_b = self.pop_middle(Side::Right).unwrap();
1664                }
1665            } else {
1666                swap(&mut self.outer_b, &mut self.inner_b);
1667            }
1668        }
1669        self.length -= 1;
1670        let outer_b = SharedPointer::make_mut(&mut self.outer_b);
1671        Some(outer_b.pop_back())
1672    }
1673
1674    fn push_front(&mut self, value: A) {
1675        if self.outer_f.is_full() {
1676            swap(&mut self.outer_f, &mut self.inner_f);
1677            if !self.outer_f.is_empty() {
1678                let mut chunk = SharedPointer::new(Chunk::new());
1679                swap(&mut chunk, &mut self.outer_f);
1680                self.push_middle(Side::Left, chunk);
1681            }
1682        }
1683        self.length = self.length.checked_add(1).expect("Vector length overflow");
1684        let outer_f = SharedPointer::make_mut(&mut self.outer_f);
1685        outer_f.push_front(value)
1686    }
1687
1688    fn push_back(&mut self, value: A) {
1689        if self.outer_b.is_full() {
1690            swap(&mut self.outer_b, &mut self.inner_b);
1691            if !self.outer_b.is_empty() {
1692                let mut chunk = SharedPointer::new(Chunk::new());
1693                swap(&mut chunk, &mut self.outer_b);
1694                self.push_middle(Side::Right, chunk);
1695            }
1696        }
1697        self.length = self.length.checked_add(1).expect("Vector length overflow");
1698        let outer_b = SharedPointer::make_mut(&mut self.outer_b);
1699        outer_b.push_back(value)
1700    }
1701
1702    fn push_middle(&mut self, side: Side, chunk: SharedPointer<Chunk<A>, P>) {
1703        if chunk.is_empty() {
1704            return;
1705        }
1706        let new_middle = {
1707            let middle = SharedPointer::make_mut(&mut self.middle);
1708            match middle.push_chunk(self.middle_level, side, chunk) {
1709                PushResult::Done => return,
1710                PushResult::Full(chunk, _num_drained) => SharedPointer::new({
1711                    match side {
1712                        Side::Left => Node::from_chunk(self.middle_level, chunk)
1713                            .join_branches(middle.clone(), self.middle_level),
1714                        Side::Right => middle.clone().join_branches(
1715                            Node::from_chunk(self.middle_level, chunk),
1716                            self.middle_level,
1717                        ),
1718                    }
1719                }),
1720            }
1721        };
1722        self.middle_level += 1;
1723        self.middle = new_middle;
1724    }
1725
1726    fn pop_middle(&mut self, side: Side) -> Option<SharedPointer<Chunk<A>, P>> {
1727        let chunk = {
1728            let middle = SharedPointer::make_mut(&mut self.middle);
1729            match middle.pop_chunk(self.middle_level, side) {
1730                PopResult::Empty => return None,
1731                PopResult::Done(chunk) => chunk,
1732                PopResult::Drained(chunk) => {
1733                    middle.clear_node();
1734                    self.middle_level = 0;
1735                    chunk
1736                }
1737            }
1738        };
1739        Some(chunk)
1740    }
1741}
1742
1743#[inline]
1744fn replace_shared_pointer<A: Default, P: SharedPointerKind>(
1745    dest: &mut SharedPointer<A, P>,
1746) -> SharedPointer<A, P> {
1747    std::mem::take(dest)
1748}
1749
1750// Core traits
1751
1752impl<A, P: SharedPointerKind> Default for GenericVector<A, P> {
1753    fn default() -> Self {
1754        Self::new()
1755    }
1756}
1757
1758impl<A: Clone, P: SharedPointerKind> Clone for GenericVector<A, P> {
1759    /// Clone a vector.
1760    ///
1761    /// Time: O(1), or O(n) with a very small, bounded *n* for an inline vector.
1762    fn clone(&self) -> Self {
1763        Self {
1764            vector: match &self.vector {
1765                Inline(chunk) => Inline(chunk.clone()),
1766                Single(chunk) => Single(chunk.clone()),
1767                Full(tree) => Full(tree.clone()),
1768            },
1769        }
1770    }
1771}
1772
1773impl<A: Debug, P: SharedPointerKind> Debug for GenericVector<A, P> {
1774    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
1775        f.debug_list().entries(self.iter()).finish()
1776        // match self {
1777        //     Full(rrb) => {
1778        //         writeln!(f, "Head: {:?} {:?}", rrb.outer_f, rrb.inner_f)?;
1779        //         rrb.middle.print(f, 0, rrb.middle_level)?;
1780        //         writeln!(f, "Tail: {:?} {:?}", rrb.inner_b, rrb.outer_b)
1781        //     }
1782        //     Single(_) => write!(f, "nowt"),
1783        // }
1784    }
1785}
1786
1787impl<A: PartialEq, P: SharedPointerKind> PartialEq for GenericVector<A, P> {
1788    fn eq(&self, other: &Self) -> bool {
1789        self.len() == other.len() && self.iter().eq(other.iter())
1790    }
1791}
1792
1793impl<A: Eq, P: SharedPointerKind> Eq for GenericVector<A, P> {}
1794
1795impl<A: PartialOrd, P: SharedPointerKind> PartialOrd for GenericVector<A, P> {
1796    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1797        self.iter().partial_cmp(other.iter())
1798    }
1799}
1800
1801impl<A: Ord, P: SharedPointerKind> Ord for GenericVector<A, P> {
1802    fn cmp(&self, other: &Self) -> Ordering {
1803        self.iter().cmp(other.iter())
1804    }
1805}
1806
1807impl<A: Hash, P: SharedPointerKind> Hash for GenericVector<A, P> {
1808    fn hash<H: Hasher>(&self, state: &mut H) {
1809        for i in self {
1810            i.hash(state)
1811        }
1812    }
1813}
1814
1815impl<A: Clone, P: SharedPointerKind> Sum for GenericVector<A, P> {
1816    fn sum<I>(it: I) -> Self
1817    where
1818        I: Iterator<Item = Self>,
1819    {
1820        it.fold(Self::new(), |a, b| a + b)
1821    }
1822}
1823
1824impl<A: Clone, P: SharedPointerKind> Add for GenericVector<A, P> {
1825    type Output = GenericVector<A, P>;
1826
1827    /// Concatenate two vectors.
1828    ///
1829    /// Time: O(log n)
1830    fn add(mut self, other: Self) -> Self::Output {
1831        self.append(other);
1832        self
1833    }
1834}
1835
1836impl<'a, A: Clone, P: SharedPointerKind> Add for &'a GenericVector<A, P> {
1837    type Output = GenericVector<A, P>;
1838
1839    /// Concatenate two vectors.
1840    ///
1841    /// Time: O(log n)
1842    fn add(self, other: Self) -> Self::Output {
1843        let mut out = self.clone();
1844        out.append(other.clone());
1845        out
1846    }
1847}
1848
1849impl<A: Clone, P: SharedPointerKind> Extend<A> for GenericVector<A, P> {
1850    /// Add values to the end of a vector by consuming an iterator.
1851    ///
1852    /// Time: O(n)
1853    fn extend<I>(&mut self, iter: I)
1854    where
1855        I: IntoIterator<Item = A>,
1856    {
1857        for item in iter {
1858            self.push_back(item)
1859        }
1860    }
1861}
1862
1863impl<A, P: SharedPointerKind> Index<usize> for GenericVector<A, P> {
1864    type Output = A;
1865    /// Get a reference to the value at index `index` in the vector.
1866    ///
1867    /// Time: O(log n)
1868    fn index(&self, index: usize) -> &Self::Output {
1869        match self.get(index) {
1870            Some(value) => value,
1871            None => panic!(
1872                "Vector::index: index out of bounds: {} < {}",
1873                index,
1874                self.len()
1875            ),
1876        }
1877    }
1878}
1879
1880impl<A: Clone, P: SharedPointerKind> IndexMut<usize> for GenericVector<A, P> {
1881    /// Get a mutable reference to the value at index `index` in the
1882    /// vector.
1883    ///
1884    /// Time: O(log n)
1885    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
1886        match self.get_mut(index) {
1887            Some(value) => value,
1888            None => panic!("Vector::index_mut: index out of bounds"),
1889        }
1890    }
1891}
1892
1893// Conversions
1894
1895impl<'a, A, P: SharedPointerKind> IntoIterator for &'a GenericVector<A, P> {
1896    type Item = &'a A;
1897    type IntoIter = Iter<'a, A, P>;
1898    fn into_iter(self) -> Self::IntoIter {
1899        self.iter()
1900    }
1901}
1902
1903impl<'a, A: Clone, P: SharedPointerKind> IntoIterator for &'a mut GenericVector<A, P> {
1904    type Item = &'a mut A;
1905    type IntoIter = IterMut<'a, A, P>;
1906    fn into_iter(self) -> Self::IntoIter {
1907        self.iter_mut()
1908    }
1909}
1910
1911impl<A: Clone, P: SharedPointerKind> IntoIterator for GenericVector<A, P> {
1912    type Item = A;
1913    type IntoIter = ConsumingIter<A, P>;
1914    fn into_iter(self) -> Self::IntoIter {
1915        ConsumingIter::new(self)
1916    }
1917}
1918
1919impl<A: Clone, P: SharedPointerKind> FromIterator<A> for GenericVector<A, P> {
1920    /// Create a vector from an iterator.
1921    ///
1922    /// Time: O(n)
1923    fn from_iter<I>(iter: I) -> Self
1924    where
1925        I: IntoIterator<Item = A>,
1926    {
1927        let mut seq = Self::new();
1928        for item in iter {
1929            seq.push_back(item)
1930        }
1931        seq
1932    }
1933}
1934
1935impl<'s, 'a, A, OA, P1, P2> From<&'s GenericVector<&'a A, P2>> for GenericVector<OA, P1>
1936where
1937    A: ToOwned<Owned = OA>,
1938    OA: Borrow<A> + Clone,
1939    P1: SharedPointerKind,
1940    P2: SharedPointerKind,
1941{
1942    fn from(vec: &GenericVector<&A, P2>) -> Self {
1943        vec.iter().map(|a| (*a).to_owned()).collect()
1944    }
1945}
1946
1947impl<A, const N: usize, P: SharedPointerKind> From<[A; N]> for GenericVector<A, P>
1948where
1949    A: Clone,
1950{
1951    fn from(arr: [A; N]) -> Self {
1952        IntoIterator::into_iter(arr).collect()
1953    }
1954}
1955
1956impl<'a, A: Clone, P: SharedPointerKind> From<&'a [A]> for GenericVector<A, P> {
1957    fn from(slice: &[A]) -> Self {
1958        slice.iter().cloned().collect()
1959    }
1960}
1961
1962impl<A: Clone, P: SharedPointerKind> From<Vec<A>> for GenericVector<A, P> {
1963    /// Create a vector from a [`std::vec::Vec`][vec].
1964    ///
1965    /// Time: O(n)
1966    ///
1967    /// [vec]: https://doc.rust-lang.org/std/vec/struct.Vec.html
1968    fn from(vec: Vec<A>) -> Self {
1969        vec.into_iter().collect()
1970    }
1971}
1972
1973impl<'a, A: Clone, P: SharedPointerKind> From<&'a Vec<A>> for GenericVector<A, P> {
1974    /// Create a vector from a [`std::vec::Vec`][vec].
1975    ///
1976    /// Time: O(n)
1977    ///
1978    /// [vec]: https://doc.rust-lang.org/std/vec/struct.Vec.html
1979    fn from(vec: &Vec<A>) -> Self {
1980        vec.iter().cloned().collect()
1981    }
1982}
1983
1984// Iterators
1985
1986/// An iterator over vectors with values of type `A`.
1987///
1988/// To obtain one, use [`Vector::iter()`][iter].
1989///
1990/// [iter]: enum.Vector.html#method.iter
1991// TODO: we'd like to support Clone even if A is not Clone, but it isn't trivial because
1992// the TreeFocus variant of Focus does need A to be Clone.
1993#[derive(Clone)]
1994pub struct Iter<'a, A, P: SharedPointerKind> {
1995    focus: Focus<'a, A, P>,
1996    front_index: usize,
1997    back_index: usize,
1998}
1999
2000impl<'a, A, P: SharedPointerKind> Iter<'a, A, P> {
2001    fn new(seq: &'a GenericVector<A, P>) -> Self {
2002        Iter {
2003            focus: seq.focus(),
2004            front_index: 0,
2005            back_index: seq.len(),
2006        }
2007    }
2008
2009    fn from_focus(focus: Focus<'a, A, P>) -> Self {
2010        Iter {
2011            front_index: 0,
2012            back_index: focus.len(),
2013            focus,
2014        }
2015    }
2016}
2017
2018impl<'a, A, P: SharedPointerKind + 'a> Iterator for Iter<'a, A, P> {
2019    type Item = &'a A;
2020
2021    /// Advance the iterator and return the next value.
2022    ///
2023    /// Time: O(1)*
2024    fn next(&mut self) -> Option<Self::Item> {
2025        if self.front_index >= self.back_index {
2026            return None;
2027        }
2028        let focus: &'a mut Focus<'a, A, P> = unsafe { &mut *(&mut self.focus as *mut _) };
2029        let value = focus.get(self.front_index);
2030        self.front_index += 1;
2031        value
2032    }
2033
2034    fn size_hint(&self) -> (usize, Option<usize>) {
2035        let remaining = self.back_index - self.front_index;
2036        (remaining, Some(remaining))
2037    }
2038}
2039
2040impl<'a, A, P: SharedPointerKind + 'a> DoubleEndedIterator for Iter<'a, A, P> {
2041    /// Advance the iterator and return the next value.
2042    ///
2043    /// Time: O(1)*
2044    fn next_back(&mut self) -> Option<Self::Item> {
2045        if self.front_index >= self.back_index {
2046            return None;
2047        }
2048        self.back_index -= 1;
2049        let focus: &'a mut Focus<'a, A, P> = unsafe { &mut *(&mut self.focus as *mut _) };
2050        focus.get(self.back_index)
2051    }
2052}
2053
2054impl<'a, A, P: SharedPointerKind + 'a> ExactSizeIterator for Iter<'a, A, P> {}
2055
2056impl<'a, A, P: SharedPointerKind + 'a> FusedIterator for Iter<'a, A, P> {}
2057
2058/// A mutable iterator over vectors with values of type `A`.
2059///
2060/// To obtain one, use [`Vector::iter_mut()`][iter_mut].
2061///
2062/// [iter_mut]: enum.Vector.html#method.iter_mut
2063pub struct IterMut<'a, A, P: SharedPointerKind> {
2064    focus: FocusMut<'a, A, P>,
2065    front_index: usize,
2066    back_index: usize,
2067}
2068
2069impl<'a, A, P: SharedPointerKind> IterMut<'a, A, P> {
2070    fn from_focus(focus: FocusMut<'a, A, P>) -> Self {
2071        IterMut {
2072            front_index: 0,
2073            back_index: focus.len(),
2074            focus,
2075        }
2076    }
2077}
2078
2079impl<'a, A: Clone, P: SharedPointerKind> IterMut<'a, A, P> {
2080    fn new(seq: &'a mut GenericVector<A, P>) -> Self {
2081        let focus = seq.focus_mut();
2082        let len = focus.len();
2083        IterMut {
2084            focus,
2085            front_index: 0,
2086            back_index: len,
2087        }
2088    }
2089}
2090
2091impl<'a, A, P: SharedPointerKind> Iterator for IterMut<'a, A, P>
2092where
2093    A: 'a + Clone,
2094{
2095    type Item = &'a mut A;
2096
2097    /// Advance the iterator and return the next value.
2098    ///
2099    /// Time: O(1)*
2100    fn next(&mut self) -> Option<Self::Item> {
2101        if self.front_index >= self.back_index {
2102            return None;
2103        }
2104        let focus: &'a mut FocusMut<'a, A, P> = unsafe { &mut *(&mut self.focus as *mut _) };
2105        let value = focus.get_mut(self.front_index);
2106        self.front_index += 1;
2107        value
2108    }
2109
2110    fn size_hint(&self) -> (usize, Option<usize>) {
2111        let remaining = self.back_index - self.front_index;
2112        (remaining, Some(remaining))
2113    }
2114}
2115
2116impl<'a, A, P: SharedPointerKind> DoubleEndedIterator for IterMut<'a, A, P>
2117where
2118    A: 'a + Clone,
2119{
2120    /// Remove and return an element from the back of the iterator.
2121    ///
2122    /// Time: O(1)*
2123    fn next_back(&mut self) -> Option<Self::Item> {
2124        if self.front_index >= self.back_index {
2125            return None;
2126        }
2127        self.back_index -= 1;
2128        let focus: &'a mut FocusMut<'a, A, P> = unsafe { &mut *(&mut self.focus as *mut _) };
2129        focus.get_mut(self.back_index)
2130    }
2131}
2132
2133impl<'a, A: Clone, P: SharedPointerKind> ExactSizeIterator for IterMut<'a, A, P> {}
2134
2135impl<'a, A: Clone, P: SharedPointerKind> FusedIterator for IterMut<'a, A, P> {}
2136
2137/// A consuming iterator over vectors with values of type `A`.
2138pub struct ConsumingIter<A, P: SharedPointerKind> {
2139    vector: GenericVector<A, P>,
2140}
2141
2142impl<A, P: SharedPointerKind> ConsumingIter<A, P> {
2143    fn new(vector: GenericVector<A, P>) -> Self {
2144        Self { vector }
2145    }
2146}
2147
2148impl<A: Clone, P: SharedPointerKind> Iterator for ConsumingIter<A, P> {
2149    type Item = A;
2150
2151    /// Advance the iterator and return the next value.
2152    ///
2153    /// Time: O(1)*
2154    fn next(&mut self) -> Option<Self::Item> {
2155        self.vector.pop_front()
2156    }
2157
2158    fn size_hint(&self) -> (usize, Option<usize>) {
2159        let len = self.vector.len();
2160        (len, Some(len))
2161    }
2162}
2163
2164impl<A: Clone, P: SharedPointerKind> DoubleEndedIterator for ConsumingIter<A, P> {
2165    /// Remove and return an element from the back of the iterator.
2166    ///
2167    /// Time: O(1)*
2168    fn next_back(&mut self) -> Option<Self::Item> {
2169        self.vector.pop_back()
2170    }
2171}
2172
2173impl<A: Clone, P: SharedPointerKind> ExactSizeIterator for ConsumingIter<A, P> {}
2174
2175impl<A: Clone, P: SharedPointerKind> FusedIterator for ConsumingIter<A, P> {}
2176
2177/// An iterator over the leaf nodes of a vector.
2178///
2179/// To obtain one, use [`Vector::chunks()`][chunks].
2180///
2181/// [chunks]: enum.Vector.html#method.chunks
2182pub struct Chunks<'a, A, P: SharedPointerKind> {
2183    focus: Focus<'a, A, P>,
2184    front_index: usize,
2185    back_index: usize,
2186}
2187
2188impl<'a, A, P: SharedPointerKind> Chunks<'a, A, P> {
2189    fn new(seq: &'a GenericVector<A, P>) -> Self {
2190        Chunks {
2191            focus: seq.focus(),
2192            front_index: 0,
2193            back_index: seq.len(),
2194        }
2195    }
2196}
2197
2198impl<'a, A, P: SharedPointerKind + 'a> Iterator for Chunks<'a, A, P> {
2199    type Item = &'a [A];
2200
2201    /// Advance the iterator and return the next value.
2202    ///
2203    /// Time: O(1)*
2204    fn next(&mut self) -> Option<Self::Item> {
2205        if self.front_index >= self.back_index {
2206            return None;
2207        }
2208        let focus: &'a mut Focus<'a, A, P> = unsafe { &mut *(&mut self.focus as *mut _) };
2209        let (range, value) = focus.chunk_at(self.front_index);
2210        self.front_index = range.end;
2211        Some(value)
2212    }
2213}
2214
2215impl<'a, A, P: SharedPointerKind + 'a> DoubleEndedIterator for Chunks<'a, A, P> {
2216    /// Remove and return an element from the back of the iterator.
2217    ///
2218    /// Time: O(1)*
2219    fn next_back(&mut self) -> Option<Self::Item> {
2220        if self.front_index >= self.back_index {
2221            return None;
2222        }
2223        self.back_index -= 1;
2224        let focus: &'a mut Focus<'a, A, P> = unsafe { &mut *(&mut self.focus as *mut _) };
2225        let (range, value) = focus.chunk_at(self.back_index);
2226        self.back_index = range.start;
2227        Some(value)
2228    }
2229}
2230
2231impl<'a, A, P: SharedPointerKind + 'a> FusedIterator for Chunks<'a, A, P> {}
2232
2233/// A mutable iterator over the leaf nodes of a vector.
2234///
2235/// To obtain one, use [`Vector::chunks_mut()`][chunks_mut].
2236///
2237/// [chunks_mut]: enum.Vector.html#method.chunks_mut
2238pub struct ChunksMut<'a, A, P: SharedPointerKind> {
2239    focus: FocusMut<'a, A, P>,
2240    front_index: usize,
2241    back_index: usize,
2242}
2243
2244impl<'a, A: Clone, P: SharedPointerKind> ChunksMut<'a, A, P> {
2245    fn new(seq: &'a mut GenericVector<A, P>) -> Self {
2246        let len = seq.len();
2247        ChunksMut {
2248            focus: seq.focus_mut(),
2249            front_index: 0,
2250            back_index: len,
2251        }
2252    }
2253}
2254
2255impl<'a, A: Clone, P: SharedPointerKind> Iterator for ChunksMut<'a, A, P> {
2256    type Item = &'a mut [A];
2257
2258    /// Advance the iterator and return the next value.
2259    ///
2260    /// Time: O(1)*
2261    fn next(&mut self) -> Option<Self::Item> {
2262        if self.front_index >= self.back_index {
2263            return None;
2264        }
2265        let focus: &'a mut FocusMut<'a, A, P> = unsafe { &mut *(&mut self.focus as *mut _) };
2266        let (range, value) = focus.chunk_at(self.front_index);
2267        self.front_index = range.end;
2268        Some(value)
2269    }
2270}
2271
2272impl<'a, A: Clone, P: SharedPointerKind> DoubleEndedIterator for ChunksMut<'a, A, P> {
2273    /// Remove and return an element from the back of the iterator.
2274    ///
2275    /// Time: O(1)*
2276    fn next_back(&mut self) -> Option<Self::Item> {
2277        if self.front_index >= self.back_index {
2278            return None;
2279        }
2280        self.back_index -= 1;
2281        let focus: &'a mut FocusMut<'a, A, P> = unsafe { &mut *(&mut self.focus as *mut _) };
2282        let (range, value) = focus.chunk_at(self.back_index);
2283        self.back_index = range.start;
2284        Some(value)
2285    }
2286}
2287
2288impl<'a, A: Clone, P: SharedPointerKind> FusedIterator for ChunksMut<'a, A, P> {}
2289
2290// Proptest
2291#[cfg(any(test, feature = "proptest"))]
2292#[doc(hidden)]
2293pub mod proptest {
2294    #[deprecated(
2295        since = "14.3.0",
2296        note = "proptest strategies have moved to imbl::proptest"
2297    )]
2298    pub use crate::proptest::vector;
2299}
2300
2301// Tests
2302
2303#[cfg(test)]
2304mod test {
2305    use super::*;
2306    use crate::proptest::vector;
2307    use ::proptest::collection::vec;
2308    use ::proptest::num::{i32, usize};
2309    use ::proptest::proptest;
2310    use static_assertions::{assert_impl_all, assert_not_impl_any};
2311
2312    assert_impl_all!(Vector<i32>: Send, Sync);
2313    assert_not_impl_any!(Vector<*const i32>: Send, Sync);
2314    assert_covariant!(Vector<T> in T);
2315
2316    #[test]
2317    fn macro_allows_trailing_comma() {
2318        let vec1 = vector![1, 2, 3];
2319        let vec2 = vector![1, 2, 3,];
2320        assert_eq!(vec1, vec2);
2321    }
2322
2323    #[test]
2324    fn indexing() {
2325        let mut vec: Vector<_> = vector![0, 1, 2, 3, 4, 5];
2326        vec.push_front(0);
2327        assert_eq!(0, *vec.get(0).unwrap());
2328        assert_eq!(0, vec[0]);
2329    }
2330
2331    #[test]
2332    fn test_vector_focus_split_at() {
2333        for (data, split_points) in [
2334            (0..0, vec![0]),
2335            (0..3, vec![0, 1, 2, 3]),
2336            (0..128, vec![0, 1, 64, 127, 128]),
2337            #[cfg(not(miri))]
2338            (0..100_000, vec![0, 1, 50_000, 99_999, 100_000]),
2339        ] {
2340            let imbl_vec = Vector::from_iter(data.clone());
2341            let vec = Vec::from_iter(data);
2342            let focus = imbl_vec.focus();
2343            for split_point in split_points {
2344                let (left, right) = focus.clone().split_at(split_point);
2345                let (expected_left, expected_right) = vec.split_at(split_point);
2346                assert_eq!(
2347                    left.clone().into_iter().copied().collect::<Vec<_>>(),
2348                    expected_left
2349                );
2350                assert_eq!(
2351                    right.clone().into_iter().copied().collect::<Vec<_>>(),
2352                    expected_right
2353                );
2354            }
2355        }
2356    }
2357
2358    #[test]
2359    #[should_panic(expected = "range out of bounds")]
2360    fn test_vector_focus_narrow_out_of_range() {
2361        let vec = Vector::from_iter(0..100);
2362        _ = vec.focus().narrow(..1000);
2363    }
2364
2365    #[test]
2366    fn test_vector_focus_narrow() {
2367        macro_rules! testcase {
2368            ($data:expr, $range:expr) => {{
2369                let imbl_vector = Vector::<_>::from_iter($data);
2370                let vec = Vec::from_iter($data);
2371                let focus = imbl_vector.focus();
2372                assert_eq!(
2373                    focus
2374                        .narrow($range)
2375                        .into_iter()
2376                        .copied()
2377                        .collect::<Vec<_>>(),
2378                    vec[$range]
2379                );
2380            }};
2381        }
2382        // exhaustively test small cases
2383        for len in 0..=3 {
2384            testcase!(0..len, ..);
2385            for start in 0..=len {
2386                testcase!(0..len, start..);
2387                testcase!(0..len, ..start);
2388                for end in start..=len {
2389                    testcase!(0..len, start..end);
2390                }
2391            }
2392        }
2393    }
2394
2395    #[cfg_attr(miri, ignore)]
2396    #[test]
2397    fn large_vector_focus() {
2398        let input = Vector::from_iter(0..100_000);
2399        let vec = input.clone();
2400        let mut sum: i64 = 0;
2401        let mut focus = vec.focus();
2402        for i in 0..input.len() {
2403            sum += *focus.index(i);
2404        }
2405        let expected: i64 = (0..100_000).sum();
2406        assert_eq!(expected, sum);
2407    }
2408
2409    #[cfg_attr(miri, ignore)]
2410    #[test]
2411    fn large_vector_focus_mut() {
2412        let input = Vector::from_iter(0..100_000);
2413        let mut vec = input.clone();
2414        {
2415            let mut focus = vec.focus_mut();
2416            for i in 0..input.len() {
2417                let p = focus.index_mut(i);
2418                *p += 1;
2419            }
2420        }
2421        let expected: Vector<_> = input.into_iter().map(|i| i + 1).collect();
2422        assert_eq!(expected, vec);
2423    }
2424
2425    #[cfg_attr(miri, ignore)]
2426    #[test]
2427    fn issue_55_fwd() {
2428        let mut l = Vector::new();
2429        for i in 0..4098 {
2430            l.append(GenericVector::unit(i));
2431        }
2432        l.append(GenericVector::unit(4098));
2433        assert_eq!(Some(&4097), l.get(4097));
2434        assert_eq!(Some(&4096), l.get(4096));
2435    }
2436
2437    #[cfg_attr(miri, ignore)]
2438    #[test]
2439    fn issue_55_back() {
2440        let mut l = Vector::unit(0);
2441        for i in 0..4099 {
2442            let mut tmp = GenericVector::unit(i + 1);
2443            tmp.append(l);
2444            l = tmp;
2445        }
2446        assert_eq!(Some(&4098), l.get(1));
2447        assert_eq!(Some(&4097), l.get(2));
2448        let len = l.len();
2449        let _ = l.slice(2..len);
2450    }
2451
2452    #[test]
2453    fn issue_55_append() {
2454        let mut vec1 = Vector::from_iter(0..92);
2455        let vec2 = GenericVector::from_iter(0..165);
2456        vec1.append(vec2);
2457    }
2458
2459    #[test]
2460    fn issue_70() {
2461        // This test assumes that chunks are of size 64.
2462        if CHUNK_SIZE != 64 {
2463            return;
2464        }
2465        let mut x = Vector::new();
2466        for _ in 0..262 {
2467            x.push_back(0);
2468        }
2469        for _ in 0..97 {
2470            x.pop_front();
2471        }
2472        for &offset in &[160, 163, 160] {
2473            x.remove(offset);
2474        }
2475        for _ in 0..64 {
2476            x.push_back(0);
2477        }
2478        // At this point middle contains three chunks of size 64, 64 and 1
2479        // respectively. Previously the next `push_back()` would append another
2480        // zero-sized chunk to middle even though there is enough space left.
2481        match x.vector {
2482            VectorInner::Full(ref tree) => {
2483                assert_eq!(129, tree.middle.len());
2484                assert_eq!(3, tree.middle.number_of_children());
2485            }
2486            _ => unreachable!(),
2487        }
2488        x.push_back(0);
2489        match x.vector {
2490            VectorInner::Full(ref tree) => {
2491                assert_eq!(131, tree.middle.len());
2492                assert_eq!(3, tree.middle.number_of_children())
2493            }
2494            _ => unreachable!(),
2495        }
2496        for _ in 0..64 {
2497            x.push_back(0);
2498        }
2499        for _ in x.iter() {}
2500    }
2501
2502    #[cfg_attr(miri, ignore)]
2503    #[test]
2504    fn issue_67() {
2505        let mut l = Vector::unit(4100);
2506        for i in (0..4099).rev() {
2507            let mut tmp = GenericVector::unit(i);
2508            tmp.append(l);
2509            l = tmp;
2510        }
2511        assert_eq!(4100, l.len());
2512        let len = l.len();
2513        let tail = l.slice(1..len);
2514        assert_eq!(1, l.len());
2515        assert_eq!(4099, tail.len());
2516        assert_eq!(Some(&0), l.get(0));
2517        assert_eq!(Some(&1), tail.get(0));
2518    }
2519
2520    #[test]
2521    fn issue_74_simple_size() {
2522        use crate::nodes::rrb::NODE_SIZE;
2523        let mut x = Vector::new();
2524        for _ in 0..(CHUNK_SIZE
2525            * (
2526                1 // inner_f
2527                + (2 * NODE_SIZE) // middle: two full Entry::Nodes (4096 elements each)
2528                + 1 // inner_b
2529                + 1
2530                // outer_b
2531            ))
2532        {
2533            x.push_back(0u32);
2534        }
2535        let middle_first_node_start = CHUNK_SIZE;
2536        let middle_second_node_start = middle_first_node_start + NODE_SIZE * CHUNK_SIZE;
2537        // This reduces the size of the second node to 4095.
2538        x.remove(middle_second_node_start);
2539        // As outer_b is full, this will cause inner_b (length 64) to be pushed
2540        // to middle. The first element will be merged into the second node, the
2541        // remaining 63 elements will end up in a new node.
2542        x.push_back(0u32);
2543        match x.vector {
2544            VectorInner::Full(tree) => {
2545                if CHUNK_SIZE == 64 {
2546                    assert_eq!(3, tree.middle.number_of_children());
2547                }
2548                assert_eq!(
2549                    2 * NODE_SIZE * CHUNK_SIZE + CHUNK_SIZE - 1,
2550                    tree.middle.len()
2551                );
2552            }
2553            _ => unreachable!(),
2554        }
2555    }
2556
2557    #[test]
2558    fn issue_77() {
2559        let mut x = Vector::new();
2560        for _ in 0..44 {
2561            x.push_back(0);
2562        }
2563        for _ in 0..20 {
2564            x.insert(0, 0);
2565        }
2566        x.insert(1, 0);
2567        for _ in 0..441 {
2568            x.push_back(0);
2569        }
2570        for _ in 0..58 {
2571            x.insert(0, 0);
2572        }
2573        x.insert(514, 0);
2574        for _ in 0..73 {
2575            x.push_back(0);
2576        }
2577        for _ in 0..10 {
2578            x.insert(0, 0);
2579        }
2580        x.insert(514, 0);
2581    }
2582
2583    #[cfg_attr(miri, ignore)]
2584    #[test]
2585    fn issue_105() {
2586        let mut v = Vector::<_>::new();
2587
2588        for i in 0..270_000 {
2589            v.push_front(i);
2590        }
2591
2592        while !v.is_empty() {
2593            v = v.take(v.len() - 1);
2594        }
2595    }
2596
2597    #[cfg_attr(miri, ignore)]
2598    #[test]
2599    fn issue_107_split_off_causes_overflow() {
2600        let mut vec = Vector::from_iter(0..4289);
2601        let mut control = Vec::from_iter(0..4289);
2602        let chunk = 64;
2603
2604        while vec.len() >= chunk {
2605            vec = vec.split_off(chunk);
2606            control = control.split_off(chunk);
2607            assert_eq!(vec.len(), control.len());
2608            assert_eq!(control, vec.iter().cloned().collect::<Vec<_>>());
2609        }
2610    }
2611
2612    #[cfg_attr(miri, ignore)]
2613    #[test]
2614    fn collect_crash() {
2615        let _vector: Vector<i32> = (0..5953).collect();
2616        // let _vector: Vector<i32> = (0..16384).collect();
2617    }
2618
2619    #[test]
2620    fn issue_116() {
2621        let vec = Vector::from_iter(0..300);
2622        let rev_vec: Vector<_> = vec.clone().into_iter().rev().collect();
2623        assert_eq!(vec.len(), rev_vec.len());
2624    }
2625
2626    #[test]
2627    fn issue_131() {
2628        let smol = std::iter::repeat(42).take(64).collect::<Vector<_>>();
2629        let mut smol2 = smol.clone();
2630        assert!(smol.ptr_eq(&smol2));
2631        smol2.set(63, 420);
2632        assert!(!smol.ptr_eq(&smol2));
2633
2634        let huge = std::iter::repeat(42).take(65).collect::<Vector<_>>();
2635        let mut huge2 = huge.clone();
2636        assert!(huge.ptr_eq(&huge2));
2637        huge2.set(63, 420);
2638        assert!(!huge.ptr_eq(&huge2));
2639    }
2640
2641    #[test]
2642    fn ptr_eq() {
2643        const MAX: usize = if cfg!(miri) { 64 } else { 256 };
2644        for len in 32..MAX {
2645            let input = std::iter::repeat(42).take(len).collect::<Vector<_>>();
2646            let mut inp2 = input.clone();
2647            assert!(input.ptr_eq(&inp2));
2648            inp2.set(len - 1, 98);
2649            assert_ne!(inp2.get(len - 1), input.get(len - 1));
2650            assert!(!input.ptr_eq(&inp2));
2651        }
2652    }
2653
2654    #[test]
2655    fn full_retain() {
2656        let mut a = Vector::from_iter(0..128);
2657        let b = Vector::from_iter(128..256);
2658        a.append(b);
2659        assert!(matches!(a.vector, Full(_)));
2660        a.retain(|i| *i % 2 == 0);
2661        assert_eq!(a.len(), 128);
2662    }
2663
2664    proptest! {
2665        // Miri is slow, so we ignore long-ish tests to keep the test
2666        // time manageable. For some property tests, it may be worthwhile
2667        // enabling them in miri with reduced iteration counts.
2668        #[cfg_attr(miri, ignore)]
2669        #[test]
2670        fn iter(ref vec in vec(i32::ANY, 0..1000)) {
2671            let seq = Vector::from_iter(vec.iter().cloned());
2672            for (index, item) in seq.iter().enumerate() {
2673                assert_eq!(&vec[index], item);
2674            }
2675            assert_eq!(vec.len(), seq.len());
2676        }
2677
2678        #[cfg_attr(miri, ignore)]
2679        #[test]
2680        fn push_front_mut(ref input in vec(i32::ANY, 0..1000)) {
2681            let mut vector = Vector::new();
2682            for (count, value) in input.iter().cloned().enumerate() {
2683                assert_eq!(count, vector.len());
2684                vector.push_front(value);
2685                assert_eq!(count + 1, vector.len());
2686            }
2687            let input2 = Vec::from_iter(input.iter().rev().cloned());
2688            assert_eq!(input2, Vec::from_iter(vector.iter().cloned()));
2689        }
2690
2691        #[cfg_attr(miri, ignore)]
2692        #[test]
2693        fn push_back_mut(ref input in vec(i32::ANY, 0..1000)) {
2694            let mut vector = Vector::new();
2695            for (count, value) in input.iter().cloned().enumerate() {
2696                assert_eq!(count, vector.len());
2697                vector.push_back(value);
2698                assert_eq!(count + 1, vector.len());
2699            }
2700            assert_eq!(input, &Vec::from_iter(vector.iter().cloned()));
2701        }
2702
2703        #[cfg_attr(miri, ignore)]
2704        #[test]
2705        fn pop_back_mut(ref input in vec(i32::ANY, 0..1000)) {
2706            let mut vector = Vector::from_iter(input.iter().cloned());
2707            assert_eq!(input.len(), vector.len());
2708            for (index, value) in input.iter().cloned().enumerate().rev() {
2709                match vector.pop_back() {
2710                    None => panic!("vector emptied unexpectedly"),
2711                    Some(item) => {
2712                        assert_eq!(index, vector.len());
2713                        assert_eq!(value, item);
2714                    }
2715                }
2716            }
2717            assert_eq!(0, vector.len());
2718        }
2719
2720        #[cfg_attr(miri, ignore)]
2721        #[test]
2722        fn pop_front_mut(ref input in vec(i32::ANY, 0..1000)) {
2723            let mut vector = Vector::from_iter(input.iter().cloned());
2724            assert_eq!(input.len(), vector.len());
2725            for (index, value) in input.iter().cloned().rev().enumerate().rev() {
2726                match vector.pop_front() {
2727                    None => panic!("vector emptied unexpectedly"),
2728                    Some(item) => {
2729                        assert_eq!(index, vector.len());
2730                        assert_eq!(value, item);
2731                    }
2732                }
2733            }
2734            assert_eq!(0, vector.len());
2735        }
2736
2737        // #[test]
2738        // fn push_and_pop(ref input in vec(i32::ANY, 0..1000)) {
2739        //     let mut vector = Vector::new();
2740        //     for (count, value) in input.iter().cloned().enumerate() {
2741        //         assert_eq!(count, vector.len());
2742        //         vector.push_back(value);
2743        //         assert_eq!(count + 1, vector.len());
2744        //     }
2745        //     for (index, value) in input.iter().cloned().rev().enumerate().rev() {
2746        //         match vector.pop_front() {
2747        //             None => panic!("vector emptied unexpectedly"),
2748        //             Some(item) => {
2749        //                 assert_eq!(index, vector.len());
2750        //                 assert_eq!(value, item);
2751        //             }
2752        //         }
2753        //     }
2754        //     assert_eq!(true, vector.is_empty());
2755        // }
2756
2757        #[cfg_attr(miri, ignore)]
2758        #[test]
2759        fn skip(ref vec in vec(i32::ANY, 1..2000), count in usize::ANY) {
2760            let count = count % (vec.len() + 1);
2761            let old = Vector::from_iter(vec.iter().cloned());
2762            let new = old.skip(count);
2763            assert_eq!(old.len(), vec.len());
2764            assert_eq!(new.len(), vec.len() - count);
2765            for (index, item) in old.iter().enumerate() {
2766                assert_eq!(& vec[index], item);
2767            }
2768            for (index, item) in new.iter().enumerate() {
2769                assert_eq!(&vec[count + index], item);
2770            }
2771        }
2772
2773        #[cfg_attr(miri, ignore)]
2774        #[test]
2775        fn split_off(ref vec in vec(i32::ANY, 1..2000), split_pos in usize::ANY) {
2776            let split_index = split_pos % (vec.len() + 1);
2777            let mut left = Vector::from_iter(vec.iter().cloned());
2778            let right = left.split_off(split_index);
2779            assert_eq!(left.len(), split_index);
2780            assert_eq!(right.len(), vec.len() - split_index);
2781            for (index, item) in left.iter().enumerate() {
2782                assert_eq!(& vec[index], item);
2783            }
2784            for (index, item) in right.iter().enumerate() {
2785                assert_eq!(&vec[split_index + index], item);
2786            }
2787        }
2788
2789        #[cfg_attr(miri, ignore)]
2790        #[test]
2791        fn append(ref vec1 in vec(i32::ANY, 0..1000), ref vec2 in vec(i32::ANY, 0..1000)) {
2792            let mut seq1 = Vector::from_iter(vec1.iter().cloned());
2793            let seq2 = Vector::from_iter(vec2.iter().cloned());
2794            assert_eq!(seq1.len(), vec1.len());
2795            assert_eq!(seq2.len(), vec2.len());
2796            seq1.append(seq2);
2797            let mut vec = vec1.clone();
2798            vec.extend(vec2);
2799            assert_eq!(seq1.len(), vec.len());
2800            for (index, item) in seq1.into_iter().enumerate() {
2801                assert_eq!(vec[index], item);
2802            }
2803        }
2804
2805        #[cfg_attr(miri, ignore)]
2806        #[test]
2807        fn iter_mut(ref input in vector(i32::ANY, 0..10000)) {
2808            let mut vec = input.clone();
2809            {
2810                for p in vec.iter_mut() {
2811                    *p = p.overflowing_add(1).0;
2812                }
2813            }
2814            let expected: Vector<i32> = input.clone().into_iter().map(|i| i.overflowing_add(1).0).collect();
2815            assert_eq!(expected, vec);
2816        }
2817
2818        #[cfg_attr(miri, ignore)]
2819        #[test]
2820        fn focus(ref input in vector(i32::ANY, 0..10000)) {
2821            let mut vec = input.clone();
2822            {
2823                let mut focus = vec.focus_mut();
2824                for i in 0..input.len() {
2825                    let p = focus.index_mut(i);
2826                    *p = p.overflowing_add(1).0;
2827                }
2828            }
2829            let expected: Vector<i32> = input.clone().into_iter().map(|i| i.overflowing_add(1).0).collect();
2830            assert_eq!(expected, vec);
2831        }
2832
2833        #[cfg_attr(miri, ignore)]
2834        #[test]
2835        fn focus_mut_split(ref input in vector(i32::ANY, 0..10000)) {
2836            let mut vec = input.clone();
2837
2838            fn split_down(focus: FocusMut<'_, i32, DefaultSharedPtr>) {
2839                let len = focus.len();
2840                if len < 8 {
2841                    for p in focus {
2842                        *p = p.overflowing_add(1).0;
2843                    }
2844                } else {
2845                    let (left, right) = focus.split_at(len / 2);
2846                    split_down(left);
2847                    split_down(right);
2848                }
2849            }
2850
2851            split_down(vec.focus_mut());
2852
2853            let expected: Vector<_> = input.clone().into_iter().map(|i| i.overflowing_add(1).0).collect();
2854            assert_eq!(expected, vec);
2855        }
2856
2857        #[cfg_attr(miri, ignore)]
2858        #[test]
2859        fn chunks(ref input in vector(i32::ANY, 0..10000)) {
2860            let output: Vector<_> = input.leaves().flatten().cloned().collect();
2861            assert_eq!(input, &output);
2862            let rev_in: Vector<_> = input.iter().rev().cloned().collect();
2863            let rev_out: Vector<_> = input.leaves().rev().flat_map(|c| c.iter().rev()).cloned().collect();
2864            assert_eq!(rev_in, rev_out);
2865        }
2866
2867        #[cfg_attr(miri, ignore)]
2868        #[test]
2869        fn chunks_mut(ref mut input_src in vector(i32::ANY, 0..10000)) {
2870            let mut input = input_src.clone();
2871            #[allow(clippy::map_clone)]
2872            let output: Vector<_> = input.leaves_mut().flatten().map(|v| *v).collect();
2873            assert_eq!(input, output);
2874            let rev_in: Vector<_> = input.iter().rev().cloned().collect();
2875            let rev_out: Vector<_> = input.leaves_mut().rev().flat_map(|c| c.iter().rev()).cloned().collect();
2876            assert_eq!(rev_in, rev_out);
2877        }
2878
2879        // The following two tests are very slow and there are unit tests above
2880        // which test for regression of issue #55.  It would still be good to
2881        // run them occasionally.
2882
2883        // #[test]
2884        // fn issue55_back(count in 0..10000, slice_at in usize::ANY) {
2885        //     let count = count as usize;
2886        //     let slice_at = slice_at % count;
2887        //     let mut l = Vector::unit(0);
2888        //     for _ in 0..count {
2889        //         let mut tmp = Vector::unit(0);
2890        //         tmp.append(l);
2891        //         l = tmp;
2892        //     }
2893        //     let len = l.len();
2894        //     l.slice(slice_at..len);
2895        // }
2896
2897        // #[test]
2898        // fn issue55_fwd(count in 0..10000, slice_at in usize::ANY) {
2899        //     let count = count as usize;
2900        //     let slice_at = slice_at % count;
2901        //     let mut l = Vector::new();
2902        //     for i in 0..count {
2903        //         l.append(Vector::unit(i));
2904        //     }
2905        //     assert_eq!(Some(&slice_at), l.get(slice_at));
2906        // }
2907    }
2908}