Skip to content

Commit c79a8bd

Browse files
committed
tweak default impls
1 parent 0b7b141 commit c79a8bd

File tree

1 file changed

+20
-19
lines changed

1 file changed

+20
-19
lines changed

src/default_impls.rs

Lines changed: 20 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -2,45 +2,46 @@
22
use crate::Error;
33
use core::{mem::MaybeUninit, slice};
44

5-
/// Default implementation of `inner_u32` on top of `getrandom::fill_uninit`
6-
pub fn u32() -> Result<u32, Error> {
7-
let mut res = MaybeUninit::<u32>::uninit();
5+
#[inline(always)]
6+
#[allow(unused_unsafe)]
7+
unsafe fn default_impl<T>(secure: bool) -> Result<T, Error> {
8+
let mut res = MaybeUninit::<T>::uninit();
89
// SAFETY: the created slice has the same size as `res`
910
let dst = unsafe {
1011
let p: *mut MaybeUninit<u8> = res.as_mut_ptr().cast();
11-
slice::from_raw_parts_mut(p, core::mem::size_of::<u32>())
12+
slice::from_raw_parts_mut(p, core::mem::size_of::<T>())
1213
};
13-
crate::fill_uninit(dst)?;
14+
if secure {
15+
crate::fill_uninit(dst)?;
16+
} else {
17+
crate::insecure_fill_uninit(dst)?;
18+
}
1419
// SAFETY: `dst` has been fully initialized by `imp::fill_inner`
1520
// since it returned `Ok`.
1621
Ok(unsafe { res.assume_init() })
1722
}
1823

24+
/// Default implementation of `inner_u32` on top of `getrandom::fill_uninit`
25+
pub fn u32() -> Result<u32, Error> {
26+
unsafe { default_impl(true) }
27+
}
28+
1929
/// Default implementation of `inner_u64` on top of `getrandom::fill_uninit`
2030
pub fn u64() -> Result<u64, Error> {
21-
let mut res = MaybeUninit::<u64>::uninit();
22-
// SAFETY: the created slice has the same size as `res`
23-
let dst = unsafe {
24-
let p: *mut MaybeUninit<u8> = res.as_mut_ptr().cast();
25-
slice::from_raw_parts_mut(p, core::mem::size_of::<u64>())
26-
};
27-
crate::fill_uninit(dst)?;
28-
// SAFETY: `dst` has been fully initialized by `imp::fill_inner`
29-
// since it returned `Ok`.
30-
Ok(unsafe { res.assume_init() })
31+
unsafe { default_impl(true) }
3132
}
3233

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

38-
/// Default implementation of `inner_u32` on top of `getrandom::u32`
39+
/// Default implementation of `inner_u32` on top of `getrandom::insecure_fill_uninit`
3940
pub fn insecure_u32() -> Result<u32, Error> {
40-
crate::u32()
41+
unsafe { default_impl(false) }
4142
}
4243

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

0 commit comments

Comments
 (0)