pub struct SliceAllocGuard<'a, T, A: Alloc + ?Sized> { /* private fields */ }
Expand description
A RAII guard for a heap‐allocated slice that tracks how many elements have been initialized.
On drop, it will:
- Run destructors for each initialized element.
- Deallocate the entire slice memory.
Use init
or init_unchecked
to initialize elements one by one, extend_init
to
initialize many elements at once, and release
to take
ownership of the fully‐initialized slice without running cleanup.
§Examples
let mut guard = SliceAllocGuard::new(
alloc.alloc_slice::<u32>(len).unwrap().cast::<u32>(),
&alloc,
len
);
for i in 0..len {
guard.init(i as u32).unwrap();
}
// All elements are now initialized; take ownership:
// (commented out for this example as the pointer will not be used)
// let slice_ptr = guard.release();
Implementations§
Source§impl<'a, T, A: Alloc + ?Sized> SliceAllocGuard<'a, T, A>
impl<'a, T, A: Alloc + ?Sized> SliceAllocGuard<'a, T, A>
Sourcepub const fn new(
ptr: NonNull<T>,
alloc: &'a A,
full: usize,
) -> SliceAllocGuard<'a, T, A>
pub const fn new( ptr: NonNull<T>, alloc: &'a A, full: usize, ) -> SliceAllocGuard<'a, T, A>
Creates a new slice guard for full
elements at ptr
in the given allocator.
Sourcepub const fn release(self) -> NonNull<[T]>
pub const fn release(self) -> NonNull<[T]>
Release ownership of the slice without deallocating memory.
Sourcepub const fn init(&mut self, elem: T) -> Result<(), T>
pub const fn init(&mut self, elem: T) -> Result<(), T>
Initializes the next element of the slice with elem
.
§Errors
Returns Err(elem)
if the slice is at capacity.
Sourcepub const unsafe fn init_unchecked(&mut self, elem: T)
pub const unsafe fn init_unchecked(&mut self, elem: T)
Initializes the next element of the slice with elem
.
§Safety
The caller must ensure that the slice is not at capacity. (initialized() < full()
)
Sourcepub fn extend_init<I: IntoIterator<Item = T>>(
&mut self,
iter: I,
) -> Result<(), I::IntoIter>
pub fn extend_init<I: IntoIterator<Item = T>>( &mut self, iter: I, ) -> Result<(), I::IntoIter>
Initializes the next elements of the slice with the elements from iter
.
§Errors
Returns Err((iter, elem))
if the slice is filled before iteration finishes. The
contained iterator will have been partially consumed.
Sourcepub const fn initialized(&self) -> usize
pub const fn initialized(&self) -> usize
Returns how many elements have been initialized.
Methods from Deref<Target = NonNull<T>>§
1.25.0 · Sourcepub unsafe fn as_ref<'a>(&self) -> &'a T
pub unsafe fn as_ref<'a>(&self) -> &'a T
Returns a shared reference to the value. If the value may be uninitialized, as_uninit_ref
must be used instead.
For the mutable counterpart see as_mut
.
§Safety
When calling this method, you have to ensure that the pointer is convertible to a reference.
§Examples
use std::ptr::NonNull;
let mut x = 0u32;
let ptr = NonNull::new(&mut x as *mut _).expect("ptr is null!");
let ref_x = unsafe { ptr.as_ref() };
println!("{ref_x}");