pub struct ReusableVec<T: 'static> { /* private fields */ }Expand description
A wrapper around Vec that allows for reusing its allocation.
In performance-sensitive applications, frequent creation and destruction of
vectors can lead to significant overhead from memory allocations. ReusableVec
mitigates this by providing a mechanism to recycle a vector’s allocation.
The recycle method returns a ReusableVecGuard, which provides temporary, exclusive access
to the underlying vector. When the guard is dropped, the vector is cleared,
but its underlying memory allocation is preserved for subsequent use.
§Type Parameters
T: The type of elements in theVec. This type must be'staticbecause theReusableVecitself holds onto the allocation indefinitely.
§Safety
This struct uses an UnsafeCell to hold the Vec, which allows for mutating
its contents through a shared reference. The safety of this pattern is
guaranteed by the recycle method, which requires a mutable reference (&mut self).
This ensures that only one ReusableVecGuard can exist at a time for a given
ReusableVec, thereby preventing data races.
§Examples
§Basic Reuse
use triple_r::ReusableVec;
let mut reusable_vec = ReusableVec::<i32>::default();
// First use: populate the vector
{
let mut vec_guard = reusable_vec.recycle();
vec_guard.push(10);
vec_guard.push(20);
assert_eq!(*vec_guard, vec![10, 20]);
} // Guard is dropped, vector is cleared, but allocation is kept.
// Second use: the vector is empty but has retained its capacity.
{
let mut vec_guard = reusable_vec.recycle();
assert!(vec_guard.is_empty());
assert!(vec_guard.capacity() >= 2);
vec_guard.push(30);
assert_eq!(*vec_guard, vec![30]);
}Implementations§
Source§impl<T1> ReusableVec<T1>where
T1: 'static,
impl<T1> ReusableVec<T1>where
T1: 'static,
Sourcepub fn recycle<'parent, T2>(
&'parent mut self,
) -> ReusableVecGuard<'parent, T1, T2>where
T1: ReuseCastInto<T2>,
pub fn recycle<'parent, T2>(
&'parent mut self,
) -> ReusableVecGuard<'parent, T1, T2>where
T1: ReuseCastInto<T2>,
Reuses the Vec’s allocation, returning a guard for temporary access.
This method allows the Vec’s element type to be “cast” to a new type T2,
as long as the original type T1 implements ReuseCastInto<T2>.
The &mut self requirement is a key safety feature, as it ensures that
only one guard can be active at any given time.