Skip to content

Commit 387248f

Browse files
authored
Remove impl From<NonZeroU32> for Error and Error::code (#507)
Also adds `Error::{new_custom, new_internal}` methods and changes return type of `__getrandom_custom` to `Result<(), getrandom::Error>`.
1 parent 0f787bc commit 387248f

File tree

5 files changed

+44
-46
lines changed

5 files changed

+44
-46
lines changed

CHANGELOG.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,17 +9,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
99
### Breaking Changes
1010
- Update MSRV to 1.60 [#472]
1111
- Remove support of the `wasm32-wasi` target (use `wasm32-wasip1` or `wasm32-wasip2` instead) [#499]
12+
- Remove `impl From<NonZeroU32> for Error` and `Error::code` method [#507]
1213

1314
### Changed
1415
- Switch to `futex` on Linux and to `nanosleep`-based wait loop on other targets
1516
in the `use_file` backend [#490]
1617

1718
### Added
1819
- `wasm32-wasip1` and `wasm32-wasip2` support [#499]
20+
- `Error::new_custom` method [#507]
1921

2022
[#472]: https://github.com/rust-random/getrandom/pull/472
2123
[#490]: https://github.com/rust-random/getrandom/pull/490
2224
[#499]: https://github.com/rust-random/getrandom/pull/499
25+
[#507]: https://github.com/rust-random/getrandom/pull/507
2326

2427
## [0.2.15] - 2024-05-06
2528
### Added

src/custom.rs

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,10 @@
11
//! An implementation which calls out to an externally defined function.
22
use crate::Error;
3-
use core::{mem::MaybeUninit, num::NonZeroU32};
3+
use core::mem::MaybeUninit;
44

55
pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
66
extern "Rust" {
7-
fn __getrandom_custom(dest: *mut u8, len: usize) -> u32;
8-
}
9-
let ret = unsafe { __getrandom_custom(dest.as_mut_ptr().cast(), dest.len()) };
10-
match NonZeroU32::new(ret) {
11-
None => Ok(()),
12-
Some(code) => Err(Error::from(code)),
7+
fn __getrandom_custom(dest: *mut u8, len: usize) -> Result<(), Error>;
138
}
9+
unsafe { __getrandom_custom(dest.as_mut_ptr().cast(), dest.len()) }
1410
}

src/error.rs

Lines changed: 26 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -20,44 +20,38 @@ use core::{fmt, num::NonZeroU32};
2020
#[derive(Copy, Clone, Eq, PartialEq)]
2121
pub struct Error(NonZeroU32);
2222

23-
const fn internal_error(n: u16) -> Error {
24-
// SAFETY: code > 0 as INTERNAL_START > 0 and adding n won't overflow a u32.
25-
let code = Error::INTERNAL_START + (n as u32);
26-
Error(unsafe { NonZeroU32::new_unchecked(code) })
27-
}
28-
2923
impl Error {
3024
/// This target/platform is not supported by `getrandom`.
31-
pub const UNSUPPORTED: Error = internal_error(0);
25+
pub const UNSUPPORTED: Error = Self::new_internal(0);
3226
/// The platform-specific `errno` returned a non-positive value.
33-
pub const ERRNO_NOT_POSITIVE: Error = internal_error(1);
27+
pub const ERRNO_NOT_POSITIVE: Error = Self::new_internal(1);
3428
/// Encountered an unexpected situation which should not happen in practice.
35-
pub const UNEXPECTED: Error = internal_error(2);
29+
pub const UNEXPECTED: Error = Self::new_internal(2);
3630
/// Call to [`CCRandomGenerateBytes`](https://opensource.apple.com/source/CommonCrypto/CommonCrypto-60074/include/CommonRandom.h.auto.html) failed
3731
/// on iOS, tvOS, or waatchOS.
3832
// TODO: Update this constant name in the next breaking release.
39-
pub const IOS_SEC_RANDOM: Error = internal_error(3);
33+
pub const IOS_SEC_RANDOM: Error = Self::new_internal(3);
4034
/// Call to Windows [`RtlGenRandom`](https://docs.microsoft.com/en-us/windows/win32/api/ntsecapi/nf-ntsecapi-rtlgenrandom) failed.
41-
pub const WINDOWS_RTL_GEN_RANDOM: Error = internal_error(4);
35+
pub const WINDOWS_RTL_GEN_RANDOM: Error = Self::new_internal(4);
4236
/// RDRAND instruction failed due to a hardware issue.
43-
pub const FAILED_RDRAND: Error = internal_error(5);
37+
pub const FAILED_RDRAND: Error = Self::new_internal(5);
4438
/// RDRAND instruction unsupported on this target.
45-
pub const NO_RDRAND: Error = internal_error(6);
39+
pub const NO_RDRAND: Error = Self::new_internal(6);
4640
/// The environment does not support the Web Crypto API.
47-
pub const WEB_CRYPTO: Error = internal_error(7);
41+
pub const WEB_CRYPTO: Error = Self::new_internal(7);
4842
/// Calling Web Crypto API `crypto.getRandomValues` failed.
49-
pub const WEB_GET_RANDOM_VALUES: Error = internal_error(8);
43+
pub const WEB_GET_RANDOM_VALUES: Error = Self::new_internal(8);
5044
/// On VxWorks, call to `randSecure` failed (random number generator is not yet initialized).
51-
pub const VXWORKS_RAND_SECURE: Error = internal_error(11);
45+
pub const VXWORKS_RAND_SECURE: Error = Self::new_internal(11);
5246
/// Node.js does not have the `crypto` CommonJS module.
53-
pub const NODE_CRYPTO: Error = internal_error(12);
47+
pub const NODE_CRYPTO: Error = Self::new_internal(12);
5448
/// Calling Node.js function `crypto.randomFillSync` failed.
55-
pub const NODE_RANDOM_FILL_SYNC: Error = internal_error(13);
49+
pub const NODE_RANDOM_FILL_SYNC: Error = Self::new_internal(13);
5650
/// Called from an ES module on Node.js. This is unsupported, see:
5751
/// <https://docs.rs/getrandom#nodejs-es-module-support>.
58-
pub const NODE_ES_MODULE: Error = internal_error(14);
52+
pub const NODE_ES_MODULE: Error = Self::new_internal(14);
5953
/// Calling Windows ProcessPrng failed.
60-
pub const WINDOWS_PROCESS_PRNG: Error = internal_error(15);
54+
pub const WINDOWS_PROCESS_PRNG: Error = Self::new_internal(15);
6155

6256
/// Codes below this point represent OS Errors (i.e. positive i32 values).
6357
/// Codes at or above this point, but below [`Error::CUSTOM_START`] are
@@ -108,13 +102,18 @@ impl Error {
108102
}
109103
}
110104

111-
/// Extract the bare error code.
112-
///
113-
/// This code can either come from the underlying OS, or be a custom error.
114-
/// Use [`Error::raw_os_error()`] to disambiguate.
115-
#[inline]
116-
pub const fn code(self) -> NonZeroU32 {
117-
self.0
105+
/// Creates a new instance of an `Error` from a particular custom error code.
106+
pub const fn new_custom(n: u16) -> Error {
107+
// SAFETY: code > 0 as CUSTOM_START > 0 and adding n won't overflow a u32.
108+
let code = Error::CUSTOM_START + (n as u32);
109+
Error(unsafe { NonZeroU32::new_unchecked(code) })
110+
}
111+
112+
/// Creates a new instance of an `Error` from a particular internal error code.
113+
const fn new_internal(n: u16) -> Error {
114+
// SAFETY: code > 0 as INTERNAL_START > 0 and adding n won't overflow a u32.
115+
let code = Error::INTERNAL_START + (n as u32);
116+
Error(unsafe { NonZeroU32::new_unchecked(code) })
118117
}
119118
}
120119

@@ -153,12 +152,6 @@ impl fmt::Display for Error {
153152
}
154153
}
155154

156-
impl From<NonZeroU32> for Error {
157-
fn from(code: NonZeroU32) -> Self {
158-
Self(code)
159-
}
160-
}
161-
162155
fn internal_desc(error: Error) -> Option<&'static str> {
163156
match error {
164157
Error::UNSUPPORTED => Some("getrandom: this target is not supported"),

src/lib.rs

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -105,8 +105,10 @@
105105
//! signature:
106106
//!
107107
//! ```
108+
//! use getrandom::Error;
109+
//!
108110
//! #[no_mangle]
109-
//! unsafe fn __getrandom_custom(dest: *mut u8, len: usize) -> u32 {
111+
//! unsafe extern "Rust" fn __getrandom_custom(dest: *mut u8, len: usize) -> Result<(), Error> {
110112
//! todo!()
111113
//! }
112114
//! ```
@@ -126,9 +128,11 @@
126128
//! it gets pulled nevertheless by one of your dependencies, then you can
127129
//! use the following custom backend which always returns "unsupported" error:
128130
//! ```
131+
//! use getrandom::Error;
132+
//!
129133
//! #[no_mangle]
130-
//! unsafe fn __getrandom_custom(dest: *mut u8, len: usize) -> u32 {
131-
//! getrandom::Error::UNSUPPORTED.code().get()
134+
//! unsafe extern "Rust" fn __getrandom_custom(dest: *mut u8, len: usize) -> Result<(), Error> {
135+
//! Err(Error::UNSUPPORTED)
132136
//! }
133137
//! ```
134138
//!

tests/mod.rs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,8 @@ fn test_multithreading() {
160160

161161
#[cfg(getrandom_backend = "custom")]
162162
mod custom {
163+
use getrandom::Error;
164+
163165
struct Xoshiro128PlusPlus {
164166
s: [u32; 4],
165167
}
@@ -204,13 +206,13 @@ mod custom {
204206
//
205207
// WARNING: this custom implementation is for testing purposes ONLY!
206208
#[no_mangle]
207-
unsafe fn __getrandom_custom(dest: *mut u8, len: usize) -> u32 {
209+
unsafe extern "Rust" fn __getrandom_custom(dest: *mut u8, len: usize) -> Result<(), Error> {
208210
use std::time::{SystemTime, UNIX_EPOCH};
209211

210212
assert_ne!(len, 0);
211213

212214
if len == 142 {
213-
return getrandom::Error::CUSTOM_START + 142;
215+
return Err(Error::new_custom(142));
214216
}
215217

216218
let dest_u32 = dest.cast::<u32>();
@@ -227,7 +229,7 @@ mod custom {
227229
core::ptr::write_unaligned(dest.add(i), val as u8);
228230
}
229231
}
230-
0
232+
Ok(())
231233
}
232234

233235
// Test that enabling the custom feature indeed uses the custom implementation

0 commit comments

Comments
 (0)