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