Struct orx_imp_vec::ImpVec
source ยท pub struct ImpVec<T, P = SplitVec<T>>where
P: PinnedVec<T>,{ /* private fields */ }Expand description
ImpVec, standing for immutable push vector ๐ฟ, is a data structure which allows appending elements with a shared reference.
Specifically, it extends vector capabilities with the following two methods:
fn imp_push(&self, value: T)fn imp_extend_from_slice(&self, slice: &[T])
Note that both of these methods can be called with &self rather than &mut self.
ยงMotivation
Appending to a vector with a shared reference sounds unconventional, and it is. However, if we consider our vector as a bag of or a container of things rather than having a collective meaning; then, appending element or elements to the end of the vector:
- does not mutate any of already added elements, and hence,
- it is not different than creating a new element in the scope.
ยงSafety
It is natural to expect that appending elements to a vector does not affect already added elements.
However, this is usually not the case due to underlying memory management.
For instance, std::vec::Vec may move already added elements to different memory locations to maintain the contagious layout of the vector.
PinnedVec prevents such implicit changes in memory locations.
It guarantees that push and extend methods keep memory locations of already added elements intact.
Therefore, it is perfectly safe to hold on to references of the vector while appending elements.
Consider the classical example that does not compile, which is often presented to highlight the safety guarantees of rust:
let mut vec = vec![0, 1, 2, 3];
let ref_to_first = &vec[0];
assert_eq!(ref_to_first, &0);
vec.push(4);
// does not compile due to the following reason: cannot borrow `vec` as mutable because it is also borrowed as immutable
// assert_eq!(ref_to_first, &0);This wonderful feature of the borrow checker of rust is not required and used for imp_push and imp_extend_from_slice methods of ImpVec
since these methods do not require a &mut self reference.
Therefore, the following code compiles and runs perfectly safely.
use orx_imp_vec::*;
let mut vec = ImpVec::new();
vec.extend_from_slice(&[0, 1, 2, 3]);
let ref_to_first = &vec[0];
assert_eq!(ref_to_first, &0);
vec.imp_push(4);
assert_eq!(vec.len(), 5);
vec.imp_extend_from_slice(&[6, 7]);
assert_eq!(vec.len(), 7);
assert_eq!(ref_to_first, &0);Implementationsยง
sourceยงimpl<T, P: PinnedVec<T>> ImpVec<T, P>
impl<T, P: PinnedVec<T>> ImpVec<T, P>
sourcepub fn into_inner(self) -> P
pub fn into_inner(self) -> P
Consumes the imp-vec into the wrapped inner pinned vector.
ยงExample
use orx_split_vec::SplitVec;
use orx_imp_vec::ImpVec;
let pinned_vec = SplitVec::new();
let imp_vec = ImpVec::from(pinned_vec);
imp_vec.imp_push(42);
let pinned_vec = imp_vec.into_inner();
assert_eq!(&pinned_vec, &[42]);sourcepub fn imp_push(&self, value: T)
pub fn imp_push(&self, value: T)
Pushes the value to the vector.
This method differs from the push method with the required reference.
Unlike push, imp_push allows to push the element with a shared reference.
ยงExample
use orx_imp_vec::*;
let mut vec = ImpVec::new();
// regular push with &mut self
vec.push(42);
// hold on to a reference to the first element
let ref_to_first = &vec[0];
assert_eq!(ref_to_first, &42);
// imp_push with &self
vec.imp_push(7);
// due to `PinnedVec` guarantees, this push will never invalidate prior references
assert_eq!(ref_to_first, &42);ยงSafety
Wrapping a PinnedVec with an ImpVec provides with two additional methods: imp_push and imp_extend_from_slice.
Note that these push and extend methods grow the vector by appending elements to the end.
It is natural to expect that these operations do not change the memory locations of already added elements.
However, this is usually not the case due to underlying allocations.
For instance, std::vec::Vec may move already added elements in memory to maintain the contagious layout of the vector.
PinnedVec prevents such implicit changes in memory locations.
It guarantees that push and extend methods keep memory locations of already added elements intact.
Therefore, it is perfectly safe to hold on to references of the vector while appending elements.
Consider the classical example that does not compile, which is often presented to highlight the safety guarantees of rust:
let mut vec = vec![0, 1, 2, 3];
let ref_to_first = &vec[0];
assert_eq!(ref_to_first, &0);
vec.push(4);
// does not compile due to the following reason: cannot borrow `vec` as mutable because it is also borrowed as immutable
// assert_eq!(ref_to_first, &0);This wonderful feature of the borrow checker of rust is not required and used for imp_push and imp_extend_from_slice methods of ImpVec
since these methods do not require a &mut self reference.
Therefore, the following code compiles and runs perfectly safely.
use orx_imp_vec::*;
let mut vec = ImpVec::new();
vec.extend_from_slice(&[0, 1, 2, 3]);
let ref_to_first = &vec[0];
assert_eq!(ref_to_first, &0);
vec.imp_push(4);
assert_eq!(vec.len(), 5);
assert_eq!(ref_to_first, &0);Although unconventional, this makes sense when we consider the ImpVec as a bag or container of things, rather than having a collective meaning.
In other words, when we do not rely on reduction methods, such as count or sum, appending element or elements to the end of the vector:
- does not mutate any of already added elements, and hence,
- it is not different than creating a new element in the scope.
Examples found in repository?
More examples
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
fn symbol(&'a self, name: &'static str) -> ExprInScope<'a> {
let expr = Expr::Symbol(name);
self.expressions.imp_push(expr);
ExprInScope {
scope: self,
expr: &self.expressions[self.expressions.len() - 1],
}
}
}
/// A recursive expression with three demo variants
enum Expr<'a> {
Symbol(&'static str),
Addition(&'a Expr<'a>, &'a Expr<'a>),
Subtraction(&'a Expr<'a>, &'a Expr<'a>),
}
impl<'a> Display for Expr<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Expr::Symbol(x) => write!(f, "{}", x),
Expr::Addition(x, y) => write!(f, "{} + {}", x, y),
Expr::Subtraction(x, y) => write!(f, "{} - {}", x, y),
}
}
}
/// Expression in a scope:
/// * it knows what it is
/// * it knows which scope it belongs to
///
/// It can implement Copy which turns out to be extremely important!
#[derive(Clone, Copy)]
struct ExprInScope<'a> {
scope: &'a Scope<'a>,
expr: &'a Expr<'a>,
}
impl<'a> ExprInScope<'a> {
/// Recall, it knows that scope it belongs to,
/// and can check it in O(1)
fn belongs_to_same_scope(&self, other: Self) -> bool {
let self_scope = self.scope as *const Scope;
let other_scope = other.scope as *const Scope;
self_scope == other_scope
}
}
impl<'a> Display for ExprInScope<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.expr)
}
}
impl<'a> Add for ExprInScope<'a> {
type Output = ExprInScope<'a>;
/// We can create an expression by adding two expressions
///
/// Where do we store the new expression?
///
/// Of course, in the scope that both expressions belong to.
/// And we can do so by `imp_push`.
///
/// # Panics
///
/// Panics if the lhs & rhs do not belong to the same scope.
fn add(self, rhs: Self) -> Self::Output {
assert!(self.belongs_to_same_scope(rhs));
let expressions = &self.scope.expressions;
let expr = Expr::Addition(self.expr, rhs.expr);
expressions.imp_push(expr);
ExprInScope {
scope: self.scope,
expr: &expressions[expressions.len() - 1],
}
}
}
impl<'a> Sub for ExprInScope<'a> {
type Output = ExprInScope<'a>;
/// Similarly, we can create an expression by subtracting two expressions
///
/// Where do we store the new expression?
///
/// Of course, in the scope that both expressions belong to.
/// And we can do so by `imp_push`.
///
/// # Panics
///
/// Panics if the lhs & rhs do not belong to the same scope.
fn sub(self, rhs: Self) -> Self::Output {
assert!(self.belongs_to_same_scope(rhs));
let expressions = &self.scope.expressions;
let expr = Expr::Subtraction(self.expr, rhs.expr);
expressions.imp_push(expr);
ExprInScope {
scope: self.scope,
expr: &expressions[expressions.len() - 1],
}
}sourcepub fn imp_extend_from_slice(&self, slice: &[T])where
T: Clone,
pub fn imp_extend_from_slice(&self, slice: &[T])where
T: Clone,
Extends the vector with the given slice.
This method differs from the extend_from_slice method with the required reference.
Unlike extend_from_slice, imp_extend_from_slice allows to push the element with a shared reference.
ยงExample
use orx_imp_vec::*;
let mut vec = ImpVec::new();
// regular extend_from_slice with &mut self
vec.extend_from_slice(&[42]);
// hold on to a reference to the first element
let ref_to_first = &vec[0];
assert_eq!(ref_to_first, &42);
// imp_extend_from_slice with &self
vec.imp_extend_from_slice(&[0, 1, 2, 3]);
assert_eq!(vec.len(), 5);
// due to `PinnedVec` guarantees, this extend will never invalidate prior references
assert_eq!(ref_to_first, &42);ยงSafety
Wrapping a PinnedVec with an ImpVec provides with two additional methods: imp_push and imp_extend_from_slice.
Note that these push and extend methods grow the vector by appending elements to the end.
It is natural to expect that these operations do not change the memory locations of already added elements.
However, this is usually not the case due to underlying allocations.
For instance, std::vec::Vec may move already added elements in memory to maintain the contagious layout of the vector.
PinnedVec prevents such implicit changes in memory locations.
It guarantees that push and extend methods keep memory locations of already added elements intact.
Therefore, it is perfectly safe to hold on to references of the vector while appending elements.
Consider the classical example that does not compile, which is often presented to highlight the safety guarantees of rust:
let mut vec = vec![0];
let ref_to_first = &vec[0];
assert_eq!(ref_to_first, &0);
vec.extend_from_slice(&[1, 2, 3, 4]);
// does not compile due to the following reason: cannot borrow `vec` as mutable because it is also borrowed as immutable
// assert_eq!(ref_to_first, &0);This wonderful feature of the borrow checker of rust is not required and used for imp_push and imp_extend_from_slice methods of ImpVec
since these methods do not require a &mut self reference.
Therefore, the following code compiles and runs perfectly safely.
use orx_imp_vec::*;
let mut vec = ImpVec::new();
vec.push(0);
let ref_to_first = &vec[0];
assert_eq!(ref_to_first, &0);
vec.imp_extend_from_slice(&[1, 2, 3, 4]);
assert_eq!(ref_to_first, &0);Although unconventional, this makes sense when we consider the ImpVec as a bag or container of things, rather than having a collective meaning.
In other words, when we do not rely on reduction methods, such as count or sum, appending element or elements to the end of the vector:
- does not mutate any of already added elements, and hence,
- it is not different than creating a new element in the scope.
sourceยงimpl<T> ImpVec<T>
impl<T> ImpVec<T>
sourcepub fn new() -> Self
pub fn new() -> Self
Creates a new empty imp-vec.
Default underlying pinned vector is a new SplitVec<T, Doubling>.
ยงExample
use orx_imp_vec::*;
let imp_vec: ImpVec<char> = ImpVec::new();
assert!(imp_vec.is_empty());sourceยงimpl<T> ImpVec<T, SplitVec<T, Doubling>>
impl<T> ImpVec<T, SplitVec<T, Doubling>>
sourcepub fn with_doubling_growth() -> Self
pub fn with_doubling_growth() -> Self
Creates a new ImpVec by creating and wrapping up a new SplitVec<T, Doubling> as the underlying storage.
sourceยงimpl<T> ImpVec<T, SplitVec<T, Recursive>>
impl<T> ImpVec<T, SplitVec<T, Recursive>>
sourcepub fn with_recursive_growth() -> Self
pub fn with_recursive_growth() -> Self
Creates a new ImpVec by creating and wrapping up a new SplitVec<T, Recursive> as the underlying storage.
sourceยงimpl<T> ImpVec<T, SplitVec<T, Linear>>
impl<T> ImpVec<T, SplitVec<T, Linear>>
sourcepub fn with_linear_growth(constant_fragment_capacity_exponent: usize) -> Self
pub fn with_linear_growth(constant_fragment_capacity_exponent: usize) -> Self
Creates a new ImpVec by creating and wrapping up a new SplitVec<T, Linear> as the underlying storage.
- Each fragment of the underlying split vector will have a capacity of
2 ^ constant_fragment_capacity_exponent.
sourceยงimpl<T> ImpVec<T, FixedVec<T>>
impl<T> ImpVec<T, FixedVec<T>>
sourcepub fn with_fixed_capacity(fixed_capacity: usize) -> Self
pub fn with_fixed_capacity(fixed_capacity: usize) -> Self
Creates a new ImpVec by creating and wrapping up a new FixedVec<T> as the underlying storage.
ยงSafety
Note that a FixedVec cannot grow beyond the given fixed_capacity.
In other words, has a hard upper bound on the number of elements it can hold, which is the fixed_capacity.
Pushing to the vector beyond this capacity leads to โout-of-capacityโ error.
This maximum capacity can be accessed by the capacitymethod.
Trait Implementationsยง
sourceยงimpl<T, P> FromIterator<T> for ImpVec<T, P>where
P: FromIterator<T> + PinnedVec<T>,
impl<T, P> FromIterator<T> for ImpVec<T, P>where
P: FromIterator<T> + PinnedVec<T>,
sourceยงfn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self
sourceยงimpl<T, P: PinnedVec<T>> IntoIterator for ImpVec<T, P>
impl<T, P: PinnedVec<T>> IntoIterator for ImpVec<T, P>
sourceยงimpl<T: PartialEq, P1: PinnedVec<T>, P2: PinnedVec<T>> PartialEq<ImpVec<T, P2>> for ImpVec<T, P1>
impl<T: PartialEq, P1: PinnedVec<T>, P2: PinnedVec<T>> PartialEq<ImpVec<T, P2>> for ImpVec<T, P1>
Auto Trait Implementationsยง
impl<T, P = SplitVec<T>> !Freeze for ImpVec<T, P>
impl<T, P = SplitVec<T>> !RefUnwindSafe for ImpVec<T, P>
impl<T, P> Send for ImpVec<T, P>
impl<T, P = SplitVec<T>> !Sync for ImpVec<T, P>
impl<T, P> Unpin for ImpVec<T, P>
impl<T, P> UnwindSafe for ImpVec<T, P>where
P: UnwindSafe,
T: UnwindSafe,
Blanket Implementationsยง
sourceยงimpl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
sourceยงfn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
sourceยงimpl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
sourceยงunsafe fn clone_to_uninit(&self, dst: *mut T)
unsafe fn clone_to_uninit(&self, dst: *mut T)
clone_to_uninit)