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