Skip to content
New issue

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

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

Already on GitHub? # to your account

Add FromBytes::new_vec_zeroed #112

Merged
merged 1 commit into from
Oct 30, 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
29 changes: 29 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,7 @@ extern crate alloc;
#[cfg(feature = "alloc")]
use {
alloc::boxed::Box,
alloc::vec::Vec,
core::{alloc::Layout, ptr::NonNull},
};

Expand Down Expand Up @@ -465,6 +466,34 @@ pub unsafe trait FromBytes {
}
}
}

/// Creates a `Vec<Self>` from zeroed bytes.
///
/// This function is useful for allocating large values of `Vec`s and
/// zero-initializing them, without ever creating a temporary instance of
/// `[Self; _]` (or many temporary instances of `Self`) on the stack. For
/// example, `u8::new_vec_zeroed(1048576)` will allocate directly on the
/// heap; it does not require storing intermediate values on the stack.
///
/// On systems that use a heap implementation that supports allocating from
/// pre-zeroed memory, using `new_vec_zeroed` may have performance benefits.
///
/// If `Self` is a zero-sized type, then this function will return a
/// `Vec<Self>` that has the correct `len`. Such a `Vec` cannot contain any
/// actual information, but its `len()` property will report the correct
/// value.
///
/// # Panics
///
/// * Panics if `size_of::<Self>() * len` overflows.
/// * Panics if allocation of `size_of::<Self>() * len` bytes fails.
#[cfg(feature = "alloc")]
fn new_vec_zeroed(len: usize) -> Vec<Self>
where
Self: Sized,
{
Self::new_box_slice_zeroed(len).into()
}
}

/// Types which are safe to treat as an immutable byte slice.
Expand Down