Skip to content

Commit

Permalink
Introduce truncate function
Browse files Browse the repository at this point in the history
  • Loading branch information
newpavlov committed Nov 25, 2024
1 parent 3ce091d commit ed419ca
Show file tree
Hide file tree
Showing 4 changed files with 13 additions and 5 deletions.
2 changes: 1 addition & 1 deletion src/backends/rdrand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ unsafe fn rdrand_exact(dest: &mut [MaybeUninit<u8>]) -> Option<()> {
#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "rdrand")]
unsafe fn rdrand_u32() -> Option<u32> {
rdrand().map(|val| u32::try_from(val & u64::from(u32::MAX)).unwrap())
rdrand().map(crate::utils::truncate)
}

#[cfg(target_arch = "x86_64")]
Expand Down
8 changes: 5 additions & 3 deletions src/backends/rndr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@
//!
//! Arm Architecture Reference Manual for A-profile architecture:
//! ARM DDI 0487K.a, ID032224, D23.2.147 RNDR, Random Number
use crate::{util::slice_as_uninit, Error};
use crate::{
util::{slice_as_uninit, truncate},
Error,
};
use core::arch::asm;
use core::mem::{size_of, MaybeUninit};

Expand Down Expand Up @@ -105,8 +108,7 @@ pub fn inner_u32() -> Result<u32, Error> {
if is_rndr_available() {
// SAFETY: after this point, we know the `rand` target feature is enabled
let res = unsafe { rndr() };
res.map(|val| u32::try_from(val & u64::from(u32::MAX)).unwrap())
.ok_or(Error::RNDR_FAILURE)
res.map(truncate).ok_or(Error::RNDR_FAILURE)
} else {
Err(Error::RNDR_NOT_AVAILABLE)
}
Expand Down
3 changes: 2 additions & 1 deletion src/backends/wasi_p2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ use core::mem::MaybeUninit;
use wasi::random::random::get_random_u64;

pub fn inner_u32() -> Result<u32, Error> {
Ok(get_random_u64() as u64)
let val = get_random_u64();
Ok(crate::utils::truncate(val))
}

pub fn inner_u64() -> Result<u32, Error> {
Expand Down
5 changes: 5 additions & 0 deletions src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,3 +75,8 @@ pub fn inner_u64() -> Result<u64, Error> {
// since it returned `Ok`.
Ok(unsafe { res.assume_init() })
}

/// Truncates `u64` and returns the lower 32 bits as `u32`
pub(crate) fn truncate(val: u64) -> u32 {
u32::try_from(val & u64::from(u32::MAX)).expect("The higher 32 bits are masked")
}

0 comments on commit ed419ca

Please sign in to comment.