Skip to main content

orx_pinned_vec/
pinned_vec.rs

1use crate::{CapacityState, imp_vec::ImpVec};
2use core::cmp::Ordering;
3use core::ops::{Index, IndexMut, RangeBounds};
4use orx_iterable::{Collection, CollectionMut};
5use orx_pseudo_default::PseudoDefault;
6
7/// Trait for vector representations differing from `std::vec::Vec` by the following:
8///
9/// => memory location of an element already pushed to the collection never changes unless any of the following `mut` methods is called:
10/// * `remove`, `pop`,
11/// * `insert`,
12/// * `clear`, `truncate`.
13///
14/// In other words,
15///
16/// => growth methods `push` or `extend_from_slice` do <ins>not</ins> change memory locations of already added elements.
17///
18/// # Pinned Elements Guarantee
19///
20/// A `PinnedVec` guarantees that positions of its elements **do not change implicitly**.
21///
22/// To be specific, let's assume that a pinned vector currently has `n` elements:
23///
24/// | Method    | Expected Behavior |
25/// | -------- | ------- |
26/// | `push(new_element)` | does not change the memory locations of the `n` elements |
27/// | `extend_from_slice(slice)` | does not change the memory locations of the first `n` elements |
28/// | `insert(a, new_element)` | does not change the memory locations of the first `a` elements, where `a <= n`; elements to the right of the inserted element might be changed, commonly shifted to right |
29/// | `pop()` | does not change the memory locations of the first `n-1` elements, the `n`-th element is removed |
30/// | `remove(a)` | does not change the memory locations of the first `a` elements, where `a < n`; elements to the right of the removed element might be changed, commonly shifted to left |
31/// | `truncate(a)` | does not change the memory locations of the first `a` elements, where `a < n` |
32pub trait PinnedVec<T>:
33    IntoIterator<Item = T>
34    + Collection<Item = T>
35    + CollectionMut<Item = T>
36    + PseudoDefault
37    + Index<usize, Output = T>
38    + IndexMut<usize, Output = T>
39{
40    /// Iterator yielding references to the elements of the vector.
41    type IterRev<'a>: Iterator<Item = &'a T>
42    where
43        T: 'a,
44        Self: 'a;
45
46    /// Iterator yielding mutable references to the elements of the vector.
47    type IterMutRev<'a>: Iterator<Item = &'a mut T>
48    where
49        T: 'a,
50        Self: 'a;
51
52    /// Iterator yielding slices corresponding to a range of indices, returned by the `slice` method.
53    type SliceIter<'a>: IntoIterator<Item = &'a [T]> + Default
54    where
55        T: 'a,
56        Self: 'a;
57
58    /// Iterator yielding mutable slices corresponding to a range of indices, returned by the `slice_mut` and `slice_mut_unchecked` methods.
59    type SliceMutIter<'a>: IntoIterator<Item = &'a mut [T]> + Default
60    where
61        T: 'a,
62        Self: 'a;
63
64    // imp vec
65
66    /// Returns a mutable view of this vector as an [`ImpVec`] without consuming it.
67    ///
68    /// This is useful when a method wants to operate on the underlying data through the
69    /// `ImpVec` abstraction while keeping ownership of the original vector.
70    fn as_imp_vec(&mut self) -> ImpVec<T, Self, &mut Self>
71    where
72        Self: Sized,
73    {
74        ImpVec::new(self)
75    }
76
77    /// Consumes this vector and returns it as an [`ImpVec`].
78    ///
79    /// This is useful when ownership should be transferred directly into an `ImpVec`-based API.
80    fn into_imp_vec(self) -> ImpVec<T, Self, Self>
81    where
82        Self: Sized,
83    {
84        ImpVec::new(self)
85    }
86
87    // pinned
88
89    /// Returns the index of the `element` with the given reference.
90    ///
91    /// Note that `T: Eq` is not required; reference equality is used.
92    ///
93    /// The complexity of this method depends on the particular `PinnedVec` implementation.
94    /// However, making use of referential equality, it possible to perform much better than *O(n)*,
95    /// where n is the vector length.
96    ///
97    /// For the two example implementations, complexity of this method:
98    /// * *O(1)* for [FixedVec](https://crates.io/crates/orx-fixed-vec);
99    /// * *O(f)* for [SplitVec](https://crates.io/crates/orx-split-vec) where f << n is the number of fragments.
100    fn index_of(&self, element: &T) -> Option<usize>;
101
102    /// Returns the index of the `element_ptr` pointing to an element of the vec.
103    ///
104    /// The complexity of this method depends on the particular `PinnedVec` implementation.
105    /// However, making use of referential equality, it possible to perform much better than *O(n)*,
106    /// where n is the vector length.
107    ///
108    /// For the two example implementations, complexity of this method:
109    /// * *O(1)* for [FixedVec](https://crates.io/crates/orx-fixed-vec);
110    /// * *O(f)* for [SplitVec](https://crates.io/crates/orx-split-vec) where f << n is the number of fragments.
111    fn index_of_ptr(&self, element_ptr: *const T) -> Option<usize>;
112
113    /// Appends an element to the back of a collection and returns a pointer to its position in the vector.
114    fn push_get_ptr(&mut self, value: T) -> *const T;
115
116    /// Creates an iterator of the pointers to the elements of the vec.
117    ///
118    /// # Safety
119    ///
120    /// The implementor guarantees that the pointers are valid and belong to the elements of the vector.
121    /// However, the lifetime of the pointers might be extended by the caller;
122    /// i.e., it is not bound to the lifetime of `&self`.
123    ///
124    /// Therefore, the caller is responsible for making sure that the obtained pointers are still
125    /// valid before accessing through the pointers.
126    unsafe fn iter_ptr<'v, 'i>(&'v self) -> impl Iterator<Item = *const T> + 'i
127    where
128        T: 'i;
129
130    /// Creates a reverse iterator of the pointers to the elements of the vec, starting from the last element to the first.
131    ///
132    /// # Safety
133    ///
134    /// The implementor guarantees that the pointers are valid and belong to the elements of the vector.
135    /// However, the lifetime of the pointers might be extended by the caller;
136    /// i.e., it is not bound to the lifetime of `&self`.
137    ///
138    /// Therefore, the caller is responsible for making sure that the obtained pointers are still
139    /// valid before accessing through the pointers.
140    unsafe fn iter_ptr_rev<'v, 'i>(&'v self) -> impl Iterator<Item = *const T> + 'i
141    where
142        T: 'i;
143
144    /// Returns whether or not of the `element` with the given reference belongs to this vector.
145    /// In other words, returns whether or not the reference to the `element` is valid.
146    ///
147    /// Note that `T: Eq` is not required; memory address is used.
148    ///
149    /// The complexity of this method depends on the particular `PinnedVec` implementation.
150    /// However, making use of pinned element guarantees, it possible to perform much better than *O(n)*,
151    /// where n is the vector length.
152    ///
153    /// For the two example implementations, complexity of this method:
154    /// * *O(1)* for [FixedVec](https://crates.io/crates/orx-fixed-vec);
155    /// * *O(f)* for [SplitVec](https://crates.io/crates/orx-split-vec) where f << n is the number of fragments.
156    fn contains_reference(&self, element: &T) -> bool;
157
158    /// Returns whether or not of the element with the given pointer belongs to this vector.
159    ///
160    /// Note that `T: Eq` is not required; memory address is used.
161    ///
162    /// The complexity of this method depends on the particular `PinnedVec` implementation.
163    /// However, making use of pinned element guarantees, it possible to perform much better than *O(n)*,
164    /// where n is the vector length.
165    ///
166    /// For the two example implementations, complexity of this method:
167    /// * *O(1)* for [FixedVec](https://crates.io/crates/orx-fixed-vec);
168    /// * *O(f)* for [SplitVec](https://crates.io/crates/orx-split-vec) where f << n is the number of fragments.
169    fn contains_ptr(&self, element_ptr: *const T) -> bool;
170
171    // vec
172    /// Clears the vector, removing all values.
173    ///
174    /// Note that this method has no effect on the allocated capacity of the vector.
175    ///
176    /// # Safety
177    ///
178    /// `clear` operation is **safe** both when `T: NotSelfRefVecItem` or not due to the following:
179    ///
180    /// * elements holding references to each other will be cleaned all together; hence,
181    ///   none of them can have an invalid reference;
182    /// * we cannot keep holding a reference to a vector element defined aliased the `clear` call,
183    ///   since `clear` requires a `mut` reference.
184    fn clear(&mut self);
185
186    /// Returns the total number of elements the vector can hold without reallocating.
187    fn capacity(&self) -> usize;
188
189    /// Provides detailed information of capacity state of the pinned vector.
190    ///
191    /// This information contains the current capacity which can be obtained by [`PinnedVec::capacity()`] method and extends with additional useful information.
192    fn capacity_state(&self) -> CapacityState;
193
194    /// Clones and appends all elements in a slice to the Vec.
195    ///
196    /// Iterates over `other`, clones each element, and then appends it to this vec. The other slice is traversed in-order.
197    fn extend_from_slice(&mut self, other: &[T])
198    where
199        T: Clone;
200
201    /// Extends this vector by copying `count` * `size_of::<T>()` bytes from src to self.
202    /// The source and destination may not overlap.
203    ///
204    /// This method can be considered as a combination of [`extend`] and `copy_from_nonoverlapping` methods
205    /// such that:
206    ///
207    /// * it takes the elements from `src` and writes them to this vector by `memcpy`;
208    /// * however, it does add these elements to the end of this vector which grows as needed.
209    ///
210    /// # SAFETY
211    ///
212    /// Behavior is undefined if any of the following conditions are violated:
213    ///
214    /// - (i) `src` must be valid for reads of `count * size_of::<T>()` bytes.
215    /// - (ii) `src` must be properly aligned.
216    /// - (iii) The region of memory beginning at `src` with a size of `count * size_of::<T>()`
217    ///   bytes must *not* overlap with the region of memory beginning at `dst` with the same size.
218    ///   This is automatically satisfied when it is used to extend the pinned vector.
219    ///
220    /// [`extend`]: core::iter::Extend::extend
221    unsafe fn extend_from_nonoverlapping(&mut self, src: *const T, count: usize);
222
223    /// Returns a reference to an element with the given `index` returns None if the index is out of bounds.
224    fn get(&self, index: usize) -> Option<&T>;
225    /// Returns a mutable reference to an element with the given `index` returns None if the index is out of bounds.
226    fn get_mut(&mut self, index: usize) -> Option<&mut T>;
227    /// Returns a reference to an element without doing bounds checking.
228    ///
229    /// For a safe alternative see `get`.
230    ///
231    /// # Safety
232    ///
233    /// Calling this method with an out-of-bounds index is *[undefined behavior]*
234    /// even if the resulting reference is not used.
235    unsafe fn get_unchecked(&self, index: usize) -> &T;
236    /// Returns a mutable reference to an element without doing bounds checking.
237    ///
238    /// For a safe alternative see `get_mut`.
239    ///
240    /// # Safety
241    ///
242    /// Calling this method with an out-of-bounds index is *[undefined behavior]*
243    /// even if the resulting reference is not used.
244    unsafe fn get_unchecked_mut(&mut self, index: usize) -> &mut T;
245
246    /// Returns a reference to the first element of the vector; returns None if the vector is empty.
247    fn first(&self) -> Option<&T>;
248    /// Returns a reference to the last element of the vector; returns None if the vector is empty.
249    fn last(&self) -> Option<&T>;
250
251    /// Returns a reference to the first element of the vector without bounds checking.
252    ///
253    /// For a safe alternative see `first`.
254    ///
255    /// # Safety
256    ///
257    /// Calling this method when the vector is empty is *[undefined behavior]* even if the resulting reference is not used.
258    unsafe fn first_unchecked(&self) -> &T;
259    /// Returns a reference to the last element of the vector without bounds checking.
260    ///
261    /// For a safe alternative see `last`.
262    ///
263    /// # Safety
264    ///
265    /// Calling this method when the vector is empty is *[undefined behavior]* even if the resulting reference is not used.
266    unsafe fn last_unchecked(&self) -> &T;
267
268    /// Returns true if the vector contains no elements.
269    fn is_empty(&self) -> bool {
270        self.len() == 0
271    }
272    /// Returns the number of elements in the vector, also referred to as its length.
273    fn len(&self) -> usize;
274    /// Appends an element to the back of a collection.
275    fn push(&mut self, value: T);
276
277    // vec but unsafe
278    /// Inserts an element at position `index` within the vector, shifting all elements after it to the right.
279    ///
280    /// # Panics
281    /// Panics if `index >= len`.
282    fn insert(&mut self, index: usize, element: T);
283    /// Removes and returns the element at position index within the vector, shifting all elements after it to the left.
284    ///
285    /// # Panics
286    ///
287    /// Panics if index is out of bounds.
288    fn remove(&mut self, index: usize) -> T;
289    /// Removes the last element from a vector and returns it, or None if it is empty.
290    fn pop(&mut self) -> Option<T>;
291    /// Swaps two elements in the slice.
292    ///
293    /// If `a` equals to `b`, it's guaranteed that elements won't change value.
294    ///
295    /// # Arguments
296    ///
297    /// * a - The index of the first element
298    /// * b - The index of the second element.
299    fn swap(&mut self, a: usize, b: usize);
300    /// Shortens the vector, keeping the first `len` elements and dropping
301    /// the rest.
302    ///
303    /// If `len` is greater than the vector's current length, this has no
304    /// effect.
305    fn truncate(&mut self, len: usize);
306
307    /// Returns a reversed back-to-front iterator to elements of the vector.
308    fn iter_rev(&self) -> Self::IterRev<'_>;
309    /// Returns a reversed back-to-front iterator mutable references to elements of the vector.
310    fn iter_mut_rev(&mut self) -> Self::IterMutRev<'_>;
311
312    /// Returns the view on the required `range` as an iterator of slices:
313    ///
314    /// * returns an empty iterator if the range is out of bounds;
315    /// * returns an iterator yielding ordered slices that forms the required range when chained.
316    fn slices<R: RangeBounds<usize>>(&self, range: R) -> Self::SliceIter<'_>;
317
318    /// Returns a mutable view on the required `range` as an iterator of mutable slices:
319    ///
320    /// * returns an empty iterator if the range is out of bounds;
321    /// * returns an iterator yielding ordered slices that forms the required range when chained.
322    fn slices_mut<R: RangeBounds<usize>>(&mut self, range: R) -> Self::SliceMutIter<'_>;
323
324    /// Creates an exact size iterator for elements over the given `range`.
325    ///
326    /// This method can be considered as a generalization of creating a slice of a vector
327    /// such that it does not necessarily return a contagious slice of elements. It might
328    /// as well return a sequence of multiple slices, as long as the elements are positioned
329    /// at the given `range` of indices.
330    fn iter_over<'a>(
331        &'a self,
332        range: impl RangeBounds<usize>,
333    ) -> impl ExactSizeIterator<Item = &'a T>
334    where
335        T: 'a;
336
337    /// Creates a mutable exact size iterator for elements over the given `range`.
338    ///
339    /// This method can be considered as a generalization of creating a mutable slice of a vector
340    /// such that it does not necessarily return a contagious slice of elements. It might
341    /// as well return a sequence of multiple slices, as long as the elements are positioned
342    /// at the given `range` of indices.
343    fn iter_mut_over<'a>(
344        &'a mut self,
345        range: impl RangeBounds<usize>,
346    ) -> impl ExactSizeIterator<Item = &'a mut T>
347    where
348        T: 'a;
349
350    /// Returns a pointer to the `index`-th element of the vector.
351    ///
352    /// Returns `None` if `index`-th position does not belong to the vector; i.e., if `index` is out of `capacity`.
353    fn get_ptr(&self, index: usize) -> Option<*const T>;
354
355    /// Returns a mutable pointer to the `index`-th element of the vector.
356    ///
357    /// Returns `None` if `index`-th position does not belong to the vector; i.e., if `index` is out of `capacity`.
358    fn get_ptr_mut(&mut self, index: usize) -> Option<*mut T>;
359
360    /// Forces the length of the vector to `new_len`.
361    ///
362    /// This is a low-level operation that maintains none of the normal invariants of the type.
363    ///
364    /// # Safety
365    ///
366    /// - `new_len` must be less than or equal to `capacity()`.
367    /// - The elements at `old_len..new_len` must be initialized.
368    unsafe fn set_len(&mut self, new_len: usize);
369
370    /// Binary searches vector slice with a comparator function.
371    ///
372    /// The comparator function `f` should return an order code that indicates whether its argument is Less, Equal or Greater the desired target.
373    /// If the vector is not sorted or if the comparator function does not implement an order consistent with the sort order of the underlying slice, the returned result is unspecified and meaningless.
374    ///
375    /// If the value is found then Result::Ok is returned, containing the index of the matching element.
376    /// If there are multiple matches, then any one of the matches could be returned.
377    ///
378    /// If the value is not found then Result::Err is returned, containing the index where a matching element could be inserted while maintaining sorted order.
379    ///
380    /// See also binary_search and binary_search_by_key.
381    ///
382    /// # Examples
383    ///
384    /// Below example is taken from std::Vec since expected behavior of `PinnedVec` is exactly the same.
385    ///
386    /// Looks up a series of four elements.
387    /// The first is found, with a uniquely determined position; the second and third are not found; the fourth could match any position in [1, 4].
388    ///
389    /// ```rust
390    /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
391    ///
392    /// let seek = 13;
393    /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
394    /// let seek = 4;
395    /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
396    /// let seek = 100;
397    /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
398    /// let seek = 1;
399    /// let r = s.binary_search_by(|probe| probe.cmp(&seek));
400    /// assert!(match r { Ok(1..=4) => true, _ => false, });
401    /// ```
402    fn binary_search_by<F>(&self, f: F) -> Result<usize, usize>
403    where
404        F: FnMut(&T) -> Ordering;
405
406    /// Binary searches this vector for the `search_value`.
407    /// If the vector is not sorted, the returned result is unspecified and
408    /// meaningless.
409    ///
410    /// If the value is found then [`Result::Ok`] is returned, containing the
411    /// index of the matching element. If there are multiple matches, then any
412    /// one of the matches could be returned
413    ///
414    /// If the value is not found then [`Result::Err`] is returned, containing
415    /// the index where a matching element could be inserted while maintaining
416    /// sorted order.
417    ///
418    /// # Examples
419    ///
420    /// Below examples are taken from std::Vec since expected behavior of `PinnedVec` is exactly the same.
421    ///
422    /// Looks up a series of four elements. The first is found, with a
423    /// uniquely determined position; the second and third are not
424    /// found; the fourth could match any position in `[1, 4]`.
425    ///
426    /// ```rust
427    /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
428    ///
429    /// assert_eq!(s.binary_search(&13),  Ok(9));
430    /// assert_eq!(s.binary_search(&4),   Err(7));
431    /// assert_eq!(s.binary_search(&100), Err(13));
432    /// let r = s.binary_search(&1);
433    /// assert!(match r { Ok(1..=4) => true, _ => false, });
434    /// ```
435    fn binary_search(&self, search_value: &T) -> Result<usize, usize>
436    where
437        T: Ord,
438    {
439        self.binary_search_by(|p| p.cmp(search_value))
440    }
441
442    /// Binary searches this vector with a key extraction function.
443    ///
444    /// Assumes that the vector is sorted by the key, for instance with
445    /// `sort_by_key` using the same key extraction function.
446    /// If the vector is not sorted by the key, the returned result is
447    /// unspecified and meaningless.
448    ///
449    /// If the value is found then [`Result::Ok`] is returned, containing the
450    /// index of the matching element. If there are multiple matches, then any
451    /// one of the matches could be returned.
452    ///
453    /// If the value is not found then [`Result::Err`] is returned, containing
454    /// the index where a matching element could be inserted while maintaining
455    /// sorted order.
456    ///
457    /// # Examples
458    ///
459    /// Below examples are taken from std::Vec since expected behavior of `PinnedVec` is exactly the same.
460    ///
461    /// Looks up a series of four elements in a slice of pairs sorted by
462    /// their second elements. The first is found, with a uniquely
463    /// determined position; the second and third are not found; the
464    /// fourth could match any position in `[1, 4]`.
465    ///
466    /// ```
467    /// let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1),
468    ///          (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
469    ///          (1, 21), (2, 34), (4, 55)];
470    ///
471    /// assert_eq!(s.binary_search_by_key(&13, |&(a, b)| b),  Ok(9));
472    /// assert_eq!(s.binary_search_by_key(&4, |&(a, b)| b),   Err(7));
473    /// assert_eq!(s.binary_search_by_key(&100, |&(a, b)| b), Err(13));
474    /// let r = s.binary_search_by_key(&1, |&(a, b)| b);
475    /// assert!(match r { Ok(1..=4) => true, _ => false, });
476    /// ```
477    fn binary_search_by_key<B, F>(&self, b: &B, mut f: F) -> Result<usize, usize>
478    where
479        F: FnMut(&T) -> B,
480        B: Ord,
481    {
482        self.binary_search_by(|k| f(k).cmp(b))
483    }
484
485    /// Sorts the vector.
486    ///
487    /// This sort is stable.
488    fn sort(&mut self)
489    where
490        T: Ord;
491
492    /// Sorts the slice with a comparator function.
493    ///
494    /// This sort is stable.
495    ///
496    /// The comparator function must define a total ordering for the elements in the slice. If
497    /// the ordering is not total, the order of the elements is unspecified. An order is a
498    /// total order if it is (for all `a`, `b` and `c`):
499    ///
500    /// * total and antisymmetric: exactly one of `a < b`, `a == b` or `a > b` is true, and
501    /// * transitive, `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
502    ///
503    /// For example, while [`f64`] doesn't implement [`Ord`] because `NaN != NaN`, we can use
504    /// `partial_cmp` as our sort function when we know the slice doesn't contain a `NaN`.
505    fn sort_by<F>(&mut self, compare: F)
506    where
507        F: FnMut(&T, &T) -> Ordering;
508
509    /// Sorts the slice with a key extraction function.
510    ///
511    /// This sort is stable.
512    fn sort_by_key<K, F>(&mut self, f: F)
513    where
514        F: FnMut(&T) -> K,
515        K: Ord;
516
517    /// Returns the maximum possible capacity that the vector can grow to.
518    fn capacity_bound(&self) -> usize;
519}