Skip to content

Commit 74cd1ed

Browse files
committed
use_file: Use AtomicI32 instead of AtomicUsize to avoid conversions.
All the targets that use this support AtomicI32.
1 parent 767e7dd commit 74cd1ed

File tree

1 file changed

+8
-6
lines changed

1 file changed

+8
-6
lines changed

src/use_file.rs

+8-6
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use core::{
77
cell::UnsafeCell,
88
ffi::c_void,
99
mem::MaybeUninit,
10-
sync::atomic::{AtomicUsize, Ordering::Relaxed},
10+
sync::atomic::{AtomicI32, Ordering::Relaxed},
1111
};
1212

1313
/// For all platforms, we use `/dev/urandom` rather than `/dev/random`.
@@ -17,7 +17,7 @@ use core::{
1717
/// - On AIX, /dev/urandom will "provide cryptographically secure output".
1818
/// - On Haiku and QNX Neutrino they are identical.
1919
const FILE_PATH: &[u8] = b"/dev/urandom\0";
20-
const FD_UNINIT: usize = usize::max_value();
20+
const FD_UNINIT: i32 = i32::MIN;
2121

2222
pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
2323
let fd = get_rng_fd()?;
@@ -30,11 +30,12 @@ pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
3030
// bytes. The file will be opened exactly once. All subsequent calls will
3131
// return the same file descriptor. This file descriptor is never closed.
3232
fn get_rng_fd() -> Result<libc::c_int, Error> {
33-
static FD: AtomicUsize = AtomicUsize::new(FD_UNINIT);
33+
const _: () = assert!(core::mem::size_of::<libc::c_int>() == core::mem::size_of::<i32>());
34+
static FD: AtomicI32 = AtomicI32::new(FD_UNINIT);
3435
fn get_fd() -> Option<libc::c_int> {
3536
match FD.load(Relaxed) {
3637
FD_UNINIT => None,
37-
val => Some(val as libc::c_int),
38+
val => Some(val),
3839
}
3940
}
4041

@@ -59,8 +60,9 @@ fn get_rng_fd() -> Result<libc::c_int, Error> {
5960

6061
let fd = open_readonly(FILE_PATH)?;
6162
// The fd always fits in a usize without conflicting with FD_UNINIT.
62-
debug_assert!(fd >= 0 && (fd as usize) < FD_UNINIT);
63-
FD.store(fd as usize, Relaxed);
63+
debug_assert!(fd >= 0);
64+
const _: () = assert!(FD_UNINIT < 0);
65+
FD.store(fd, Relaxed);
6466

6567
Ok(fd)
6668
}

0 commit comments

Comments
 (0)