pub unsafe trait TakeOwnedSlice {
type Item;
// Required methods
fn owned_slice_ref(&self) -> &[Self::Item];
fn take_owned_slice(&mut self);
}Expand description
A trait for objects which own a slice and can relinquish their ownership of all its elements at once.
Implementors of this trait must behave like a Vec<T> in the sense that they manage a slice they own.
When the slice is “taken” using take_owned_slice, the implementor
must relinquish ownership of its elements entirely, leaving behind an empty slice.
The goal of the safety conditions are so that a function like this is sound:
fn append<T>(vec: &mut Vec<T>, mut to_append: impl TakeOwnedSlice<Item = T>) {
let slice = NonNull::from(to_append.owned_slice_ref());
vec.reserve(slice.len());
unsafe {
let src = slice.cast::<T>().as_ptr();
let dst = vec.as_mut_ptr().add(vec.len());
src.copy_to_nonoverlapping(dst, slice.len());
to_append.take_owned_slice();
vec.set_len(vec.len() + slice.len());
}
}
§Safety
The implementor must own a slice, that both of the methods operate on. Let’s call it the slice.
owned_slice_refreturns the slice.take_owned_slicerelinquishes the ownership of the slice. The elements of the slice must not be dropped. Once called, the slice becomes an empty slice.- Between calls to
owned_slice_refandtake_owned_slice, the caller can assume that the slice won’t change as long as the caller itself does not interact with the type. As such this trait must not be implemented for a type whose slice could change from a different thread for instance.
Required Associated Types§
Required Methods§
Sourcefn owned_slice_ref(&self) -> &[Self::Item]
fn owned_slice_ref(&self) -> &[Self::Item]
Returns a slice of its elements.
Sourcefn take_owned_slice(&mut self)
fn take_owned_slice(&mut self)
Makes the slice forget all of its elements.
Its elements are the elements referred to by owned_slice_ref.
The caller is now responsible for dropping these elements.
After calling this method, owned_slice_ref will return an empty slice.
Implementations on Foreign Types§
Source§impl<T> TakeOwnedSlice for Box<[T]>
Available on crate feature alloc only.
impl<T> TakeOwnedSlice for Box<[T]>
alloc only.type Item = T
fn owned_slice_ref(&self) -> &[Self::Item]
fn take_owned_slice(&mut self)
Source§impl<T> TakeOwnedSlice for Drain<'_, T>
Available on crate feature alloc only.
impl<T> TakeOwnedSlice for Drain<'_, T>
alloc only.type Item = T
fn owned_slice_ref(&self) -> &[Self::Item]
fn take_owned_slice(&mut self)
Source§impl<T> TakeOwnedSlice for IntoIter<T>
Available on crate feature alloc only.
impl<T> TakeOwnedSlice for IntoIter<T>
alloc only.type Item = T
fn owned_slice_ref(&self) -> &[Self::Item]
fn take_owned_slice(&mut self)
Source§impl<T> TakeOwnedSlice for Vec<T>
Available on crate feature alloc only.
impl<T> TakeOwnedSlice for Vec<T>
alloc only.