Skip to content

Commit

Permalink
Use i32::unsigned_abs() instead of (-x) as u32.
Browse files Browse the repository at this point in the history
(-x) overflows when x is the minimum value, where `x.unsigned_abs()`
does the right thing.
  • Loading branch information
briansmith committed May 29, 2024
1 parent 6cdf4a3 commit 1d82297
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 9 deletions.
15 changes: 7 additions & 8 deletions src/hermit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,6 @@
use crate::Error;
use core::{mem::MaybeUninit, num::NonZeroU32};

/// Minimum return value which we should get from syscalls in practice,
/// because Hermit uses positive `i32`s for error codes:
/// https://github.com/hermitcore/libhermit-rs/blob/main/src/errno.rs
const MIN_RET_CODE: isize = -(i32::MAX as isize);

extern "C" {
fn sys_read_entropy(buffer: *mut u8, length: usize, flags: u32) -> isize;
}
Expand All @@ -18,9 +13,13 @@ pub fn getrandom_inner(mut dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
if res > 0 && (res as usize) <= dest.len() {
dest = &mut dest[res as usize..];
} else {
let err = match res {
MIN_RET_CODE..=-1 => NonZeroU32::new(-res as u32).unwrap().into(),
_ => Error::UNEXPECTED,
let err = if res < 0 {
u32::try_from(res.unsigned_abs())
.ok()
.and_then(NonZeroU32::new)
.map_or(Error::UNEXPECTED, Error::from)
} else {
Error::UNEXPECTED
};
return Err(err);
}
Expand Down
2 changes: 1 addition & 1 deletion src/solid.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,6 @@ pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
} else {
// ITRON error numbers are always negative, so we negate it so that it
// falls in the dedicated OS error range (1..INTERNAL_START).
Err(NonZeroU32::new((-ret) as u32).unwrap().into())
Err(NonZeroU32::new(ret.unsigned_abs()).unwrap().into())
}
}

0 comments on commit 1d82297

Please sign in to comment.