pub struct SliceCache { /* private fields */ }
Expand description
A cache of non-overlapping mutable sub-slices of that enforces lifetimes dynamically.
This type is useful when you have to give up on the mutable reference to a slice but need a way to cache mutable sub-slices deriving from it.
§Examples
let mut array = [1, 2, 3];
let mut cache = SliceCache::new(3, |span| {
let (left, right) = span.split_at(1);
Box::new([left, right])
});
for slice in cache.access(&mut array).unwrap().iter_mut() {
for val in slice.iter_mut() {
*val += 1;
}
}
assert_eq!(array, [2, 3, 4]);
Implementations§
Source§impl SliceCache
impl SliceCache
Sourcepub fn new<F>(len: usize, f: F) -> Self
pub fn new<F>(len: usize, f: F) -> Self
Creates a new slice cache by storing sub-spans created from a root passed to the closure
f
. len
is the minimum slice length that can then be passed to access
.
§Examples
let mut cache = SliceCache::new(3, |span| {
let (left, right) = span.split_at(1);
// All returned sub-spans stem from the span passed above.
Box::new([left, right])
});
Sourcepub fn access<'c, 's, T>(
&'c mut self,
slice: &'s mut [T],
) -> Option<Ref<'c, [Slice<'s, T>]>>
pub fn access<'c, 's, T>( &'c mut self, slice: &'s mut [T], ) -> Option<Ref<'c, [Slice<'s, T>]>>
Accesses the slice
by returning all the sub-slices equivalent to the previously created
spans in the closure passed to new
.
If the slice
does not have a length at least as large as the one passed to
new
, this function returns None
.
Note: this method should not be called concurrently with any other access
calls since it
will wait for the previously returned Ref
to be dropped.
§Examples
let mut array = [1, 2, 3];
let mut cache = SliceCache::new(3, |span| {
let (left, right) = span.split_at(1);
Box::new([left, right])
});
let mut copy = array;
let skipped_one = cache.access(&mut array).unwrap();
assert_eq!(&*skipped_one[1], ©[1..]);