Skip to main content

stable_vec/
lib.rs

1//! A `Vec<T>`-like collection which guarantees stable indices and features
2//! O(1) deletion of elements.
3//!
4//! You can find nearly all the relevant documentation on the type
5//! [`StableVecFacade`]. This is the main type which is configurable over the
6//! core implementation. To use a pre-configured stable vector, use
7//! [`StableVec`].
8//!
9//! This crate uses `#![no_std]` but requires the `alloc` crate.
10//!
11//!
12//! # Why?
13//!
14//! The standard `Vec<T>` always stores all elements contiguously. While this
15//! has many advantages (most notable: cache friendliness), it has the
16//! disadvantage that you can't simply remove an element from the middle; at
17//! least not without shifting all elements after it to the left. And this has
18//! two major drawbacks:
19//!
20//! 1. It has a linear O(n) time complexity
21//! 2. It invalidates all indices of the shifted elements
22//!
23//! Invalidating an index means that a given index `i` who referred to an
24//! element `a` before, now refers to another element `b`. On the contrary, a
25//! *stable* index means, that the index always refers to the same element.
26//!
27//! Stable indices are needed in quite a few situations. One example are graph
28//! data structures (or complex data structures in general). Instead of
29//! allocating heap memory for every node and edge, all nodes and all edges are
30//! stored in a vector (each). But how does the programmer unambiguously refer
31//! to one specific node? A pointer is not possible due to the reallocation
32//! strategy of most dynamically growing arrays (the pointer itself is not
33//! *stable*). Thus, often the index is used.
34//!
35//! But in order to use the index, it has to be stable. This is one example,
36//! where this data structure comes into play.
37//!
38//!
39//! # How?
40//!
41//! We can trade O(1) deletions and stable indices for a higher memory
42//! consumption.
43//!
44//! When `StableVec::remove()` is called, the element is just marked as
45//! "deleted" (and the actual element is dropped), but other than that, nothing
46//! happens. This has the very obvious disadvantage that deleted objects (so
47//! called empty slots) just waste space. This is also the most important thing
48//! to understand:
49//!
50//! The memory requirement of this data structure is `O(|inserted elements|)`;
51//! instead of `O(|inserted elements| - |removed elements|)`. The latter is the
52//! memory requirement of normal `Vec<T>`. Thus, if deletions are far more
53//! numerous than insertions in your situation, then this data structure is
54//! probably not fitting your needs.
55//!
56//!
57//! # Why not?
58//!
59//! As mentioned above, this data structure is rather simple and has many
60//! disadvantages on its own. Here are some reason not to use it:
61//!
62//! - You don't need stable indices or O(1) removal
63//! - Your deletions significantly outnumber your insertions
64//! - You want to choose your keys/indices
65//! - Lookup times do not matter so much to you
66//!
67//! Especially in the last two cases, you could consider using a `HashMap` with
68//! integer keys, best paired with a fast hash function for small keys.
69//!
70//! If you not only want stable indices, but stable pointers, you might want
71//! to use something similar to a linked list. Although: think carefully about
72//! your problem before using a linked list.
73//!
74//!
75//! # Use of `unsafe` in this crate
76//!
77//! Unfortunately, implementing the features of this crate in a fast manner
78//! requires `unsafe`. This was measured in micro-benchmarks (included in this
79//! repository) and on a larger project using this crate. Thus, the use of
80//! `unsafe` is measurement-guided and not just because it was assumed `unsafe`
81//! makes things faster.
82//!
83//! This crate takes great care to ensure that all instances of `unsafe` are
84//! actually safe. All methods on the (low level) `Core` trait have extensive
85//! documentation of preconditions, invariants and postconditions. Comments in
86//! functions usually describe why `unsafe` is safe. This crate contains a
87//! fairly large number of unit tests and some tests with randomized input.
88//! These tests are executed with `miri` to try to catch UB caused by invalid
89//! `unsafe` code.
90//!
91//! That said, of course it cannot be guaranteed this crate is perfectly safe.
92//! If you think you found an instance of incorrect usage of `unsafe` or any
93//! UB, don't hesitate to open an issue immediately. Also, if you find `unsafe`
94//! code that is not necessary and you can show that removing it does not
95//! decrease execution speed, please also open an issue or PR!
96//!
97
98#![deny(missing_debug_implementations)]
99#![deny(broken_intra_doc_links)]
100
101// enable `no_std` for everything except for tests.
102#![cfg_attr(not(test), no_std)]
103extern crate alloc;
104
105
106use ::core::{
107    cmp,
108    fmt,
109    iter::FromIterator,
110    mem,
111    ops::{Index, IndexMut},
112};
113use alloc::vec::Vec;
114
115use crate::{
116    core::{Core, DefaultCore, OwningCore, OptionCore, BitVecCore},
117    iter::{Indices, Iter, IterMut, IntoIter, Values, ValuesMut},
118};
119
120#[cfg(test)]
121mod tests;
122pub mod core;
123pub mod iter;
124
125
126
127/// A stable vector with the default core implementation.
128pub type StableVec<T> = StableVecFacade<T, DefaultCore<T>>;
129
130/// A stable vector which stores the "deleted information" inline. This is very
131/// close to `Vec<Option<T>>`.
132///
133/// This is particularly useful if `T` benefits from "null optimization", i.e.
134/// if `size_of::<T>() == size_of::<Option<T>>()`.
135pub type InlineStableVec<T> = StableVecFacade<T, OptionCore<T>>;
136
137/// A stable vector which stores the "deleted information" externally in a bit
138/// vector.
139pub type ExternStableVec<T> = StableVecFacade<T, BitVecCore<T>>;
140
141
142/// A `Vec<T>`-like collection which guarantees stable indices and features
143/// O(1) deletion of elements.
144///
145///
146/// # Terminology and overview of a stable vector
147///
148/// A stable vector has slots. Each slot can either be filled or empty. There
149/// are three numbers describing a stable vector (each of those functions runs
150/// in O(1)):
151///
152/// - [`capacity()`][StableVecFacade::capacity]: the total number of slots
153///   (filled and empty).
154/// - [`num_elements()`][StableVecFacade::num_elements]: the number of filled
155///   slots.
156/// - [`next_push_index()`][StableVecFacade::next_push_index]: the index of the
157///   first slot (i.e. with the smallest index) that was never filled. This is
158///   the index that is returned by [`push`][StableVecFacade::push]. This
159///   implies that all filled slots have indices smaller than
160///   `next_push_index()`.
161///
162/// Here is an example visualization (with `num_elements = 4`).
163///
164/// ```text
165///      0   1   2   3   4   5   6   7   8   9   10
166///    ┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐
167///    │ a │ - │ b │ c │ - │ - │ d │ - │ - │ - │
168///    └───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘
169///                                      ↑       ↑
170///                        next_push_index       capacity
171/// ```
172///
173/// Unlike `Vec<T>`, `StableVecFacade` allows access to all slots with indices
174/// between 0 and `capacity()`. In particular, it is allowed to call
175/// [`insert`][StableVecFacade::insert] with all indices smaller than
176/// `capacity()`.
177///
178///
179/// # The Core implementation `C`
180///
181/// You might have noticed the type parameter `C`. There are actually multiple
182/// ways how to implement the abstact data structure described above. One might
183/// basically use a `Vec<Option<T>>`. But there are other ways, too.
184///
185/// Most of the time, you can simply use the alias [`StableVec`] which uses the
186/// [`DefaultCore`]. This is fine for almost all cases. That's why all
187/// documentation examples use that type instead of the generic
188/// `StableVecFacade`.
189///
190///
191/// # Implemented traits
192///
193/// This type implements a couple of traits. Some of those implementations
194/// require further explanation:
195///
196/// - `Clone`: the cloned instance is exactly the same as the original,
197///   including empty slots.
198/// - `Extend`, `FromIterator`, `From<AsRef<[T]>>`: these impls work as if all
199///   of the source elements are just `push`ed onto the stable vector in order.
200/// - `PartialEq<Self>`/`Eq`: empty slots, capacity, `next_push_index` and the
201///   indices of elements are all checked. In other words: all observable
202///   properties of the stable vectors need to be the same for them to be
203///   "equal".
204/// - `PartialEq<[B]>`/`PartialEq<Vec<B>>`: capacity, `next_push_index`, empty
205///   slots and indices are ignored for the comparison. It is equivalent to
206///   `sv.iter().eq(vec)`.
207///
208/// # Overview of important methods
209///
210/// (*there are more methods than mentioned in this overview*)
211///
212/// **Creating a stable vector**
213///
214/// - [`new`][StableVecFacade::new]
215/// - [`with_capacity`][StableVecFacade::with_capacity]
216/// - [`FromIterator::from_iter`](#impl-FromIterator<T>)
217///
218/// **Adding and removing elements**
219///
220/// - [`push`][StableVecFacade::push]
221/// - [`insert`][StableVecFacade::insert]
222/// - [`remove`][StableVecFacade::remove]
223///
224/// **Accessing elements**
225///
226/// - [`get`][StableVecFacade::get] and [`get_mut`][StableVecFacade::get_mut]
227///   (returns `Option<&T>` and `Option<&mut T>`)
228/// - [the `[]` index operator](#impl-Index<usize>) (returns `&T` or `&mut T`)
229/// - [`remove`][StableVecFacade::remove] (returns `Option<T>`)
230///
231/// **Stable vector specifics**
232///
233/// - [`has_element_at`][StableVecFacade::has_element_at]
234/// - [`next_push_index`][StableVecFacade::next_push_index]
235/// - [`is_compact`][StableVecFacade::is_compact]
236///
237#[derive(Clone)]
238pub struct StableVecFacade<T, C: Core<T>> {
239    core: OwningCore<T, C>,
240    num_elements: usize,
241}
242
243impl<T, C: Core<T>> StableVecFacade<T, C> {
244    /// Constructs a new, empty stable vector.
245    ///
246    /// The stable-vector will not allocate until elements are pushed onto it.
247    pub fn new() -> Self {
248        Self {
249            core: OwningCore::new(C::new()),
250            num_elements: 0,
251        }
252    }
253
254    /// Constructs a new, empty stable vector with the specified capacity.
255    ///
256    /// The stable-vector will be able to hold exactly `capacity` elements
257    /// without reallocating. If `capacity` is 0, the stable-vector will not
258    /// allocate any memory. See [`reserve`][StableVecFacade::reserve] for more
259    /// information.
260    pub fn with_capacity(capacity: usize) -> Self {
261        let mut out = Self::new();
262        out.reserve_exact(capacity);
263        out
264    }
265
266    /// Inserts the new element `elem` at index `self.next_push_index` and
267    /// returns said index.
268    ///
269    /// The inserted element will always be accessible via the returned index.
270    ///
271    /// This method has an amortized runtime complexity of O(1), just like
272    /// `Vec::push`.
273    ///
274    /// # Example
275    ///
276    /// ```
277    /// # use stable_vec::StableVec;
278    /// let mut sv = StableVec::new();
279    /// let star_idx = sv.push('★');
280    /// let heart_idx = sv.push('♥');
281    ///
282    /// assert_eq!(sv.get(heart_idx), Some(&'♥'));
283    ///
284    /// // After removing the star we can still use the heart's index to access
285    /// // the element!
286    /// sv.remove(star_idx);
287    /// assert_eq!(sv.get(heart_idx), Some(&'♥'));
288    /// ```
289    pub fn push(&mut self, elem: T) -> usize {
290        let index = self.core.len();
291        self.reserve(1);
292
293        unsafe {
294            // Due to `reserve`, the core holds at least one empty slot, so we
295            // know that `index` is smaller than the capacity. We also know
296            // that at `index` there is no element (the definition of `len`
297            // guarantees this).
298            self.core.set_len(index + 1);
299            self.core.insert_at(index, elem);
300        }
301
302        self.num_elements += 1;
303        index
304    }
305
306    /// Inserts the given value at the given index.
307    ///
308    /// If the slot at `index` is empty, the `elem` is inserted at that
309    /// position and `None` is returned. If there is an existing element `x` at
310    /// that position, that element is replaced by `elem` and `Some(x)` is
311    /// returned. The `next_push_index` is adjusted accordingly if `index >=
312    /// next_push_index()`.
313    ///
314    ///
315    /// # Panics
316    ///
317    /// Panics if the index is `>= self.capacity()`.
318    ///
319    /// # Example
320    ///
321    /// ```
322    /// # use stable_vec::StableVec;
323    /// let mut sv = StableVec::new();
324    /// let star_idx = sv.push('★');
325    /// let heart_idx = sv.push('♥');
326    ///
327    /// // Inserting into an empty slot (element was deleted).
328    /// sv.remove(star_idx);
329    /// assert_eq!(sv.num_elements(), 1);
330    /// assert_eq!(sv.insert(star_idx, 'x'), None);
331    /// assert_eq!(sv.num_elements(), 2);
332    /// assert_eq!(sv[star_idx], 'x');
333    ///
334    /// // We can also reserve memory (create new empty slots) and insert into
335    /// // such a new slot. Note that that `next_push_index` gets adjusted.
336    /// sv.reserve_for(5);
337    /// assert_eq!(sv.insert(5, 'y'), None);
338    /// assert_eq!(sv.num_elements(), 3);
339    /// assert_eq!(sv.next_push_index(), 6);
340    /// assert_eq!(sv[5], 'y');
341    ///
342    /// // Inserting into a filled slot replaces the value and returns the old
343    /// // value.
344    /// assert_eq!(sv.insert(heart_idx, 'z'), Some('♥'));
345    /// assert_eq!(sv[heart_idx], 'z');
346    /// ```
347    pub fn insert(&mut self, index: usize, mut elem: T) -> Option<T> {
348        // If the index is out of bounds, we cannot insert the new element.
349        if index >= self.core.cap() {
350            panic!(
351                "`index ({}) >= capacity ({})` in `StableVecFacade::insert`",
352                index,
353                self.core.cap(),
354            );
355        }
356
357        if self.has_element_at(index) {
358            unsafe {
359                // We just checked there is an element at that position, so
360                // this is fine.
361                mem::swap(self.core.get_unchecked_mut(index), &mut elem);
362            }
363            Some(elem)
364        } else {
365            if index >= self.core.len() {
366                // Due to the bounds check above, we know that `index + 1` is ≤
367                // `capacity`.
368                unsafe {
369                    self.core.set_len(index + 1);
370                }
371            }
372
373            unsafe {
374                // `insert_at` requires that `index < cap` and
375                // `!has_element_at(index)`. Both of these conditions are met
376                // by the two explicit checks above.
377                self.core.insert_at(index, elem);
378            }
379
380            self.num_elements += 1;
381
382            None
383        }
384    }
385
386    /// Removes and returns the element at position `index`. If the slot at
387    /// `index` is empty, nothing is changed and `None` is returned.
388    ///
389    /// This simply marks the slot at `index` as empty. The elements after the
390    /// given index are **not** shifted to the left. Thus, the time complexity
391    /// of this method is O(1).
392    ///
393    /// # Panic
394    ///
395    /// Panics if `index >= self.capacity()`.
396    ///
397    /// # Example
398    ///
399    /// ```
400    /// # use stable_vec::StableVec;
401    /// let mut sv = StableVec::new();
402    /// let star_idx = sv.push('★');
403    /// let heart_idx = sv.push('♥');
404    ///
405    /// assert_eq!(sv.remove(star_idx), Some('★'));
406    /// assert_eq!(sv.remove(star_idx), None); // the star was already removed
407    ///
408    /// // We can use the heart's index here. It has not been invalidated by
409    /// // the removal of the star.
410    /// assert_eq!(sv.remove(heart_idx), Some('♥'));
411    /// assert_eq!(sv.remove(heart_idx), None); // the heart was already removed
412    /// ```
413    pub fn remove(&mut self, index: usize) -> Option<T> {
414        // If the index is out of bounds, we cannot insert the new element.
415        if index >= self.core.cap() {
416            panic!(
417                "`index ({}) >= capacity ({})` in `StableVecFacade::remove`",
418                index,
419                self.core.cap(),
420            );
421        }
422
423        if self.has_element_at(index) {
424            // We checked with `Self::has_element_at` that the conditions for
425            // `remove_at` are met.
426            let elem = unsafe {
427                self.core.remove_at(index)
428            };
429
430            self.num_elements -= 1;
431            Some(elem)
432        } else {
433            None
434        }
435    }
436
437    /// Removes all elements from this collection.
438    ///
439    /// After calling this, `num_elements()` will return 0. All indices are
440    /// invalidated. However, no memory is deallocated, so the capacity stays
441    /// as it was before. `self.next_push_index` is 0 after calling this method.
442    ///
443    /// # Example
444    ///
445    /// ```
446    /// # use stable_vec::StableVec;
447    /// let mut sv = StableVec::from(&['a', 'b']);
448    ///
449    /// sv.clear();
450    /// assert_eq!(sv.num_elements(), 0);
451    /// assert!(sv.capacity() >= 2);
452    /// ```
453    pub fn clear(&mut self) {
454        self.core.clear();
455        self.num_elements = 0;
456    }
457
458    /// Returns a reference to the element at the given index, or `None` if
459    /// there exists no element at that index.
460    ///
461    /// If you are calling `unwrap()` on the result of this method anyway,
462    /// rather use the index operator instead: `stable_vec[index]`.
463    pub fn get(&self, index: usize) -> Option<&T> {
464        if self.has_element_at(index) {
465            // We might call this, because we checked both conditions via
466            // `Self::has_element_at`.
467            let elem = unsafe {
468                self.core.get_unchecked(index)
469            };
470            Some(elem)
471        } else {
472            None
473        }
474    }
475
476    /// Returns a mutable reference to the element at the given index, or
477    /// `None` if there exists no element at that index.
478    ///
479    /// If you are calling `unwrap()` on the result of this method anyway,
480    /// rather use the index operator instead: `stable_vec[index]`.
481    pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
482        if self.has_element_at(index) {
483            // We might call this, because we checked both conditions via
484            // `Self::has_element_at`.
485            let elem = unsafe {
486                self.core.get_unchecked_mut(index)
487            };
488            Some(elem)
489        } else {
490            None
491        }
492    }
493
494    /// Returns a reference to the element at the given index without checking
495    /// the index.
496    ///
497    /// # Security
498    ///
499    /// When calling this method `self.has_element_at(index)` has to be `true`,
500    /// otherwise this method's behavior is undefined! This requirement implies
501    /// the requirement `index < self.next_push_index()`.
502    pub unsafe fn get_unchecked(&self, index: usize) -> &T {
503        self.core.get_unchecked(index)
504    }
505
506    /// Returns a mutable reference to the element at the given index without
507    /// checking the index.
508    ///
509    /// # Security
510    ///
511    /// When calling this method `self.has_element_at(index)` has to be `true`,
512    /// otherwise this method's behavior is undefined! This requirement implies
513    /// the requirement `index < self.next_push_index()`.
514    pub unsafe fn get_unchecked_mut(&mut self, index: usize) -> &mut T {
515        self.core.get_unchecked_mut(index)
516    }
517
518    /// Returns `true` if there exists an element at the given index (i.e. the
519    /// slot at `index` is *not* empty), `false` otherwise.
520    ///
521    /// An element is said to exist if the index is not out of bounds and the
522    /// slot at the given index is not empty. In particular, this method can
523    /// also be called with indices larger than the current capacity (although,
524    /// `false` is always returned in those cases).
525    ///
526    /// # Example
527    ///
528    /// ```
529    /// # use stable_vec::StableVec;
530    /// let mut sv = StableVec::new();
531    /// assert!(!sv.has_element_at(3));         // no: index out of bounds
532    ///
533    /// let heart_idx = sv.push('♥');
534    /// assert!(sv.has_element_at(heart_idx));  // yes
535    ///
536    /// sv.remove(heart_idx);
537    /// assert!(!sv.has_element_at(heart_idx)); // no: was removed
538    /// ```
539    pub fn has_element_at(&self, index: usize) -> bool {
540        if index >= self.core.cap() {
541            false
542        } else {
543            unsafe {
544                // The index is smaller than the capacity, as checked aboved,
545                // so we can call this without a problem.
546                self.core.has_element_at(index)
547            }
548        }
549    }
550
551    /// Returns the number of existing elements in this collection.
552    ///
553    /// As long as no element is ever removed, `num_elements()` equals
554    /// `next_push_index()`. Once an element has been removed, `num_elements()`
555    /// will always be less than `next_push_index()` (assuming
556    /// `[reordering_]make_compact()` is not called).
557    ///
558    /// # Example
559    ///
560    /// ```
561    /// # use stable_vec::StableVec;
562    /// let mut sv = StableVec::new();
563    /// assert_eq!(sv.num_elements(), 0);
564    ///
565    /// let heart_idx = sv.push('♥');
566    /// assert_eq!(sv.num_elements(), 1);
567    ///
568    /// sv.remove(heart_idx);
569    /// assert_eq!(sv.num_elements(), 0);
570    /// ```
571    pub fn num_elements(&self) -> usize {
572        self.num_elements
573    }
574
575    /// Returns the index that would be returned by calling
576    /// [`push()`][StableVecFacade::push]. All filled slots have indices below
577    /// `next_push_index()`.
578    ///
579    /// # Example
580    ///
581    /// ```
582    /// # use stable_vec::StableVec;
583    /// let mut sv = StableVec::from(&['a', 'b', 'c']);
584    ///
585    /// let next_push_index = sv.next_push_index();
586    /// let index_of_d = sv.push('d');
587    ///
588    /// assert_eq!(next_push_index, index_of_d);
589    /// ```
590    pub fn next_push_index(&self) -> usize {
591        self.core.len()
592    }
593
594    /// Returns the number of slots in this stable vector.
595    pub fn capacity(&self) -> usize {
596        self.core.cap()
597    }
598
599    /// Returns `true` if this collection doesn't contain any existing
600    /// elements.
601    ///
602    /// This means that `is_empty()` returns true iff no elements were inserted
603    /// *or* all inserted elements were removed again.
604    ///
605    /// # Example
606    ///
607    /// ```
608    /// # use stable_vec::StableVec;
609    /// let mut sv = StableVec::new();
610    /// assert!(sv.is_empty());
611    ///
612    /// let heart_idx = sv.push('♥');
613    /// assert!(!sv.is_empty());
614    ///
615    /// sv.remove(heart_idx);
616    /// assert!(sv.is_empty());
617    /// ```
618    pub fn is_empty(&self) -> bool {
619        self.num_elements == 0
620    }
621
622    /// Returns `true` if all existing elements are stored contiguously from
623    /// the beginning (in other words: there are no empty slots with indices
624    /// below `self.next_push_index()`).
625    ///
626    /// # Example
627    ///
628    /// ```
629    /// # use stable_vec::StableVec;
630    /// let mut sv = StableVec::from(&[0, 1, 2, 3, 4]);
631    /// assert!(sv.is_compact());
632    ///
633    /// sv.remove(1);
634    /// assert!(!sv.is_compact());
635    /// ```
636    pub fn is_compact(&self) -> bool {
637        self.num_elements == self.core.len()
638    }
639
640    /// Returns an iterator over indices and immutable references to the stable
641    /// vector's elements. Elements are yielded in order of their increasing
642    /// indices.
643    ///
644    /// Note that you can also obtain this iterator via the `IntoIterator` impl
645    /// of `&StableVecFacade`.
646    ///
647    /// # Example
648    ///
649    /// ```
650    /// # use stable_vec::StableVec;
651    /// let mut sv = StableVec::from(&[10, 11, 12, 13, 14]);
652    /// sv.remove(1);
653    ///
654    /// let mut it = sv.iter().filter(|&(_, &n)| n <= 13);
655    /// assert_eq!(it.next(), Some((0, &10)));
656    /// assert_eq!(it.next(), Some((2, &12)));
657    /// assert_eq!(it.next(), Some((3, &13)));
658    /// assert_eq!(it.next(), None);
659    /// ```
660    pub fn iter(&self) -> Iter<'_, T, C> {
661        Iter::new(self)
662    }
663
664    /// Returns an iterator over indices and mutable references to the stable
665    /// vector's elements. Elements are yielded in order of their increasing
666    /// indices.
667    ///
668    /// Note that you can also obtain this iterator via the `IntoIterator` impl
669    /// of `&mut StableVecFacade`.
670    ///
671    /// # Example
672    ///
673    /// ```
674    /// # use stable_vec::StableVec;
675    /// let mut sv = StableVec::from(&[10, 11, 12, 13, 14]);
676    /// sv.remove(1);
677    ///
678    /// for (idx, elem) in &mut sv {
679    ///     if idx % 2 == 0 {
680    ///         *elem *= 2;
681    ///     }
682    /// }
683    ///
684    /// assert_eq!(sv, vec![20, 24, 13, 28]);
685    /// ```
686    pub fn iter_mut(&mut self) -> IterMut<'_, T, C> {
687        IterMut::new(self)
688    }
689
690    /// Returns an iterator over immutable references to the existing elements
691    /// of this stable vector. Elements are yielded in order of their
692    /// increasing indices.
693    ///
694    /// # Example
695    ///
696    /// ```
697    /// # use stable_vec::StableVec;
698    /// let mut sv = StableVec::from(&[0, 1, 2, 3, 4]);
699    /// sv.remove(1);
700    ///
701    /// let mut it = sv.values().filter(|&&n| n <= 3);
702    /// assert_eq!(it.next(), Some(&0));
703    /// assert_eq!(it.next(), Some(&2));
704    /// assert_eq!(it.next(), Some(&3));
705    /// assert_eq!(it.next(), None);
706    /// ```
707    pub fn values(&self) -> Values<'_, T, C> {
708        Values::new(self)
709    }
710
711    /// Returns an iterator over mutable references to the existing elements
712    /// of this stable vector. Elements are yielded in order of their
713    /// increasing indices.
714    ///
715    /// Through this iterator, the elements within the stable vector can be
716    /// mutated.
717    ///
718    /// # Examples
719    ///
720    /// ```
721    /// # use stable_vec::StableVec;
722    /// let mut sv = StableVec::from(&[1.0, 2.0, 3.0]);
723    ///
724    /// for e in sv.values_mut() {
725    ///     *e *= 2.0;
726    /// }
727    ///
728    /// assert_eq!(sv, &[2.0, 4.0, 6.0] as &[_]);
729    /// ```
730    pub fn values_mut(&mut self) -> ValuesMut<'_, T, C> {
731        ValuesMut::new(self)
732    }
733
734    /// Returns an iterator over all indices of filled slots of this stable
735    /// vector. Indices are yielded in increasing order.
736    ///
737    /// # Example
738    ///
739    /// ```
740    /// # use stable_vec::StableVec;
741    /// let mut sv = StableVec::from(&['a', 'b', 'c', 'd']);
742    /// sv.remove(1);
743    ///
744    /// let mut it = sv.indices();
745    /// assert_eq!(it.next(), Some(0));
746    /// assert_eq!(it.next(), Some(2));
747    /// assert_eq!(it.next(), Some(3));
748    /// assert_eq!(it.next(), None);
749    /// ```
750    ///
751    /// Simply using the `for`-loop:
752    ///
753    /// ```
754    /// # use stable_vec::StableVec;
755    /// let mut sv = StableVec::from(&['a', 'b', 'c', 'd']);
756    ///
757    /// for index in sv.indices() {
758    ///     println!("index: {}", index);
759    /// }
760    /// ```
761    pub fn indices(&self) -> Indices<'_, T, C> {
762        Indices::new(self)
763    }
764
765    /// Reserves memory for at least `additional` more elements to be inserted
766    /// at indices `>= self.next_push_index()`.
767    ///
768    /// This method might allocate more than `additional` to avoid frequent
769    /// reallocations. Does nothing if the current capacity is already
770    /// sufficient. After calling this method, `self.capacity()` is ≥
771    /// `self.next_push_index() + additional`.
772    ///
773    /// Unlike `Vec::reserve`, the additional reserved memory is not completely
774    /// unaccessible. Instead, additional empty slots are added to this stable
775    /// vector. These can be used just like any other empty slot; in
776    /// particular, you can insert into it.
777    ///
778    /// # Example
779    ///
780    /// ```
781    /// # use stable_vec::StableVec;
782    /// let mut sv = StableVec::new();
783    /// let star_idx = sv.push('★');
784    ///
785    /// // After we inserted one element, the next element would sit at index
786    /// // 1, as expected.
787    /// assert_eq!(sv.next_push_index(), 1);
788    ///
789    /// sv.reserve(2); // insert two empty slots
790    ///
791    /// // `reserve` doesn't change any of this
792    /// assert_eq!(sv.num_elements(), 1);
793    /// assert_eq!(sv.next_push_index(), 1);
794    ///
795    /// // We can now insert an element at index 2.
796    /// sv.insert(2, 'x');
797    /// assert_eq!(sv[2], 'x');
798    ///
799    /// // These values get adjusted accordingly.
800    /// assert_eq!(sv.num_elements(), 2);
801    /// assert_eq!(sv.next_push_index(), 3);
802    /// ```
803    pub fn reserve(&mut self, additional: usize) {
804        #[inline(never)]
805        #[cold]
806        fn capacity_overflow() -> ! {
807            panic!("capacity overflow in `stable_vec::StableVecFacade::reserve` (attempt \
808                to allocate more than `isize::MAX` elements");
809        }
810
811        //:    new_cap = len + additional  ∧  additional >= 0
812        //: => new_cap >= len
813        let new_cap = match self.core.len().checked_add(additional) {
814            None => capacity_overflow(),
815            Some(new_cap) => new_cap,
816        };
817
818        if self.core.cap() < new_cap {
819            // We at least double our capacity. Otherwise repeated `push`es are
820            // O(n²).
821            //
822            // This multiplication can't overflow, because we know the capacity
823            // is `<= isize::MAX`.
824            //
825            //:    new_cap = max(new_cap_before, 2 * cap)
826            //:        ∧ cap >= len
827            //:        ∧ new_cap_before >= len
828            //: => new_cap >= len
829            let new_cap = cmp::max(new_cap, 2 * self.core.cap());
830
831            if new_cap > isize::max_value() as usize {
832                capacity_overflow();
833            }
834
835            //: new_cap >= len  ∧  new_cap <= isize::MAX
836            //
837            // These both properties are exactly the preconditions of
838            // `realloc`, so we can safely call that method.
839            unsafe {
840                self.core.realloc(new_cap);
841            }
842        }
843    }
844
845    /// Reserve enough memory so that there is a slot at `index`. Does nothing
846    /// if `index < self.capacity()`.
847    ///
848    /// This method might allocate more memory than requested to avoid frequent
849    /// allocations. After calling this method, `self.capacity() >= index + 1`.
850    ///
851    ///
852    /// # Example
853    ///
854    /// ```
855    /// # use stable_vec::StableVec;
856    /// let mut sv = StableVec::new();
857    /// let star_idx = sv.push('★');
858    ///
859    /// // Allocate enough memory so that we have a slot at index 5.
860    /// sv.reserve_for(5);
861    /// assert!(sv.capacity() >= 6);
862    ///
863    /// // We can now insert an element at index 5.
864    /// sv.insert(5, 'x');
865    /// assert_eq!(sv[5], 'x');
866    ///
867    /// // This won't do anything as the slot with index 3 already exists.
868    /// let capacity_before = sv.capacity();
869    /// sv.reserve_for(3);
870    /// assert_eq!(sv.capacity(), capacity_before);
871    /// ```
872    pub fn reserve_for(&mut self, index: usize) {
873        if index >= self.capacity() {
874            // Won't underflow as `index >= capacity >= next_push_index`.
875            self.reserve(1 + index - self.next_push_index());
876        }
877    }
878
879    /// Like [`reserve`][StableVecFacade::reserve], but tries to allocate
880    /// memory for exactly `additional` more elements.
881    ///
882    /// The underlying allocator might allocate more memory than requested,
883    /// meaning that you cannot rely on the capacity of this stable vector
884    /// having an exact value after calling this method.
885    pub fn reserve_exact(&mut self, additional: usize) {
886        #[inline(never)]
887        #[cold]
888        fn capacity_overflow() -> ! {
889            panic!("capacity overflow in `stable_vec::StableVecFacade::reserve_exact` (attempt \
890                to allocate more than `isize::MAX` elements");
891        }
892
893        //:    new_cap = len + additional  ∧  additional >= 0
894        //: => new_cap >= len
895        let new_cap = match self.core.len().checked_add(additional) {
896            None => capacity_overflow(),
897            Some(new_cap) => new_cap,
898        };
899
900        if self.core.cap() < new_cap {
901            if new_cap > isize::max_value() as usize {
902                capacity_overflow();
903            }
904
905            //: new_cap >= len  ∧  new_cap <= isize::MAX
906            //
907            // These both properties are exactly the preconditions of
908            // `realloc`, so we can safely call that method.
909            unsafe {
910                self.core.realloc(new_cap);
911            }
912        }
913    }
914
915    /// Removes and returns the first element from this collection, or `None`
916    /// if it's empty.
917    ///
918    /// This method uses exactly the same deletion strategy as
919    /// [`remove()`][StableVecFacade::remove].
920    ///
921    /// # Example
922    ///
923    /// ```
924    /// # use stable_vec::StableVec;
925    /// let mut sv = StableVec::from(&[1, 2, 3]);
926    /// assert_eq!(sv.remove_first(), Some(1));
927    /// assert_eq!(sv, vec![2, 3]);
928    /// ```
929    ///
930    /// # Note
931    ///
932    /// This method needs to find the index of the first valid element. Finding
933    /// it has a worst case time complexity of O(n). If you already know the
934    /// index, use [`remove()`][StableVecFacade::remove] instead.
935    pub fn remove_first(&mut self) -> Option<T> {
936        self.find_first_index().and_then(|index| self.remove(index))
937    }
938
939    /// Removes and returns the last element from this collection, or `None` if
940    /// it's empty.
941    ///
942    /// This method uses exactly the same deletion strategy as
943    /// [`remove()`][StableVecFacade::remove].
944    ///
945    /// # Example
946    ///
947    /// ```
948    /// # use stable_vec::StableVec;
949    /// let mut sv = StableVec::from(&[1, 2, 3]);
950    /// assert_eq!(sv.remove_last(), Some(3));
951    /// assert_eq!(sv, vec![1, 2]);
952    /// ```
953    ///
954    /// # Note
955    ///
956    /// This method needs to find the index of the last valid element. Finding
957    /// it has a worst case time complexity of O(n). If you already know the
958    /// index, use [`remove()`][StableVecFacade::remove] instead.
959    pub fn remove_last(&mut self) -> Option<T> {
960        self.find_last_index().and_then(|index| self.remove(index))
961    }
962
963    /// Finds the first element and returns a reference to it, or `None` if
964    /// the stable vector is empty.
965    ///
966    /// This method has a worst case time complexity of O(n).
967    ///
968    /// # Example
969    ///
970    /// ```
971    /// # use stable_vec::StableVec;
972    /// let mut sv = StableVec::from(&[1, 2]);
973    /// sv.remove(0);
974    /// assert_eq!(sv.find_first(), Some(&2));
975    /// ```
976    pub fn find_first(&self) -> Option<&T> {
977        self.find_first_index().map(|index| unsafe { self.core.get_unchecked(index) })
978    }
979
980    /// Finds the first element and returns a mutable reference to it, or
981    /// `None` if the stable vector is empty.
982    ///
983    /// This method has a worst case time complexity of O(n).
984    ///
985    /// # Example
986    ///
987    /// ```
988    /// # use stable_vec::StableVec;
989    /// let mut sv = StableVec::from(&[1, 2]);
990    /// {
991    ///     let first = sv.find_first_mut().unwrap();
992    ///     assert_eq!(*first, 1);
993    ///
994    ///     *first = 3;
995    /// }
996    /// assert_eq!(sv, vec![3, 2]);
997    /// ```
998    pub fn find_first_mut(&mut self) -> Option<&mut T> {
999        self.find_first_index().map(move |index| unsafe { self.core.get_unchecked_mut(index) })
1000    }
1001
1002    /// Finds the last element and returns a reference to it, or `None` if
1003    /// the stable vector is empty.
1004    ///
1005    /// This method has a worst case time complexity of O(n).
1006    ///
1007    /// # Example
1008    ///
1009    /// ```
1010    /// # use stable_vec::StableVec;
1011    /// let mut sv = StableVec::from(&[1, 2]);
1012    /// sv.remove(1);
1013    /// assert_eq!(sv.find_last(), Some(&1));
1014    /// ```
1015    pub fn find_last(&self) -> Option<&T> {
1016        self.find_last_index().map(|index| unsafe { self.core.get_unchecked(index) })
1017    }
1018
1019    /// Finds the last element and returns a mutable reference to it, or `None`
1020    /// if the stable vector is empty.
1021    ///
1022    /// This method has a worst case time complexity of O(n).
1023    ///
1024    /// # Example
1025    ///
1026    /// ```
1027    /// # use stable_vec::StableVec;
1028    /// let mut sv = StableVec::from(&[1, 2]);
1029    /// {
1030    ///     let last = sv.find_last_mut().unwrap();
1031    ///     assert_eq!(*last, 2);
1032    ///
1033    ///     *last = 3;
1034    /// }
1035    /// assert_eq!(sv, vec![1, 3]);
1036    /// ```
1037    pub fn find_last_mut(&mut self) -> Option<&mut T> {
1038        self.find_last_index().map(move |index| unsafe { self.core.get_unchecked_mut(index) })
1039    }
1040
1041    /// Performs a forwards search starting at index `start`, returning the
1042    /// index of the first filled slot that is found.
1043    ///
1044    /// Specifically, if an element at index `start` exists, `Some(start)` is
1045    /// returned. If all slots with indices `start` and higher are empty (or
1046    /// don't exist), `None` is returned. This method can be used to iterate
1047    /// over all existing elements without an iterator object.
1048    ///
1049    /// The inputs `start >= self.next_push_index()` are only allowed for
1050    /// convenience. For those `start` values, `None` is always returned.
1051    ///
1052    /// # Panics
1053    ///
1054    /// Panics if `start > self.capacity()`. Note: `start == self.capacity()`
1055    /// is allowed for convenience, but always returns `None`.
1056    ///
1057    /// # Example
1058    ///
1059    /// ```
1060    /// # use stable_vec::StableVec;
1061    /// let mut sv = StableVec::from(&[0, 1, 2, 3, 4]);
1062    /// sv.remove(1);
1063    /// sv.remove(2);
1064    /// sv.remove(4);
1065    ///
1066    /// assert_eq!(sv.first_filled_slot_from(0), Some(0));
1067    /// assert_eq!(sv.first_filled_slot_from(1), Some(3));
1068    /// assert_eq!(sv.first_filled_slot_from(2), Some(3));
1069    /// assert_eq!(sv.first_filled_slot_from(3), Some(3));
1070    /// assert_eq!(sv.first_filled_slot_from(4), None);
1071    /// assert_eq!(sv.first_filled_slot_from(5), None);
1072    /// ```
1073    pub fn first_filled_slot_from(&self, start: usize) -> Option<usize> {
1074        if start > self.core.cap() {
1075            panic!(
1076                "`start` is {}, but capacity is {} in `first_filled_slot_from`",
1077                start,
1078                self.capacity(),
1079            );
1080        } else {
1081            // The precondition `start <= self.core.cap()` is satisfied.
1082            unsafe { self.core.first_filled_slot_from(start) }
1083        }
1084    }
1085
1086    /// Performs a backwards search starting at index `start - 1`, returning
1087    /// the index of the first filled slot that is found. For `start == 0`,
1088    /// `None` is returned.
1089    ///
1090    /// Note: passing in `start >= self.len()` just wastes time, as those slots
1091    /// are never filled.
1092    ///
1093    /// # Panics
1094    ///
1095    /// Panics if `start > self.capacity()`. Note: `start == self.capacity()`
1096    /// is allowed for convenience, but wastes time.
1097    ///
1098    /// # Example
1099    ///
1100    /// ```
1101    /// # use stable_vec::StableVec;
1102    /// let mut sv = StableVec::from(&[0, 1, 2, 3, 4]);
1103    /// sv.remove(0);
1104    /// sv.remove(2);
1105    /// sv.remove(3);
1106    ///
1107    /// assert_eq!(sv.first_filled_slot_below(0), None);
1108    /// assert_eq!(sv.first_filled_slot_below(1), None);
1109    /// assert_eq!(sv.first_filled_slot_below(2), Some(1));
1110    /// assert_eq!(sv.first_filled_slot_below(3), Some(1));
1111    /// assert_eq!(sv.first_filled_slot_below(4), Some(1));
1112    /// assert_eq!(sv.first_filled_slot_below(5), Some(4));
1113    /// ```
1114    pub fn first_filled_slot_below(&self, start: usize) -> Option<usize> {
1115        if start > self.core.cap() {
1116            panic!(
1117                "`start` is {}, but capacity is {} in `first_filled_slot_below`",
1118                start,
1119                self.capacity(),
1120            );
1121        } else {
1122            // The precondition `start <= self.core.cap()` is satisfied.
1123            unsafe { self.core.first_filled_slot_below(start) }
1124        }
1125    }
1126
1127    /// Performs a forwards search starting at index `start`, returning the
1128    /// index of the first empty slot that is found.
1129    ///
1130    /// Specifically, if the slot at index `start` is empty, `Some(start)` is
1131    /// returned. If all slots with indices `start` and higher are filled,
1132    /// `None` is returned.
1133    ///
1134    ///
1135    /// # Panics
1136    ///
1137    /// Panics if `start > self.capacity()`. Note: `start == self.capacity()`
1138    /// is allowed for convenience, but always returns `None`.
1139    ///
1140    /// # Example
1141    ///
1142    /// ```
1143    /// # use stable_vec::StableVec;
1144    /// let mut sv = StableVec::from(&[0, 1, 2, 3, 4, 5]);
1145    /// sv.remove(1);
1146    /// sv.remove(2);
1147    /// sv.remove(4);
1148    ///
1149    /// assert_eq!(sv.first_empty_slot_from(0), Some(1));
1150    /// assert_eq!(sv.first_empty_slot_from(1), Some(1));
1151    /// assert_eq!(sv.first_empty_slot_from(2), Some(2));
1152    /// assert_eq!(sv.first_empty_slot_from(3), Some(4));
1153    /// assert_eq!(sv.first_empty_slot_from(4), Some(4));
1154    ///
1155    /// // Make sure we have at least one empty slot at the end
1156    /// sv.reserve_for(6);
1157    /// assert_eq!(sv.first_empty_slot_from(5), Some(6));
1158    /// assert_eq!(sv.first_empty_slot_from(6), Some(6));
1159    /// ```
1160    pub fn first_empty_slot_from(&self, start: usize) -> Option<usize> {
1161        if start > self.core.cap() {
1162            panic!(
1163                "`start` is {}, but capacity is {} in `first_empty_slot_from`",
1164                start,
1165                self.capacity(),
1166            );
1167        } else {
1168            unsafe { self.core.first_empty_slot_from(start) }
1169        }
1170    }
1171
1172    /// Performs a backwards search starting at index `start - 1`, returning
1173    /// the index of the first empty slot that is found. For `start == 0`,
1174    /// `None` is returned.
1175    ///
1176    /// If all slots with indices below `start` are filled, `None` is returned.
1177    ///
1178    /// # Example
1179    ///
1180    /// ```
1181    /// # use stable_vec::StableVec;
1182    /// let mut sv = StableVec::from(&[0, 1, 2, 3, 4, 5]);
1183    /// sv.remove(1);
1184    /// sv.remove(2);
1185    /// sv.remove(4);
1186    ///
1187    /// assert_eq!(sv.first_empty_slot_below(0), None);
1188    /// assert_eq!(sv.first_empty_slot_below(1), None);
1189    /// assert_eq!(sv.first_empty_slot_below(2), Some(1));
1190    /// assert_eq!(sv.first_empty_slot_below(3), Some(2));
1191    /// assert_eq!(sv.first_empty_slot_below(4), Some(2));
1192    /// assert_eq!(sv.first_empty_slot_below(5), Some(4));
1193    /// assert_eq!(sv.first_empty_slot_below(6), Some(4));
1194    /// ```
1195    pub fn first_empty_slot_below(&self, start: usize) -> Option<usize> {
1196        if start > self.core.cap() {
1197            panic!(
1198                "`start` is {}, but capacity is {} in `first_empty_slot_below`",
1199                start,
1200                self.capacity(),
1201            );
1202        } else {
1203            unsafe { self.core.first_empty_slot_below(start) }
1204        }
1205    }
1206
1207
1208    /// Finds the first element and returns its index, or `None` if the stable
1209    /// vector is empty.
1210    ///
1211    /// This method has a worst case time complexity of O(n).
1212    ///
1213    /// # Example
1214    ///
1215    /// ```
1216    /// # use stable_vec::StableVec;
1217    /// let mut sv = StableVec::from(&[1, 2]);
1218    /// sv.remove(0);
1219    /// assert_eq!(sv.find_first_index(), Some(1));
1220    /// ```
1221    pub fn find_first_index(&self) -> Option<usize> {
1222        // `0 <= self.core.cap()` is always true
1223        unsafe {
1224            self.core.first_filled_slot_from(0)
1225        }
1226    }
1227
1228    /// Finds the last element and returns its index, or `None` if the stable
1229    /// vector is empty.
1230    ///
1231    /// This method has a worst case time complexity of O(n).
1232    ///
1233    /// # Example
1234    ///
1235    /// ```
1236    /// # use stable_vec::StableVec;
1237    /// let mut sv = StableVec::from(&[1, 2]);
1238    /// sv.remove(1);
1239    /// assert_eq!(sv.find_last_index(), Some(0));
1240    /// ```
1241    pub fn find_last_index(&self) -> Option<usize> {
1242        // `self.core.len() <= self.core.cap()` is always true
1243        unsafe {
1244            self.core.first_filled_slot_below(self.core.len())
1245        }
1246    }
1247
1248    /// Reallocates to have a capacity as small as possible while still holding
1249    /// `self.next_push_index()` slots.
1250    ///
1251    /// Note that this does not move existing elements around and thus does not
1252    /// invalidate indices. This method also doesn't change what
1253    /// `next_push_index` returns. Instead, only the capacity is changed. Due
1254    /// to the underlying allocator, it cannot be guaranteed that the capacity
1255    /// is exactly `self.next_push_index()` after calling this method.
1256    ///
1257    /// If you want to compact this stable vector by removing deleted elements,
1258    /// use the method [`make_compact`][StableVecFacade::make_compact] or
1259    /// [`reordering_make_compact`][StableVecFacade::reordering_make_compact]
1260    /// instead.
1261    pub fn shrink_to_fit(&mut self) {
1262        // `realloc` has the following preconditions:
1263        // - (a) `new_cap ≥ self.len()`
1264        // - (b) `new_cap ≤ isize::MAX`
1265        //
1266        // It's trivial to see that (a) is not violated here. (b) is also never
1267        // violated, because the `Core` trait says that `len < cap` and `cap <
1268        // isize::MAX`.
1269        unsafe {
1270            let new_cap = self.core.len();
1271            self.core.realloc(new_cap);
1272        }
1273    }
1274
1275    /// Rearranges elements to reclaim memory. **Invalidates indices!**
1276    ///
1277    /// After calling this method, all existing elements stored contiguously in
1278    /// memory. You might want to call [`shrink_to_fit()`][StableVecFacade::shrink_to_fit]
1279    /// afterwards to actually free memory previously used by removed elements.
1280    /// This method itself does not deallocate any memory.
1281    ///
1282    /// The `next_push_index` value is also changed by this method (if the
1283    /// stable vector wasn't compact before).
1284    ///
1285    /// In comparison to
1286    /// [`reordering_make_compact()`][StableVecFacade::reordering_make_compact],
1287    /// this method does not change the order of elements. Due to this, this
1288    /// method is a bit slower.
1289    ///
1290    /// # Warning
1291    ///
1292    /// This method invalidates the indices of all elements that are stored
1293    /// after the first empty slot in the stable vector!
1294    pub fn make_compact(&mut self) {
1295        if self.is_compact() {
1296            return;
1297        }
1298
1299        // We only have to move elements, if we have any.
1300        if self.num_elements > 0 {
1301            unsafe {
1302                // We have to find the position of the first hole. We know that
1303                // there is at least one hole, so we can unwrap.
1304                let first_hole_index = self.core.first_empty_slot_from(0).unwrap();
1305
1306                // This variable will store the first possible index of an element
1307                // which can be inserted in the hole.
1308                let mut element_index = first_hole_index + 1;
1309
1310                // Beginning from the first hole, we have to fill each index with
1311                // a new value. This is required to keep the order of elements.
1312                for hole_index in first_hole_index..self.num_elements {
1313                    // Actually find the next element which we can use to fill the
1314                    // hole. Note that we do not check if `element_index` runs out
1315                    // of bounds. This will never happen! We do have enough
1316                    // elements to fill all holes. And once all holes are filled,
1317                    // the outer loop will stop.
1318                    while !self.core.has_element_at(element_index) {
1319                        element_index += 1;
1320                    }
1321
1322                    // So at this point `hole_index` points to a valid hole and
1323                    // `element_index` points to a valid element. Time to swap!
1324                    self.core.swap(hole_index, element_index);
1325                }
1326            }
1327        }
1328
1329        // We can safely call `set_len()` here: all elements are in the
1330        // range 0..self.num_elements.
1331        unsafe {
1332            self.core.set_len(self.num_elements);
1333        }
1334    }
1335
1336    /// Rearranges elements to reclaim memory. **Invalidates indices and
1337    /// changes the order of the elements!**
1338    ///
1339    /// After calling this method, all existing elements stored contiguously
1340    /// in memory. You might want to call [`shrink_to_fit()`][StableVecFacade::shrink_to_fit]
1341    /// afterwards to actually free memory previously used by removed elements.
1342    /// This method itself does not deallocate any memory.
1343    ///
1344    /// The `next_push_index` value is also changed by this method (if the
1345    /// stable vector wasn't compact before).
1346    ///
1347    /// If you do need to preserve the order of elements, use
1348    /// [`make_compact()`][StableVecFacade::make_compact] instead. However, if
1349    /// you don't care about element order, you should prefer using this
1350    /// method, because it is faster.
1351    ///
1352    /// # Warning
1353    ///
1354    /// This method invalidates the indices of all elements that are stored
1355    /// after the first hole and it does not preserve the order of elements!
1356    pub fn reordering_make_compact(&mut self) {
1357        if self.is_compact() {
1358            return;
1359        }
1360
1361        // We only have to move elements, if we have any.
1362        if self.num_elements > 0 {
1363            unsafe {
1364                // We use two indices:
1365                //
1366                // - `hole_index` starts from the front and searches for a hole
1367                //   that can be filled with an element.
1368                // - `element_index` starts from the back and searches for an
1369                //   element.
1370                let len = self.core.len();
1371                let mut element_index = len;
1372                let mut hole_index = 0;
1373                loop {
1374                    element_index = self.core.first_filled_slot_below(element_index).unwrap_or(0);
1375                    hole_index = self.core.first_empty_slot_from(hole_index).unwrap_or(len);
1376
1377                    // If both indices passed each other, we can stop. There are no
1378                    // holes left of `hole_index` and no element right of
1379                    // `element_index`.
1380                    if hole_index > element_index {
1381                        break;
1382                    }
1383
1384                    // We found an element and a hole left of the element. That
1385                    // means that we can swap.
1386                    self.core.swap(hole_index, element_index);
1387                }
1388            }
1389        }
1390
1391        // We can safely call `set_len()` here: all elements are in the
1392        // range 0..self.num_elements.
1393        unsafe {
1394            self.core.set_len(self.num_elements);
1395        }
1396    }
1397
1398    /// Returns `true` if the stable vector contains an element with the given
1399    /// value, `false` otherwise.
1400    ///
1401    /// ```
1402    /// # use stable_vec::StableVec;
1403    /// let mut sv = StableVec::from(&['a', 'b', 'c']);
1404    /// assert!(sv.contains(&'b'));
1405    ///
1406    /// sv.remove(1);   // 'b' is stored at index 1
1407    /// assert!(!sv.contains(&'b'));
1408    /// ```
1409    pub fn contains<U>(&self, item: &U) -> bool
1410    where
1411        U: PartialEq<T>,
1412    {
1413        self.values().any(|e| item == e)
1414    }
1415
1416    /// Swaps the slot at index `a` with the slot at index `b`.
1417    ///
1418    /// The full slots are swapped, including the element and the "filled"
1419    /// state. If you swap slots with an element in it, that element's index is
1420    /// invalidated, of course. This method automatically sets
1421    /// `next_push_index` to a larger value if that's necessary.
1422    ///
1423    /// # Panics
1424    ///
1425    /// This panics if `a` or `b` are not smaller than `self.capacity()`.
1426    ///
1427    /// # Example
1428    ///
1429    /// ```
1430    /// # use stable_vec::StableVec;
1431    /// let mut sv = StableVec::from(&['a', 'b', 'c', 'd']);
1432    /// sv.reserve_for(5);
1433    /// assert_eq!(sv.next_push_index(), 4);
1434    ///
1435    /// // Swapping an empty slot with a filled one
1436    /// sv.swap(0, 5);
1437    /// assert_eq!(sv.get(0), None);
1438    /// assert_eq!(sv.get(1), Some(&'b'));
1439    /// assert_eq!(sv.get(2), Some(&'c'));
1440    /// assert_eq!(sv.get(3), Some(&'d'));
1441    /// assert_eq!(sv.get(4), None);
1442    /// assert_eq!(sv.get(5), Some(&'a'));
1443    /// assert_eq!(sv.next_push_index(), 6);
1444    ///
1445    /// // Swapping two filled slots
1446    /// sv.swap(1, 2);
1447    /// assert_eq!(sv.get(0), None);
1448    /// assert_eq!(sv.get(1), Some(&'c'));
1449    /// assert_eq!(sv.get(2), Some(&'b'));
1450    /// assert_eq!(sv.get(3), Some(&'d'));
1451    /// assert_eq!(sv.get(4), None);
1452    /// assert_eq!(sv.get(5), Some(&'a'));
1453    ///
1454    /// // You can also swap two empty slots, but that doesn't change anything.
1455    /// sv.swap(0, 4);
1456    /// assert_eq!(sv.get(0), None);
1457    /// assert_eq!(sv.get(1), Some(&'c'));
1458    /// assert_eq!(sv.get(2), Some(&'b'));
1459    /// assert_eq!(sv.get(3), Some(&'d'));
1460    /// assert_eq!(sv.get(4), None);
1461    /// assert_eq!(sv.get(5), Some(&'a'));
1462    /// ```
1463    pub fn swap(&mut self, a: usize, b: usize) {
1464        assert!(a < self.core.cap());
1465        assert!(b < self.core.cap());
1466
1467        // Adjust the `len`
1468        let mut len = self.core.len();
1469        if a >= len && self.has_element_at(b) {
1470            len = a + 1;
1471        }
1472        if b >= len && self.has_element_at(a) {
1473            len = b + 1;
1474        }
1475
1476        // Both indices are less than `cap`. These indices + 1 are <= cap. And
1477        // all slots with indices > `len` are empty.
1478        unsafe { self.core.set_len(len) };
1479
1480        // With the asserts above we made sure the preconditions are met. The
1481        // maintain the core invariants, we increased the length.
1482        unsafe { self.core.swap(a, b) };
1483
1484    }
1485
1486    /// Retains only the elements specified by the given predicate.
1487    ///
1488    /// Each element `e` for which `should_be_kept(&e)` returns `false` is
1489    /// removed from the stable vector.
1490    ///
1491    /// # Example
1492    ///
1493    /// ```
1494    /// # use stable_vec::StableVec;
1495    /// let mut sv = StableVec::from(&[1, 2, 3, 4, 5]);
1496    /// sv.retain(|&e| e % 2 == 0);
1497    ///
1498    /// assert_eq!(sv, &[2, 4] as &[_]);
1499    /// ```
1500    pub fn retain<P>(&mut self, mut should_be_kept: P)
1501    where
1502        P: FnMut(&T) -> bool,
1503    {
1504        let mut pos = 0;
1505
1506        // These unsafe calls are fine: indices returned by
1507        // `first_filled_slot_from` are always valid and point to an existing
1508        // element.
1509        unsafe {
1510            while let Some(idx) = self.core.first_filled_slot_from(pos) {
1511                let elem = self.core.get_unchecked(idx);
1512                if !should_be_kept(elem) {
1513                    self.core.remove_at(idx);
1514                    self.num_elements -= 1;
1515                }
1516
1517                pos = idx + 1;
1518            }
1519        }
1520    }
1521
1522    /// Retains only the elements with indices specified by the given
1523    /// predicate.
1524    ///
1525    /// Each element with index `i` for which `should_be_kept(i)` returns
1526    /// `false` is removed from the stable vector.
1527    ///
1528    /// # Example
1529    ///
1530    /// ```
1531    /// # use stable_vec::StableVec;
1532    /// let mut sv = StableVec::new();
1533    /// sv.push(1);
1534    /// let two = sv.push(2);
1535    /// sv.push(3);
1536    /// sv.retain_indices(|i| i == two);
1537    ///
1538    /// assert_eq!(sv, &[2] as &[_]);
1539    /// ```
1540    pub fn retain_indices<P>(&mut self, mut should_be_kept: P)
1541    where
1542        P: FnMut(usize) -> bool,
1543    {
1544        let mut pos = 0;
1545
1546        // These unsafe call is fine: indices returned by
1547        // `first_filled_slot_from` are always valid and point to an existing
1548        // element.
1549        unsafe {
1550            while let Some(idx) = self.core.first_filled_slot_from(pos) {
1551                if !should_be_kept(idx) {
1552                    self.core.remove_at(idx);
1553                    self.num_elements -= 1;
1554                }
1555
1556                pos = idx + 1;
1557            }
1558        }
1559    }
1560
1561    /// Appends all elements in `new_elements` to this stable vector. This is
1562    /// equivalent to calling [`push()`][StableVecFacade::push] for each
1563    /// element.
1564    pub fn extend_from_slice(&mut self, new_elements: &[T])
1565    where
1566        T: Clone,
1567    {
1568        let len = new_elements.len();
1569
1570        self.reserve(len);
1571        self.num_elements += len;
1572
1573        // It's important that a panic in `clone()` does not lead to memory
1574        // unsafety! The only way that could happen is if some uninitialized
1575        // values would be read when `out` is dropped. However, this won't
1576        // happen: the core won't ever drop uninitialized elements.
1577        //
1578        // So that's good. But we also would like to drop all elements that
1579        // have already been inserted. That's why we set the length first.
1580        unsafe {
1581            let mut i = self.core.len();
1582            let new_len = self.core.len() + len;
1583            self.core.set_len(new_len);
1584
1585            for elem in new_elements {
1586                self.core.insert_at(i, elem.clone());
1587                i += 1;
1588            }
1589        }
1590    }
1591}
1592
1593
1594#[inline(never)]
1595#[cold]
1596fn index_fail(idx: usize) -> ! {
1597    panic!("attempt to index StableVec with index {}, but no element exists at that index", idx);
1598}
1599
1600impl<T, C: Core<T>> Index<usize> for StableVecFacade<T, C> {
1601    type Output = T;
1602
1603    fn index(&self, index: usize) -> &T {
1604        match self.get(index) {
1605            Some(v) => v,
1606            None => index_fail(index),
1607        }
1608    }
1609}
1610
1611impl<T, C: Core<T>> IndexMut<usize> for StableVecFacade<T, C> {
1612    fn index_mut(&mut self, index: usize) -> &mut T {
1613        match self.get_mut(index) {
1614            Some(v) => v,
1615            None => index_fail(index),
1616        }
1617    }
1618}
1619
1620impl<T, C: Core<T>> Default for StableVecFacade<T, C> {
1621    fn default() -> Self {
1622        Self::new()
1623    }
1624}
1625
1626impl<T, S, C: Core<T>> From<S> for StableVecFacade<T, C>
1627where
1628    S: AsRef<[T]>,
1629    T: Clone,
1630{
1631    fn from(slice: S) -> Self {
1632        let mut out = Self::new();
1633        out.extend_from_slice(slice.as_ref());
1634        out
1635    }
1636}
1637
1638impl<T, C: Core<T>> FromIterator<T> for StableVecFacade<T, C> {
1639    fn from_iter<I>(iter: I) -> Self
1640    where
1641        I: IntoIterator<Item = T>,
1642    {
1643        let mut out = Self::new();
1644        out.extend(iter);
1645        out
1646    }
1647}
1648
1649impl<T, C: Core<T>> Extend<T> for StableVecFacade<T, C> {
1650    fn extend<I>(&mut self, iter: I)
1651    where
1652        I: IntoIterator<Item = T>,
1653    {
1654        let it = iter.into_iter();
1655        self.reserve(it.size_hint().0);
1656
1657        for elem in it {
1658            self.push(elem);
1659        }
1660    }
1661}
1662
1663impl<'a, T, C: Core<T>> IntoIterator for &'a StableVecFacade<T, C> {
1664    type Item = (usize, &'a T);
1665    type IntoIter = Iter<'a, T, C>;
1666    fn into_iter(self) -> Self::IntoIter {
1667        self.iter()
1668    }
1669}
1670
1671impl<'a, T, C: Core<T>> IntoIterator for &'a mut StableVecFacade<T, C> {
1672    type Item = (usize, &'a mut T);
1673    type IntoIter = IterMut<'a, T, C>;
1674    fn into_iter(self) -> Self::IntoIter {
1675        self.iter_mut()
1676    }
1677}
1678
1679impl<T, C: Core<T>> IntoIterator for StableVecFacade<T, C> {
1680    type Item = (usize, T);
1681    type IntoIter = IntoIter<T, C>;
1682    fn into_iter(self) -> Self::IntoIter {
1683        IntoIter::new(self)
1684    }
1685}
1686
1687impl<T: fmt::Debug, C: Core<T>> fmt::Debug for StableVecFacade<T, C> {
1688    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1689        write!(f, "StableVec ")?;
1690        f.debug_list().entries(self.values()).finish()
1691    }
1692}
1693
1694impl<Ta, Tb, Ca, Cb> PartialEq<StableVecFacade<Tb, Cb>> for StableVecFacade<Ta, Ca>
1695where
1696    Ta: PartialEq<Tb>,
1697    Ca: Core<Ta>,
1698    Cb: Core<Tb>,
1699{
1700    fn eq(&self, other: &StableVecFacade<Tb, Cb>) -> bool {
1701        self.num_elements() == other.num_elements()
1702            && self.capacity() == other.capacity()
1703            && self.next_push_index() == other.next_push_index()
1704            && (0..self.capacity()).all(|idx| {
1705                match (self.get(idx), other.get(idx)) {
1706                    (None, None) => true,
1707                    (Some(a), Some(b)) => a == b,
1708                    _ => false,
1709                }
1710            })
1711    }
1712}
1713
1714impl<T: Eq, C: Core<T>> Eq for StableVecFacade<T, C> {}
1715
1716impl<A, B, C: Core<A>> PartialEq<[B]> for StableVecFacade<A, C>
1717where
1718    A: PartialEq<B>,
1719{
1720    fn eq(&self, other: &[B]) -> bool {
1721        self.values().eq(other)
1722    }
1723}
1724
1725impl<'other, A, B, C: Core<A>> PartialEq<&'other [B]> for StableVecFacade<A, C>
1726where
1727    A: PartialEq<B>,
1728{
1729    fn eq(&self, other: &&'other [B]) -> bool {
1730        self == *other
1731    }
1732}
1733
1734impl<A, B, C: Core<A>> PartialEq<Vec<B>> for StableVecFacade<A, C>
1735where
1736    A: PartialEq<B>,
1737{
1738    fn eq(&self, other: &Vec<B>) -> bool {
1739        self == &other[..]
1740    }
1741}