Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add try_zeroed_vec and zeroed_vec #117

Merged
merged 3 commits into from
Jul 7, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 22 additions & 8 deletions src/allocation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,25 @@ pub fn zeroed_box<T: Zeroable>() -> Box<T> {
try_zeroed_box().unwrap()
}

/// Allocates a `Vec<T>` of length and capacity exactly equal to `length` and all elements zeroed.
///
/// ## Failure
///
/// This fails if the allocation fails, or if a layout cannot be calculated for the allocation.
pub fn try_zeroed_vec<T: Zeroable>(length: usize) -> Result<Vec<T>, ()> {
Lokathor marked this conversation as resolved.
Show resolved Hide resolved
if length == 0 {
Ok(Vec::new())
} else {
let boxed_slice = try_zeroed_slice_box(length)?;
Ok(boxed_slice.into_vec())
}
}

/// As [`try_zeroed_vec`] but unwraps for you
pub fn zeroed_vec<T: Zeroable>(length: usize) -> Vec<T> {
try_zeroed_vec(length).unwrap()
}

/// Allocates a `Box<[T]>` with all contents being zeroed out.
///
/// This uses the global allocator to create a zeroed allocation and _then_
Expand All @@ -102,7 +121,7 @@ pub fn zeroed_box<T: Zeroable>() -> Box<T> {
///
/// ## Failure
///
/// This fails if the allocation fails.
/// This fails if the allocation fails, or if a layout cannot be calculated for the allocation.
#[inline]
pub fn try_zeroed_slice_box<T: Zeroable>(
length: usize,
Expand All @@ -117,12 +136,7 @@ pub fn try_zeroed_slice_box<T: Zeroable>(
// This will also not allocate.
return Ok(Vec::new().into_boxed_slice());
}
// For Pod types, the layout of the array/slice is equivalent to repeating the
// type.
let layout_length = size_of::<T>().checked_mul(length).ok_or(())?;
assert!(layout_length != 0);
let layout =
Layout::from_size_align(layout_length, align_of::<T>()).map_err(|_| ())?;
let layout = core::alloc::Layout::array::<T>(length).map_err(|_| ())?;
let ptr = unsafe { alloc_zeroed(layout) };
if ptr.is_null() {
// we don't know what the error is because `alloc_zeroed` is a dumb API
Expand All @@ -131,7 +145,7 @@ pub fn try_zeroed_slice_box<T: Zeroable>(
let slice =
unsafe { core::slice::from_raw_parts_mut(ptr as *mut T, length) };
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be core::ptr::slice_from_raw_parts_mut() to avoid creating an intermediate reference (also also reduces the amount of unsafe by one line).

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's a possible change, but in this case the intermediate reference is fine, because the allocation is initialized anyway.

Ok(unsafe { Box::<[T]>::from_raw(slice) })
}
}
}

/// As [`try_zeroed_slice_box`](try_zeroed_slice_box), but unwraps for you.
Expand Down