Skip to content

Commit 4e3bbef

Browse files
committed
Move __getrandom_custom definition into an unnamed block
This supersedes #341, and makes the following changes - All the code for implementing `__getrandom_custom` is now in an **named** `const` block (unnamed consts require Rust 1.37) - I found this approch [here](https://internals.rust-lang.org/t/anonymous-modules/15441) - Nothing inside the block can be referenced outside of it - `__getrandom_custom` is marked `unsafe` - It can't be accessed externally, but is "logically" unsafe as it dereferences raw pointers - The type of the function is moved to a typedef, so we can check that the defined type matches that of `getrandom:getrandom`. - Use `::core::result::Result` instead of `Result` - Similar to use use of `from_raw_parts_mut` this prevents compilation errors if `Result` is redefined. Signed-off-by: Joe Richey <[email protected]>
1 parent 93c3074 commit 4e3bbef

File tree

1 file changed

+16
-9
lines changed

1 file changed

+16
-9
lines changed

src/custom.rs

+16-9
Original file line numberDiff line numberDiff line change
@@ -76,16 +76,23 @@ use core::{mem::MaybeUninit, num::NonZeroU32};
7676
#[cfg_attr(docsrs, doc(cfg(feature = "custom")))]
7777
macro_rules! register_custom_getrandom {
7878
($path:path) => {
79-
// We use an extern "C" function to get the guarantees of a stable ABI.
80-
#[no_mangle]
81-
extern "C" fn __getrandom_custom(dest: *mut u8, len: usize) -> u32 {
82-
let f: fn(&mut [u8]) -> Result<(), $crate::Error> = $path;
83-
let slice = unsafe { ::core::slice::from_raw_parts_mut(dest, len) };
84-
match f(slice) {
85-
Ok(()) => 0,
86-
Err(e) => e.code().get(),
79+
// TODO(MSRV 1.37): change to unnamed block
80+
const __getrandom_internal: () = {
81+
// Make sure the passed function has the type of getrandom::getrandom
82+
type F = fn(&mut [u8]) -> ::core::result::Result<(), $crate::Error>;
83+
const getrandom_fn: F = $crate::getrandom;
84+
85+
// We use an extern "C" function to get the guarantees of a stable ABI.
86+
#[no_mangle]
87+
unsafe extern "C" fn __getrandom_custom(dest: *mut u8, len: usize) -> u32 {
88+
let f: F = $path;
89+
let slice = ::core::slice::from_raw_parts_mut(dest, len);
90+
match f(slice) {
91+
Ok(()) => 0,
92+
Err(e) => e.code().get(),
93+
}
8794
}
88-
}
95+
};
8996
};
9097
}
9198

0 commit comments

Comments
 (0)