Skip to content

Commit 0ff946c

Browse files
authored
Make getrandom a non-pub dep; rename feature to os_rng (#1537)
1 parent c1f865f commit 0ff946c

19 files changed

+95
-49
lines changed

.github/workflows/gh-pages.yml

+1-1
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ jobs:
3030
RUSTDOCFLAGS: --cfg doc_cfg
3131
# --all builds all crates, but with default features for other crates (okay in this case)
3232
run: |
33-
cargo doc --all --features nightly,serde,getrandom,small_rng
33+
cargo doc --all --all-features --no-deps
3434
cp utils/redirect.html target/doc/index.html
3535
rm target/doc/.lock
3636

.github/workflows/test.yml

+3-3
Original file line numberDiff line numberDiff line change
@@ -90,8 +90,8 @@ jobs:
9090
- name: Test rand
9191
run: |
9292
cargo test --target ${{ matrix.target }} --lib --tests --no-default-features
93-
cargo build --target ${{ matrix.target }} --no-default-features --features alloc,getrandom,small_rng,unbiased
94-
cargo test --target ${{ matrix.target }} --lib --tests --no-default-features --features=alloc,getrandom,small_rng
93+
cargo build --target ${{ matrix.target }} --no-default-features --features alloc,os_rng,small_rng,unbiased
94+
cargo test --target ${{ matrix.target }} --lib --tests --no-default-features --features=alloc,os_rng,small_rng
9595
cargo test --target ${{ matrix.target }} --examples
9696
- name: Test rand (all stable features)
9797
run: |
@@ -100,7 +100,7 @@ jobs:
100100
run: |
101101
cargo test --target ${{ matrix.target }} --manifest-path rand_core/Cargo.toml
102102
cargo test --target ${{ matrix.target }} --manifest-path rand_core/Cargo.toml --no-default-features
103-
cargo test --target ${{ matrix.target }} --manifest-path rand_core/Cargo.toml --no-default-features --features=alloc,getrandom
103+
cargo test --target ${{ matrix.target }} --manifest-path rand_core/Cargo.toml --no-default-features --features=alloc,os_rng
104104
- name: Test rand_distr
105105
run: |
106106
cargo test --target ${{ matrix.target }} --manifest-path rand_distr/Cargo.toml --features=serde

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ You may also find the [Upgrade Guide](https://rust-random.github.io/book/update.
3434
- Remove impl of `Distribution<Option<T>>` for `Standard` (#1526)
3535
- Remove `SmallRng::from_thread_rng` (#1532)
3636
- Remove first parameter (`rng`) of `ReseedingRng::new` (#1533)
37+
- Rename feature `getrandom` to `os_rng`
3738

3839
## [0.9.0-alpha.1] - 2024-03-18
3940
- Add the `Slice::num_choices` method to the Slice distribution (#1402)

Cargo.toml

+3-3
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ features = ["small_rng", "serde"]
2828

2929
[features]
3030
# Meta-features:
31-
default = ["std", "std_rng", "getrandom", "small_rng"]
31+
default = ["std", "std_rng", "os_rng", "small_rng"]
3232
nightly = [] # some additions requiring nightly Rust
3333
serde = ["dep:serde", "rand_core/serde"]
3434

@@ -39,8 +39,8 @@ std = ["rand_core/std", "rand_chacha?/std", "alloc"]
3939
# Option: "alloc" enables support for Vec and Box when not using "std"
4040
alloc = ["rand_core/alloc"]
4141

42-
# Option: use getrandom package for seeding
43-
getrandom = ["rand_core/getrandom"]
42+
# Option: enable OsRng
43+
os_rng = ["rand_core/os_rng"]
4444

4545
# Option (requires nightly Rust): experimental SIMD support
4646
simd_support = ["zerocopy/simd-nightly"]

README.md

+8-7
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ Rand is a set of crates supporting (pseudo-)random generators:
1212
- With fast implementations of both [strong](https://rust-random.github.io/book/guide-rngs.html#cryptographically-secure-pseudo-random-number-generators-csprngs) and
1313
[small](https://rust-random.github.io/book/guide-rngs.html#basic-pseudo-random-number-generators-prngs) generators: [`rand::rngs`](https://docs.rs/rand/latest/rand/rngs/index.html), and more RNGs: [`rand_chacha`](https://docs.rs/rand_chacha), [`rand_xoshiro`](https://docs.rs/rand_xoshiro/), [`rand_pcg`](https://docs.rs/rand_pcg/), [rngs repo](https://github.com/rust-random/rngs/)
1414
- [`rand::rng`](https://docs.rs/rand/latest/rand/fn.rng.html) is an asymptotically-fast, automatically-seeded and reasonably strong generator available on all `std` targets
15-
- Direct support for seeding generators from the [`getrandom` crate](https://crates.io/crates/getrandom)
15+
- Direct support for seeding generators from the [getrandom] crate
1616

1717
With broad support for random value generation and random processes:
1818

@@ -80,8 +80,7 @@ Rand is built with these features enabled by default:
8080

8181
- `std` enables functionality dependent on the `std` lib
8282
- `alloc` (implied by `std`) enables functionality requiring an allocator
83-
- `getrandom` (implied by `std`) is an optional dependency providing the code
84-
behind `rngs::OsRng`
83+
- `os_rng` (implied by `std`) enables `rngs::OsRng`, using the [getrandom] crate
8584
- `std_rng` enables inclusion of `StdRng`, `ThreadRng`
8685

8786
Optionally, the following dependencies can be enabled:
@@ -101,23 +100,23 @@ experimental `simd_support` feature.
101100

102101
Rand supports limited functionality in `no_std` mode (enabled via
103102
`default-features = false`). In this case, `OsRng` and `from_os_rng` are
104-
unavailable (unless `getrandom` is enabled), large parts of `seq` are
103+
unavailable (unless `os_rng` is enabled), large parts of `seq` are
105104
unavailable (unless `alloc` is enabled), and `ThreadRng` is unavailable.
106105

107106
## Portability and platform support
108107

109108
Many (but not all) algorithms are intended to have reproducible output. Read more in the book: [Portability](https://rust-random.github.io/book/portability.html).
110109

111-
The Rand library supports a variety of CPU architectures. Platform integration is outsourced to [getrandom](https://docs.rs/getrandom/latest/getrandom/).
110+
The Rand library supports a variety of CPU architectures. Platform integration is outsourced to [getrandom].
112111

113112
### WASM support
114113

115114
Seeding entropy from OS on WASM target `wasm32-unknown-unknown` is not
116115
*automatically* supported by `rand` or `getrandom`. If you are fine with
117-
seeding the generator manually, you can disable the `getrandom` feature
116+
seeding the generator manually, you can disable the `os_rng` feature
118117
and use the methods on the `SeedableRng` trait. To enable seeding from OS,
119118
either use a different target such as `wasm32-wasi` or add a direct
120-
dependency on `getrandom` with the `js` feature (if the target supports
119+
dependency on [getrandom] with the `js` feature (if the target supports
121120
JavaScript). See
122121
[getrandom#WebAssembly support](https://docs.rs/getrandom/latest/getrandom/#webassembly-support).
123122

@@ -128,3 +127,5 @@ Apache License (Version 2.0).
128127

129128
See [LICENSE-APACHE](LICENSE-APACHE) and [LICENSE-MIT](LICENSE-MIT), and
130129
[COPYRIGHT](COPYRIGHT) for details.
130+
131+
[getrandom]: https://crates.io/crates/getrandom

rand_chacha/CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
66

77
## [Unreleased]
88
- The `serde1` feature has been renamed `serde` (#1477)
9+
- Rename feature `getrandom` to `os_rng`
910

1011
## [0.9.0-alpha.1] - 2024-03-18
1112

rand_chacha/Cargo.toml

+2-2
Original file line numberDiff line numberDiff line change
@@ -27,10 +27,10 @@ serde = { version = "1.0", features = ["derive"], optional = true }
2727
[dev-dependencies]
2828
# Only to test serde
2929
serde_json = "1.0"
30-
rand_core = { path = "../rand_core", version = "=0.9.0-alpha.1", features = ["getrandom"] }
30+
rand_core = { path = "../rand_core", version = "=0.9.0-alpha.1", features = ["os_rng"] }
3131

3232
[features]
3333
default = ["std"]
34-
getrandom = ["rand_core/getrandom"]
34+
os_rng = ["rand_core/os_rng"]
3535
std = ["ppv-lite86/std", "rand_core/std"]
3636
serde = ["dep:serde"]

rand_chacha/README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ Links:
3636
`rand_chacha` is `no_std` compatible when disabling default features; the `std`
3737
feature can be explicitly required to re-enable `std` support. Using `std`
3838
allows detection of CPU features and thus better optimisation. Using `std`
39-
also enables `getrandom` functionality, such as `ChaCha20Rng::from_os_rng()`.
39+
also enables `os_rng` functionality, such as `ChaCha20Rng::from_os_rng()`.
4040

4141

4242
# License

rand_core/CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
77
## [Unreleased]
88
- Bump the MSRV to 1.63.0
99
- The `serde1` feature has been renamed `serde` (#1477)
10+
- Rename feature `getrandom` to `os_rng`
1011

1112
## [0.9.0-alpha.1] - 2024-03-18
1213

rand_core/Cargo.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ all-features = true
2727
[features]
2828
std = ["alloc", "getrandom?/std"]
2929
alloc = [] # enables Vec and Box support without std
30-
getrandom = ["dep:getrandom"]
30+
os_rng = ["dep:getrandom"]
3131
serde = ["dep:serde"] # enables serde for BlockRng wrapper
3232

3333
[dependencies]

rand_core/src/lib.rs

+5-7
Original file line numberDiff line numberDiff line change
@@ -45,13 +45,11 @@ use core::{fmt, ops::DerefMut};
4545
pub mod block;
4646
pub mod impls;
4747
pub mod le;
48-
#[cfg(feature = "getrandom")]
48+
#[cfg(feature = "os_rng")]
4949
mod os;
5050

51-
#[cfg(feature = "getrandom")]
52-
pub use getrandom;
53-
#[cfg(feature = "getrandom")]
54-
pub use os::OsRng;
51+
#[cfg(feature = "os_rng")]
52+
pub use os::{OsError, OsRng};
5553

5654
/// Implementation-level interface for RNGs
5755
///
@@ -495,7 +493,7 @@ pub trait SeedableRng: Sized {
495493
///
496494
/// [`getrandom`]: https://docs.rs/getrandom
497495
/// [`try_from_os_rng`]: SeedableRng::try_from_os_rng
498-
#[cfg(feature = "getrandom")]
496+
#[cfg(feature = "os_rng")]
499497
fn from_os_rng() -> Self {
500498
match Self::try_from_os_rng() {
501499
Ok(res) => res,
@@ -511,7 +509,7 @@ pub trait SeedableRng: Sized {
511509
/// `from_rng(&mut rand::rng()).unwrap()`.
512510
///
513511
/// [`getrandom`]: https://docs.rs/getrandom
514-
#[cfg(feature = "getrandom")]
512+
#[cfg(feature = "os_rng")]
515513
fn try_from_os_rng() -> Result<Self, getrandom::Error> {
516514
let mut seed = Self::Seed::default();
517515
getrandom::getrandom(seed.as_mut())?;

rand_core/src/os.rs

+48-5
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ use getrandom::getrandom;
1919
/// [getrandom] documentation for details.
2020
///
2121
/// This struct is available as `rand_core::OsRng` and as `rand::rngs::OsRng`.
22-
/// In both cases, this requires the crate feature `getrandom` or `std`
22+
/// In both cases, this requires the crate feature `os_rng` or `std`
2323
/// (enabled by default in `rand` but not in `rand_core`).
2424
///
2525
/// # Blocking and error handling
@@ -47,26 +47,69 @@ use getrandom::getrandom;
4747
#[derive(Clone, Copy, Debug, Default)]
4848
pub struct OsRng;
4949

50+
/// Error type of [`OsRng`]
51+
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
52+
pub struct OsError(getrandom::Error);
53+
54+
impl core::fmt::Display for OsError {
55+
#[inline]
56+
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
57+
self.0.fmt(f)
58+
}
59+
}
60+
61+
// NOTE: this can use core::error::Error from rustc 1.81.0
62+
#[cfg(feature = "std")]
63+
impl std::error::Error for OsError {
64+
#[inline]
65+
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
66+
std::error::Error::source(&self.0)
67+
}
68+
}
69+
70+
impl OsError {
71+
/// Extract the raw OS error code (if this error came from the OS)
72+
///
73+
/// This method is identical to [`std::io::Error::raw_os_error()`][1], except
74+
/// that it works in `no_std` contexts. If this method returns `None`, the
75+
/// error value can still be formatted via the `Display` implementation.
76+
///
77+
/// [1]: https://doc.rust-lang.org/std/io/struct.Error.html#method.raw_os_error
78+
#[inline]
79+
pub fn raw_os_error(self) -> Option<i32> {
80+
self.0.raw_os_error()
81+
}
82+
83+
/// Extract the bare error code.
84+
///
85+
/// This code can either come from the underlying OS, or be a custom error.
86+
/// Use [`OsError::raw_os_error()`] to disambiguate.
87+
#[inline]
88+
pub const fn code(self) -> core::num::NonZeroU32 {
89+
self.0.code()
90+
}
91+
}
92+
5093
impl TryRngCore for OsRng {
51-
type Error = getrandom::Error;
94+
type Error = OsError;
5295

5396
#[inline]
5497
fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
5598
let mut buf = [0u8; 4];
56-
getrandom(&mut buf)?;
99+
getrandom(&mut buf).map_err(OsError)?;
57100
Ok(u32::from_ne_bytes(buf))
58101
}
59102

60103
#[inline]
61104
fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
62105
let mut buf = [0u8; 8];
63-
getrandom(&mut buf)?;
106+
getrandom(&mut buf).map_err(OsError)?;
64107
Ok(u64::from_ne_bytes(buf))
65108
}
66109

67110
#[inline]
68111
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Self::Error> {
69-
getrandom(dest)?;
112+
getrandom(dest).map_err(OsError)?;
70113
Ok(())
71114
}
72115
}

rand_pcg/CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
66

77
## [Unreleased]
88
- The `serde1` feature has been renamed `serde` (#1477)
9+
- Rename feature `getrandom` to `os_rng`
910

1011
## [0.9.0-alpha.1] - 2024-03-18
1112

rand_pcg/Cargo.toml

+2-2
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ rustdoc-args = ["--generate-link-to-definition"]
2121

2222
[features]
2323
serde = ["dep:serde"]
24-
getrandom = ["rand_core/getrandom"]
24+
os_rng = ["rand_core/os_rng"]
2525

2626
[dependencies]
2727
rand_core = { path = "../rand_core", version = "=0.9.0-alpha.1" }
@@ -32,4 +32,4 @@ serde = { version = "1", features = ["derive"], optional = true }
3232
# deps yet, see: https://github.com/rust-lang/cargo/issues/1596
3333
# Versions prior to 1.1.4 had incorrect minimal dependencies.
3434
bincode = { version = "1.1.4" }
35-
rand_core = { path = "../rand_core", version = "=0.9.0-alpha.1", features = ["getrandom"] }
35+
rand_core = { path = "../rand_core", version = "=0.9.0-alpha.1", features = ["os_rng"] }

src/lib.rs

+11-11
Original file line numberDiff line numberDiff line change
@@ -103,13 +103,13 @@ pub mod rngs;
103103
pub mod seq;
104104

105105
// Public exports
106-
#[cfg(all(feature = "std", feature = "std_rng", feature = "getrandom"))]
106+
#[cfg(all(feature = "std", feature = "std_rng", feature = "os_rng"))]
107107
pub use crate::rngs::thread::rng;
108108

109109
/// Access the thread-local generator
110110
///
111111
/// Use [`rand::rng()`](rng()) instead.
112-
#[cfg(all(feature = "std", feature = "std_rng", feature = "getrandom"))]
112+
#[cfg(all(feature = "std", feature = "std_rng", feature = "os_rng"))]
113113
#[deprecated(since = "0.9.0", note = "renamed to `rng`")]
114114
#[inline]
115115
pub fn thread_rng() -> crate::rngs::ThreadRng {
@@ -118,7 +118,7 @@ pub fn thread_rng() -> crate::rngs::ThreadRng {
118118

119119
pub use rng::{Fill, Rng};
120120

121-
#[cfg(all(feature = "std", feature = "std_rng", feature = "getrandom"))]
121+
#[cfg(all(feature = "std", feature = "std_rng", feature = "os_rng"))]
122122
use crate::distr::{Distribution, StandardUniform};
123123

124124
/// Generate a random value using the thread-local random number generator.
@@ -159,7 +159,7 @@ use crate::distr::{Distribution, StandardUniform};
159159
///
160160
/// [`StandardUniform`]: distr::StandardUniform
161161
/// [`ThreadRng`]: rngs::ThreadRng
162-
#[cfg(all(feature = "std", feature = "std_rng", feature = "getrandom"))]
162+
#[cfg(all(feature = "std", feature = "std_rng", feature = "os_rng"))]
163163
#[inline]
164164
pub fn random<T>() -> T
165165
where
@@ -179,7 +179,7 @@ where
179179
/// let v: Vec<i32> = rand::random_iter().take(5).collect();
180180
/// println!("{v:?}");
181181
/// ```
182-
#[cfg(all(feature = "std", feature = "std_rng", feature = "getrandom"))]
182+
#[cfg(all(feature = "std", feature = "std_rng", feature = "os_rng"))]
183183
#[inline]
184184
pub fn random_iter<T>() -> distr::DistIter<StandardUniform, rngs::ThreadRng, T>
185185
where
@@ -204,7 +204,7 @@ where
204204
/// ```
205205
/// Note that the first example can also be achieved (without `collect`'ing
206206
/// to a `Vec`) using [`seq::IteratorRandom::choose`].
207-
#[cfg(all(feature = "std", feature = "std_rng", feature = "getrandom"))]
207+
#[cfg(all(feature = "std", feature = "std_rng", feature = "os_rng"))]
208208
#[inline]
209209
pub fn random_range<T, R>(range: R) -> T
210210
where
@@ -228,7 +228,7 @@ where
228228
/// # Panics
229229
///
230230
/// If `p < 0` or `p > 1`.
231-
#[cfg(all(feature = "std", feature = "std_rng", feature = "getrandom"))]
231+
#[cfg(all(feature = "std", feature = "std_rng", feature = "os_rng"))]
232232
#[inline]
233233
#[track_caller]
234234
pub fn random_bool(p: f64) -> bool {
@@ -260,7 +260,7 @@ pub fn random_bool(p: f64) -> bool {
260260
/// ```
261261
///
262262
/// [`Bernoulli`]: distr::Bernoulli
263-
#[cfg(all(feature = "std", feature = "std_rng", feature = "getrandom"))]
263+
#[cfg(all(feature = "std", feature = "std_rng", feature = "os_rng"))]
264264
#[inline]
265265
#[track_caller]
266266
pub fn random_ratio(numerator: u32, denominator: u32) -> bool {
@@ -282,7 +282,7 @@ pub fn random_ratio(numerator: u32, denominator: u32) -> bool {
282282
/// Note that you can instead use [`random()`] to generate an array of random
283283
/// data, though this is slower for small elements (smaller than the RNG word
284284
/// size).
285-
#[cfg(all(feature = "std", feature = "std_rng", feature = "getrandom"))]
285+
#[cfg(all(feature = "std", feature = "std_rng", feature = "os_rng"))]
286286
#[inline]
287287
#[track_caller]
288288
pub fn fill<T: Fill + ?Sized>(dest: &mut T) {
@@ -302,7 +302,7 @@ mod test {
302302
}
303303

304304
#[test]
305-
#[cfg(all(feature = "std", feature = "std_rng", feature = "getrandom"))]
305+
#[cfg(all(feature = "std", feature = "std_rng", feature = "os_rng"))]
306306
fn test_random() {
307307
let _n: u64 = random();
308308
let _f: f32 = random();
@@ -316,7 +316,7 @@ mod test {
316316
}
317317

318318
#[test]
319-
#[cfg(all(feature = "std", feature = "std_rng", feature = "getrandom"))]
319+
#[cfg(all(feature = "std", feature = "std_rng", feature = "os_rng"))]
320320
fn test_range() {
321321
let _n: usize = random_range(42..=43);
322322
let _f: f32 = random_range(42.0..43.0);

0 commit comments

Comments
 (0)