Skip to content

Commit

Permalink
tweak default impls
Browse files Browse the repository at this point in the history
  • Loading branch information
newpavlov committed Nov 28, 2024
1 parent 0b7b141 commit c79a8bd
Showing 1 changed file with 20 additions and 19 deletions.
39 changes: 20 additions & 19 deletions src/default_impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,45 +2,46 @@
use crate::Error;
use core::{mem::MaybeUninit, slice};

/// Default implementation of `inner_u32` on top of `getrandom::fill_uninit`
pub fn u32() -> Result<u32, Error> {
let mut res = MaybeUninit::<u32>::uninit();
#[inline(always)]
#[allow(unused_unsafe)]
unsafe fn default_impl<T>(secure: bool) -> Result<T, Error> {
let mut res = MaybeUninit::<T>::uninit();
// SAFETY: the created slice has the same size as `res`
let dst = unsafe {
let p: *mut MaybeUninit<u8> = res.as_mut_ptr().cast();
slice::from_raw_parts_mut(p, core::mem::size_of::<u32>())
slice::from_raw_parts_mut(p, core::mem::size_of::<T>())
};
crate::fill_uninit(dst)?;
if secure {
crate::fill_uninit(dst)?;
} else {
crate::insecure_fill_uninit(dst)?;
}
// SAFETY: `dst` has been fully initialized by `imp::fill_inner`
// since it returned `Ok`.
Ok(unsafe { res.assume_init() })
}

/// Default implementation of `inner_u32` on top of `getrandom::fill_uninit`
pub fn u32() -> Result<u32, Error> {
unsafe { default_impl(true) }
}

/// Default implementation of `inner_u64` on top of `getrandom::fill_uninit`
pub fn u64() -> Result<u64, Error> {
let mut res = MaybeUninit::<u64>::uninit();
// SAFETY: the created slice has the same size as `res`
let dst = unsafe {
let p: *mut MaybeUninit<u8> = res.as_mut_ptr().cast();
slice::from_raw_parts_mut(p, core::mem::size_of::<u64>())
};
crate::fill_uninit(dst)?;
// SAFETY: `dst` has been fully initialized by `imp::fill_inner`
// since it returned `Ok`.
Ok(unsafe { res.assume_init() })
unsafe { default_impl(true) }
}

/// Default implementation of `insecure_fill_inner` on top of `getrandom::fill_uninit`
pub fn insecure_fill_uninit(dst: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
crate::fill_uninit(dst).map(|_| ())
}

/// Default implementation of `inner_u32` on top of `getrandom::u32`
/// Default implementation of `inner_u32` on top of `getrandom::insecure_fill_uninit`
pub fn insecure_u32() -> Result<u32, Error> {
crate::u32()
unsafe { default_impl(false) }
}

/// Default implementation of `inner_insecure_u64` on top of `getrandom::u64`
/// Default implementation of `inner_insecure_u64` on top of `getrandom::insecure_fill_uninit`
pub fn insecure_u64() -> Result<u64, Error> {
crate::u64()
unsafe { default_impl(false) }
}

0 comments on commit c79a8bd

Please sign in to comment.