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

Adding a zeroize function for flat types #1045

Merged
merged 13 commits into from
Jan 31, 2024
14 changes: 14 additions & 0 deletions zeroize/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -795,6 +795,20 @@ unsafe fn volatile_set<T: Copy + Sized>(dst: *mut T, src: T, count: usize) {
}
}

/// Zeroizes a flat type/struct. Only zeroizes the values that it owns, and it does not work on
/// dynamically sized values or trait objects.
#[inline(always)]
pub fn zeroize_flat_type<T: Sized>(data: &mut T) {
nstilt1 marked this conversation as resolved.
Show resolved Hide resolved
let size = mem::size_of::<T>();
let data_ptr = (data as *mut T).cast::<u8>();
// Safety:
//
// This is safe because `mem::size_of<T>()` returns the exact size of the object in memory, and
// `data_ptr` points directly to the first byte of the data.
unsafe { volatile_set(data_ptr, 0, size) }
atomic_fence()
}

/// Internal module used as support for `AssertZeroizeOnDrop`.
#[doc(hidden)]
pub mod __internal {
Expand Down