Skip to content

Commit 52d3e0d

Browse files
committed
tweak code
1 parent 7e2b951 commit 52d3e0d

File tree

1 file changed

+11
-10
lines changed

1 file changed

+11
-10
lines changed

src/linux_android_with_fallback.rs

+11-10
Original file line numberDiff line numberDiff line change
@@ -23,11 +23,12 @@ fn init() -> NonNull<c_void> {
2323
let res_ptr = match NonNull::new(raw_ptr) {
2424
Some(fptr) => {
2525
let getrandom_fn = unsafe { mem::transmute::<NonNull<c_void>, GetRandomFn>(fptr) };
26+
let dangling_ptr = ptr::NonNull::dangling().as_ptr();
2627
// Check that `getrandom` syscall is supported by kernel
27-
let res = unsafe { getrandom_fn(ptr::NonNull::dangling().as_ptr(), 0, 0) };
28+
let res = unsafe { getrandom_fn(dangling_ptr, 0, 0) };
2829
if cfg!(getrandom_test_linux_fallback) {
2930
NOT_AVAILABLE
30-
} else if res < 0 {
31+
} else if res.is_negative() {
3132
match util_libc::last_os_error().raw_os_error() {
3233
Some(libc::ENOSYS) => NOT_AVAILABLE, // No kernel support
3334
// The fallback on EPERM is intentionally not done on Android since this workaround
@@ -48,6 +49,12 @@ fn init() -> NonNull<c_void> {
4849
res_ptr
4950
}
5051

52+
// prevent inlining of the fallback implementation
53+
#[inline(never)]
54+
fn use_file_fallback(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
55+
use_file::getrandom_inner(dest)
56+
}
57+
5158
pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
5259
// Despite being only a single atomic variable, we still cannot always use
5360
// Ordering::Relaxed, as we need to make sure a successful call to `init`
@@ -62,15 +69,9 @@ pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
6269
};
6370

6471
if fptr == NOT_AVAILABLE {
65-
// prevent inlining of the fallback implementation
66-
#[inline(never)]
67-
fn inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
68-
use_file::getrandom_inner(dest)
69-
}
70-
71-
inner(dest)
72+
use_file_fallback(dest)
7273
} else {
73-
// note: `transume` is currently the only way to get function pointer
74+
// note: `transume` is currently the only way to convert pointer into function reference
7475
let getrandom_fn = unsafe { mem::transmute::<NonNull<c_void>, GetRandomFn>(fptr) };
7576
util_libc::sys_fill_exact(dest, |buf| unsafe {
7677
getrandom_fn(buf.as_mut_ptr().cast(), buf.len(), 0)

0 commit comments

Comments
 (0)