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 functions for writing zeroed bytes to &mut impl Zeroable and &mut [impl Zeroable] #193

Merged
merged 4 commits into from
Sep 5, 2023
Merged
Changes from 3 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
48 changes: 48 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -398,3 +398,51 @@ pub fn try_cast_slice_mut<
) -> Result<&mut [B], PodCastError> {
unsafe { internal::try_cast_slice_mut(a) }
}

/// Fill all bytes of `target` with zeroes (see [`Zeroable`]).
///
/// This is similar to `*target = Zeroable::zeroed()`, but guarantees that any
/// padding bytes in `target` are zeroed as well.
///
/// See also [`fill_zero`], if you have a slice rather than a single value.
#[inline]
pub fn write_zero<T: Zeroable>(target: &mut T) {
struct EnsureZeroWrite<T>(*mut T);
impl<T> Drop for EnsureZeroWrite<T> {
#[inline(always)]
fn drop(&mut self) {
unsafe {
core::ptr::write_bytes(
self.0.cast::<u8>(),
0u8,
core::mem::size_of::<T>(),
);
Lokathor marked this conversation as resolved.
Show resolved Hide resolved
}
}
}
unsafe {
let guard = EnsureZeroWrite(target);
core::ptr::drop_in_place(guard.0);
drop(guard);
}
}

/// Fill all bytes of `slice` with zeroes (see [`Zeroable`]).
///
/// This is similar to `slice.fill(Zeroable::zeroed())`, but guarantees that any
/// padding bytes in `slice` are zeroed as well.
///
/// See also [`write_zero`], which zeroes all bytes of a single value rather
/// than a slice.
#[inline]
pub fn fill_zero<T: Zeroable>(slice: &mut [T]) {
if core::mem::needs_drop::<T>() {
// If `T` needs to be dropped then we have to do this one item at a time, in
// case one of the intermediate drops does a panic.
slice.iter_mut().for_each(write_zero);
} else {
// Otherwise we can be really fast and just fill everthing with zeros.
let len = core::mem::size_of_val::<[T]>(slice);
unsafe { core::ptr::write_bytes(slice.as_mut_ptr() as *mut u8, 0u8, len) }
}
}