|
2 | 2 | use crate::Error;
|
3 | 3 | use core::{mem::MaybeUninit, slice};
|
4 | 4 |
|
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(); |
8 | 9 | // SAFETY: the created slice has the same size as `res`
|
9 | 10 | let dst = unsafe {
|
10 | 11 | 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>()) |
12 | 13 | };
|
13 |
| - crate::fill_uninit(dst)?; |
| 14 | + if secure { |
| 15 | + crate::fill_uninit(dst)?; |
| 16 | + } else { |
| 17 | + crate::insecure_fill_uninit(dst)?; |
| 18 | + } |
14 | 19 | // SAFETY: `dst` has been fully initialized by `imp::fill_inner`
|
15 | 20 | // since it returned `Ok`.
|
16 | 21 | Ok(unsafe { res.assume_init() })
|
17 | 22 | }
|
18 | 23 |
|
| 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 | + |
19 | 29 | /// Default implementation of `inner_u64` on top of `getrandom::fill_uninit`
|
20 | 30 | 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) } |
31 | 32 | }
|
32 | 33 |
|
33 | 34 | /// Default implementation of `insecure_fill_inner` on top of `getrandom::fill_uninit`
|
34 | 35 | pub fn insecure_fill_uninit(dst: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
|
35 | 36 | crate::fill_uninit(dst).map(|_| ())
|
36 | 37 | }
|
37 | 38 |
|
38 |
| -/// Default implementation of `inner_u32` on top of `getrandom::u32` |
| 39 | +/// Default implementation of `inner_u32` on top of `getrandom::insecure_fill_uninit` |
39 | 40 | pub fn insecure_u32() -> Result<u32, Error> {
|
40 |
| - crate::u32() |
| 41 | + unsafe { default_impl(false) } |
41 | 42 | }
|
42 | 43 |
|
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` |
44 | 45 | pub fn insecure_u64() -> Result<u64, Error> {
|
45 |
| - crate::u64() |
| 46 | + unsafe { default_impl(false) } |
46 | 47 | }
|
0 commit comments