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 FromBytes::getrandom method #814

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
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
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ __internal_use_only_features_that_work_on_stable = ["alloc", "derive", "simd"]

[dependencies]
zerocopy-derive = { version = "=0.8.0-alpha.5", path = "zerocopy-derive", optional = true }
getrandom = { version = "0.2", optional = true }

# The "associated proc macro pattern" ensures that the versions of zerocopy and
# zerocopy-derive remain equal, even if the 'derive' feature isn't used.
Expand Down
34 changes: 34 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2513,6 +2513,40 @@ pub unsafe trait FromBytes: FromZeros {
Ref::<_, Unalign<Self>>::new_unaligned_from_suffix(bytes)
.map(|(_, r)| r.read().into_inner())
}

/// Generate random value of `Self` using OS randomness source
/// (see the table in the [`getrandom`] crate docs for more information).
///
/// # Examples
/// ```
/// # fn main() -> Result<(), getrandom::Error> {
/// use zerocopy::FromBytes;
///
/// let seed = u32::getrandom()?;
/// let key: [u8; 16] = FromBytes::getrandom()?;
/// # Ok(()) }
/// ```
#[cfg(feature = "getrandom")]
#[inline]
fn getrandom() -> Result<Self, getrandom::Error>
where
Self: Sized,
{
let mut value = MaybeUninit::<Self>::uninit();
// SAFETY: it's safe to cast `&mut MaybeUninit<T>` to `&mut [MaybeUninit<u8>]`
// with slice length equal to `size_of::<T>()`. The compiler will ensure that
// `T` isn't too large.
unsafe {
let ptr: *mut MaybeUninit<u8> = value.as_mut_ptr().cast();
let size = core::mem::size_of::<Self>();
let uninit_bytes = core::slice::from_raw_parts_mut(ptr, size);
getrandom::getrandom_uninit(uninit_bytes)?;
};
// SAFETY: when `getrandom_uninit` returns `Ok` all bytes in `uninit_bytes`
// (and thus in `value`) are properly initialized. Any bit-sequence is valid
// for `T: FromBytes`, so we can safely execute `assume_init` on `value`.
Ok(unsafe { value.assume_init() })
}
}

/// Analyzes whether a type is [`IntoBytes`].
Expand Down
Loading