Vendor dependencies

This commit is contained in:
2026-08-01 16:11:49 +03:00
parent 7f139a0241
commit 6b5e7f0f8b
29706 changed files with 9575646 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
{"$comment":"This file only protects against accidental modifications. It is not a security mechanism and does not protect against malicious changes.","files":{".cargo_vcs_info.json":"dfb564e676e5d157f692ca8f656aaab4ae20a2ff7f632587dacfc4725d7d7645","CHANGELOG.md":"c8c7ba5f1e50799fc838dec4ba295b87193f55dc81fb0cf0dedfa826ea825444","COPYRIGHT":"92b81db30f7ab6d693e0af5661a40d273ca1947e891123ed823924192c10cbc7","Cargo.lock":"d813ec97b7a0d6442ecf16651aa19979f491b771b798195e0e39ff02eacd4597","Cargo.toml":"4ff4becbb9ef65154f4840262f8d0cffa97d97a265b994b9d53f53925bdd3578","Cargo.toml.orig":"ce111f6a71bc63e21518ea5ad8b39d7dfc8e46727b0c0a953a85d32faaf64fb1","LICENSE-APACHE":"6df43f6f4b5d4587f3d8d71e45532c688fd168afa5fe89d571cb32fa09c4ef51","LICENSE-MIT":"8b6e9feec03e7c9a5facb26855cecd31662bf989b636bcfe79521bdf8ac863f0","README.md":"5337aa07d8ff993a96479ea9af969e9d95feaca79ecdcdc479051883fd3befca","src/block.rs":"ec396874071b217e1e4636ab1f57f5b5167bcf89688bb64d67dda39230a6f927","src/lib.rs":"b4df43985896bf2f38e595f7574c4d7e0df1c562e40c6a92133d9eef1cc01908","src/seedable_rng.rs":"151b125f0e2e943bc2b44cf409e202642f43f78473b1a1657063f29a07560e57","src/unwrap_err.rs":"a47826be69411fdc6950a00230e9403a68ca223d8a779a660bff7f1a9b1531d5","src/utils.rs":"6a0c2d6f64ae8e27f3b71be1b1973353d3eccf24cd6e17bdde2b966282438d20","src/word.rs":"6673e8e79bafe39ee5ec07317d166ce6824b32e0dfc71a1033afdc672bac5e2e","tests/block.rs":"a25188a8d38d0a9b2326236dce57eff124af1c5917937cc7ea38c4e69630ab54","tests/mod.rs":"34a86c1e6d359581b25ec52df40abd122b45722de6f3136f9a0adec79c68d952","tests/utils.rs":"61b073e9d6b7b7f3ef3976796876149fa8ddcd18bea45efe6904597450adede2"},"package":"63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"}
+6
View File
@@ -0,0 +1,6 @@
{
"git": {
"sha1": "5cd7df496d0bff1d95534ac8b66a2610f5bf7808"
},
"path_in_vcs": ""
}
+315
View File
@@ -0,0 +1,315 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.10.1] - 2026-04-13
### Fixed
- Reference to the `rand` crate in `TryRng` docs ([#75])
[0.10.1]: https://github.com/rust-random/rand_core/compare/v0.10.0...v0.10.1
[#75]: https://github.com/rust-random/rand_core/pull/75
## [0.10.0] - 2026-02-01
This release makes a number of significant changes which we hope will be the
last significant breakage before 1.0. Code has moved from the [rust-random/rand]
repository to its own [rust-random/rand_core].
### User-facing API changes
#### Changed
- Edition changed to 2024 and MSRV bumped to 1.85 ([rand#1668])
- `RngCore` and `TryRngCore` are renamed to `Rng` and `TryRng` respectively ([#54])
- `Rng` is now an extension trait of `TryRng<Error = Infallible>` ([#45])
- `TryRng::Error` is bound on `core::error::Error` instead of `Debug + Display` ([#58])
- Relax `Sized` bound on impls of `SeedableRng` ([rand#1641])
#### Added
- `SeedableRng::{fork, try_fork}` methods ([#17])
- Re-export of `core::convert::Infallible` ([#56])
#### Removed
- `TryRng::read_adapter` method (replaced with `rand::RngReader`) ([rand#1669])
- `os_rng` crate feature ([rand#1674])
- `OsRng` and `OsError` structs ([rand#1674])
- `SeedableRng::from_os_rng` and `SeedableRng::try_from_os_rng` methods ([rand#1674])
- `getrandom` dependency ([rand#1674])
- `std` crate feature ([rand#1674])
- Optional `serde` dependency ([#28])
- `UnwrapMut` struct and `Rng::unwrap_mut` method ([#45])
- `Rng::unwrap_err` method in favor of explicit wrapping in `UnwrapErr` ([#53])
### API changes to PRNG implementation helpers
### Added
- `BlockRng::reconstruct` and `BlockRng::remaining_results` methods ([#36])
- `block::Generator::drop` method ([#35])
- `BlockRng::word_offset` method ([#44])
### Changed
- Replaced `le` helper functions with new `utils` helpers ([rand#1667], [#34], [#38], [#45])
- Rename `BlockRng::generate_and_set` method to `reset_and_skip` ([#44])
- Rename `block::BlockRngCore` trait to `block::Generator` ([#26])
- Rename `BlockRngCore::Results` associated type to `Output` and remove type bounds on it ([#26])
### Removed
- Implementation of `Rng` for `BlockRng`, making the latter more generic ([#34])
- `BlockRng64` struct ([#34])
- `BlockRng::reset` method ([#44])
- `BlockRng::index` method (replaced with `BlockRng::word_offset`) ([#44])
- `Generator::Item` associated type ([#26])
- `CryptoBlockRng` ([#69])
[0.10.0]: https://github.com/rust-random/rand_core/compare/v0.9.3...v0.10.0
[rand#1641]: https://github.com/rust-random/rand/pull/1641
[rand#1667]: https://github.com/rust-random/rand/pull/1667
[rand#1668]: https://github.com/rust-random/rand/pull/1668
[rand#1669]: https://github.com/rust-random/rand/pull/1669
[rand#1674]: https://github.com/rust-random/rand/pull/1674
[#17]: https://github.com/rust-random/rand_core/pull/17
[#26]: https://github.com/rust-random/rand_core/pull/28
[#28]: https://github.com/rust-random/rand_core/pull/28
[#34]: https://github.com/rust-random/rand_core/pull/34
[#35]: https://github.com/rust-random/rand_core/pull/35
[#36]: https://github.com/rust-random/rand_core/pull/36
[#38]: https://github.com/rust-random/rand_core/pull/38
[#44]: https://github.com/rust-random/rand_core/pull/44
[#45]: https://github.com/rust-random/rand_core/pull/45
[#53]: https://github.com/rust-random/rand_core/pull/53
[#54]: https://github.com/rust-random/rand_core/pull/54
[#56]: https://github.com/rust-random/rand_core/pull/56
[#58]: https://github.com/rust-random/rand_core/pull/58
[#69]: https://github.com/rust-random/rand_core/pull/69
[rust-random/rand]: https://github.com/rust-random/rand
[rust-random/rand_core]: https://github.com/rust-random/rand_core
## [0.9.3] - 2025-02-29
### Other
- Remove `zerocopy` dependency ([rand#1607])
- Deprecate `rand_core::impls::fill_via_u32_chunks`, `fill_via_u64_chunks` ([rand#1607])
[0.9.3]: https://github.com/rust-random/rand_core/compare/v0.9.2...v0.9.3
[rand#1607]: https://github.com/rust-random/rand/pull/1607
## [0.9.2] - 2025-02-22
### API changes
- Relax `Sized` bound on impls of `TryRngCore`, `TryCryptoRng` and `UnwrapMut` ([rand#1593])
- Add `UnwrapMut::re` to reborrow the inner rng with a tighter lifetime ([rand#1595])
[0.9.2]: https://github.com/rust-random/rand_core/compare/v0.9.1...v0.9.2
[rand#1593]: https://github.com/rust-random/rand/pull/1593
[rand#1595]: https://github.com/rust-random/rand/pull/1595
## [0.9.1] - 2025-02-16
### API changes
- Add `TryRngCore::unwrap_mut`, providing an impl of `RngCore` over `&mut rng` ([rand#1589])
[0.9.1]: https://github.com/rust-random/rand_core/compare/v0.9.0...v0.9.1
[rand#1589]: https://github.com/rust-random/rand/pull/1589
## [0.9.0] - 2025-01-27
### Dependencies and features
- Bump the MSRV to 1.63.0 ([rand#1536]); note that 1.60.0 may work for dependents when using `--ignore-rust-version`
- Update to `getrandom` v0.3.0 ([rand#1558])
- Use `zerocopy` to replace some `unsafe` code ([rand#1349], [rand#1393], [rand#1446], [rand#1502])
- Rename feature `serde1` to `serde` ([rand#1477])
- Rename feature `getrandom` to `os_rng` ([rand#1537])
### API changes
- Allow `rand_core::impls::fill_via_u*_chunks` to mutate source ([rand#1182])
- Add fn `RngCore::read_adapter` implementing `std::io::Read` ([rand#1267])
- Add trait `CryptoBlockRng: BlockRngCore`; make `trait CryptoRng: RngCore` replacing `CryptoRngCore` ([rand#1273])
- Add traits `TryRngCore`, `TryCryptoRng` ([rand#1424], [rand#1499])
- Rename `fn SeedableRng::from_rng` -> `try_from_rng` and add infallible variant `fn from_rng` ([rand#1424])
- Rename `fn SeedableRng::from_entropy` -> `from_os_rng` and add fallible variant `fn try_from_os_rng` ([rand#1424])
- Add bounds `Clone` and `AsRef` to associated type `SeedableRng::Seed` ([rand#1491])
[0.9.0]: https://github.com/rust-random/rand_core/compare/v0.6.4...v0.9.0
[rand#1182]: https://github.com/rust-random/rand/pull/1182
[rand#1267]: https://github.com/rust-random/rand/pull/1267
[rand#1273]: https://github.com/rust-random/rand/pull/1273
[rand#1349]: https://github.com/rust-random/rand/pull/1349
[rand#1393]: https://github.com/rust-random/rand/pull/1393
[rand#1424]: https://github.com/rust-random/rand/pull/1424
[rand#1446]: https://github.com/rust-random/rand/pull/1446
[rand#1477]: https://github.com/rust-random/rand/pull/1477
[rand#1491]: https://github.com/rust-random/rand/pull/1491
[rand#1499]: https://github.com/rust-random/rand/pull/1499
[rand#1502]: https://github.com/rust-random/rand/pull/1502
[rand#1536]: https://github.com/rust-random/rand/pull/1536
[rand#1537]: https://github.com/rust-random/rand/pull/1537
[rand#1558]: https://github.com/rust-random/rand/pull/1558
## [0.6.4] - 2022-09-15
- Fix unsoundness in `<BlockRng64 as RngCore>::next_u32` ([rand#1160])
- Reduce use of `unsafe` and improve gen_bytes performance ([rand#1180])
- Add `CryptoRngCore` trait ([rand#1187], [rand#1230])
[0.6.4]: https://github.com/rust-random/rand_core/compare/v0.6.3...v0.6.4
[rand#1160]: https://github.com/rust-random/rand/pull/1160
[rand#1180]: https://github.com/rust-random/rand/pull/1180
[rand#1187]: https://github.com/rust-random/rand/pull/1187
[rand#1230]: https://github.com/rust-random/rand/pull/1230
## [0.6.3] - 2021-06-15
### Changed
- Improved bound for `serde` impls on `BlockRng` ([rand#1130])
- Minor doc additions ([rand#1118])
[0.6.3]: https://github.com/rust-random/rand_core/compare/v0.6.2...v0.6.3
[rand#1118]: https://github.com/rust-random/rand/pull/1118
[rand#1130]: https://github.com/rust-random/rand/pull/1130
## [0.6.2] - 2021-02-12
### Fixed
- Fixed assertions in `le::read_u32_into` and `le::read_u64_into` which could
have allowed buffers not to be fully populated ([rand#1096])
[0.6.2]: https://github.com/rust-random/rand_core/compare/v0.6.1...v0.6.2
[rand#1096]: https://github.com/rust-random/rand/pull/1096
## [0.6.1] - 2021-01-03
### Fixed
- Avoid panic when using `RngCore::seed_from_u64` with a seed which is not a
multiple of four ([rand#1082])
### Other
- Enable all stable features in the playground ([rand#1081])
[0.6.1]: https://github.com/rust-random/rand_core/compare/v0.6.0...v0.6.1
[rand#1081]: https://github.com/rust-random/rand/pull/1081
[rand#1082]: https://github.com/rust-random/rand/pull/1082
## [0.6.0] - 2020-12-08
### Breaking changes
- Bump MSRV to 1.36, various code improvements ([rand#1011])
- Update to getrandom v0.2 ([rand#1041])
- Fix: `next_u32_via_fill` and `next_u64_via_fill` now use LE as documented ([rand#1061])
### Other
- Reduce usage of `unsafe` ([rand#962], [rand#963], [rand#1011])
- Annotate feature-gates in documentation ([rand#1019])
- Document available error codes ([rand#1061])
- Various documentation tweaks
- Fix some clippy warnings ([rand#1036])
- Apply rustfmt ([rand#926])
[0.6.0]: https://github.com/rust-random/rand_core/compare/v0.5.1...v0.6.0
[rand#926]: https://github.com/rust-random/rand/pull/926
[rand#962]: https://github.com/rust-random/rand/pull/962
[rand#963]: https://github.com/rust-random/rand/pull/963
[rand#1011]: https://github.com/rust-random/rand/pull/1011
[rand#1019]: https://github.com/rust-random/rand/pull/1019
[rand#1036]: https://github.com/rust-random/rand/pull/1036
[rand#1041]: https://github.com/rust-random/rand/pull/1041
[rand#1061]: https://github.com/rust-random/rand/pull/1061
## [0.5.1] - 2019-08-28
- `OsRng` added to `rand_core` ([rand#863])
- `Error::INTERNAL_START` and `Error::CUSTOM_START` constants ([rand#864])
- `Error::raw_os_error` method ([rand#864])
- `Debug` and `Display` formatting for `getrandom` error codes without `std` ([rand#864])
### Changed
- `alloc` feature in `no_std` is available since Rust 1.36 ([rand#856])
- Added `#[inline]` to `Error` conversion methods ([rand#864])
[0.5.1]: https://github.com/rust-random/rand_core/compare/v0.5.0...v0.5.1
[rand#863]: https://github.com/rust-random/rand/pull/863
[rand#864]: https://github.com/rust-random/rand/pull/864
[rand#856]: https://github.com/rust-random/rand/pull/856
[rand#864]: https://github.com/rust-random/rand/pull/864
## [0.5.0] - 2019-06-06
### Changed
- Enable testing with Miri and fix incorrect pointer usages ([rand#779], [rand#780], [rand#781], [rand#783], [rand#784])
- Rewrite `Error` type and adjust API ([rand#800])
- Adjust usage of `#[inline]` for `BlockRng` and `BlockRng64`
[0.5.0]: https://github.com/rust-random/rand_core/compare/v0.4.0...v0.5.0
[rand#779]: https://github.com/rust-random/rand/pull/779
[rand#780]: https://github.com/rust-random/rand/pull/780
[rand#781]: https://github.com/rust-random/rand/pull/781
[rand#783]: https://github.com/rust-random/rand/pull/783
[rand#784]: https://github.com/rust-random/rand/pull/784
[rand#800]: https://github.com/rust-random/rand/pull/800
## [0.4.0] - 2019-01-24
### Changed
- Disable the `std` feature by default ([rand#702])
[0.4.0]: https://github.com/rust-random/rand_core/compare/v0.3.0...v0.4.0
[rand#702]: https://github.com/rust-random/rand/pull/702
## [0.3.0] - 2018-09-24
### Added
- Add `SeedableRng::seed_from_u64` for convenient seeding. ([rand#537])
[0.3.0]: https://github.com/rust-random/rand_core/compare/v0.2.1...v0.3.0
[rand#537]: https://github.com/rust-random/rand/pull/537
## [0.2.1] - 2018-06-08
### Added
- References to a `CryptoRng` now also implement `CryptoRng`. ([rand#470])
[0.2.1]: https://github.com/rust-random/rand_core/compare/v0.2.0...v0.2.1
[rand#470]: https://github.com/rust-random/rand/pull/470
## [0.2.0] - 2018-05-21
### Changed
- Enable the `std` feature by default. ([rand#409])
- Remove `BlockRng{64}::inner` and `BlockRng::inner_mut`; instead making `core` public
- Change `BlockRngCore::Results` bound to also require `AsMut<[Self::Item]>`. ([rand#419])
### Added
- Add `BlockRng{64}::index` and `BlockRng{64}::generate_and_set`. ([rand#374], [rand#419])
- Implement `std::io::Read` for RngCore. ([rand#434])
[0.2.0]: https://github.com/rust-random/rand_core/compare/v0.1.0...v0.2.0
[rand#374]: https://github.com/rust-random/rand/pull/374
[rand#409]: https://github.com/rust-random/rand/pull/409
[rand#419]: https://github.com/rust-random/rand/pull/419
[rand#434]: https://github.com/rust-random/rand/pull/434
## [0.1.0] - 2018-04-17
(Split out of the Rand crate, changes here are relative to rand 0.4.2.)
### Added
- `RngCore` and `SeedableRng` are now part of `rand_core`. ([rand#288])
- Add modules to help implementing RNGs `impl` and `le`. ([rand#209], [rand#228])
- Add `Error` and `ErrorKind`. ([rand#225])
- Add `CryptoRng` marker trait. ([rand#273])
- Add `BlockRngCore` trait. ([rand#281])
- Add `BlockRng` and `BlockRng64` wrappers to help implementations. ([rand#281], [rand#325])
- Add `RngCore::try_fill_bytes`. ([rand#225])
### Changed
- Revise the `SeedableRng` trait. ([rand#233])
- Remove default implementations for `RngCore::next_u64` and `RngCore::fill_bytes`. ([rand#288])
[0.1.0]: https://github.com/rust-random/rand_core/compare/v0.0.0...v0.1.0
[rand#209]: https://github.com/rust-random/rand/pull/209
[rand#225]: https://github.com/rust-random/rand/pull/225
[rand#228]: https://github.com/rust-random/rand/pull/228
[rand#233]: https://github.com/rust-random/rand/pull/233
[rand#273]: https://github.com/rust-random/rand/pull/273
[rand#281]: https://github.com/rust-random/rand/pull/281
[rand#288]: https://github.com/rust-random/rand/pull/288
[rand#325]: https://github.com/rust-random/rand/pull/325
+9
View File
@@ -0,0 +1,9 @@
Copyrights in the Rand project are retained by their contributors. No
copyright assignment is required to contribute to the Rand project.
For full authorship information, see the version control history.
Except as otherwise noted (below and/or in individual files), Rand is
licensed under the Apache License, Version 2.0 <LICENSE-APACHE> or
<http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
<LICENSE-MIT> or <http://opensource.org/licenses/MIT>, at your option.
+7
View File
@@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "rand_core"
version = "0.10.1"
+64
View File
@@ -0,0 +1,64 @@
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2024"
rust-version = "1.85"
name = "rand_core"
version = "0.10.1"
authors = ["The Rand Project Developers"]
build = false
exclude = ["/.github"]
autolib = false
autobins = false
autoexamples = false
autotests = false
autobenches = false
description = "Core random number generation traits and tools for implementation."
homepage = "https://rust-random.github.io/book"
documentation = "https://docs.rs/rand_core"
readme = "README.md"
keywords = [
"random",
"rng",
]
categories = [
"algorithms",
"no-std",
]
license = "MIT OR Apache-2.0"
repository = "https://github.com/rust-random/rand_core"
[package.metadata.docs.rs]
rustdoc-args = ["--generate-link-to-definition"]
[lib]
name = "rand_core"
path = "src/lib.rs"
[[test]]
name = "block"
path = "tests/block.rs"
[[test]]
name = "mod"
path = "tests/mod.rs"
[[test]]
name = "utils"
path = "tests/utils.rs"
[lints.clippy]
undocumented_unsafe_blocks = "warn"
[lints.rust]
missing_debug_implementations = "warn"
missing_docs = "warn"
+27
View File
@@ -0,0 +1,27 @@
[package]
name = "rand_core"
version = "0.10.1"
authors = ["The Rand Project Developers"]
license = "MIT OR Apache-2.0"
readme = "README.md"
repository = "https://github.com/rust-random/rand_core"
documentation = "https://docs.rs/rand_core"
homepage = "https://rust-random.github.io/book"
description = "Core random number generation traits and tools for implementation."
keywords = ["random", "rng"]
categories = ["algorithms", "no-std"]
edition = "2024"
rust-version = "1.85"
exclude = ["/.github"]
[lints.rust]
missing_docs = "warn"
missing_debug_implementations = "warn"
[lints.clippy]
undocumented_unsafe_blocks = "warn"
[package.metadata.docs.rs]
# To build locally:
# cargo +nightly doc --open
rustdoc-args = ["--generate-link-to-definition"]
+187
View File
@@ -0,0 +1,187 @@
Apache License
Version 2.0, January 2004
https://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
+25
View File
@@ -0,0 +1,25 @@
Copyright (c) 2018-2026 The Rand Project Developers
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
+41
View File
@@ -0,0 +1,41 @@
# rand_core: core random number generation traits
<div class="badges">
[![crate][crate-badge]][crate-link]
[![Docs][docs-image]][docs-link]
[![Apache2/MIT licensed][license-image]][license-link]
[![Build Status][build-image]][build-link]
</div>
This crate provides a collection of traits used by implementations of Random Number Generation (RNG)
algorithms. Additionally, it includes helper utilities that assist with the implementation
of these traits.
Note that the traits focus solely on the core RNG functionality. Most users should prefer
the [`rand`] crate, which offers more advanced RNG capabilities built on these core traits,
such as sampling from restricted ranges, generating floating-point numbers, list permutations,
and more.
[`rand`]: https://docs.rs/rand
## License
The crate is licensed under either of:
* [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0)
* [MIT license](http://opensource.org/licenses/MIT)
at your option.
[//]: # (badges)
[crate-badge]: https://img.shields.io/crates/v/rand_core.svg
[crate-link]: https://crates.io/crates/rand_core
[docs-image]: https://docs.rs/rand_core/badge.svg
[docs-link]: https://docs.rs/rand_core
[license-image]: https://img.shields.io/badge/license-Apache2.0/MIT-blue.svg
[build-image]: https://github.com/rust-random/rand_core/actions/workflows/test.yml/badge.svg?branch=master
[license-link]: #license
[build-link]: https://github.com/rust-random/rand_core/actions/workflows/test.yml?query=branch:master
+308
View File
@@ -0,0 +1,308 @@
//! The [`Generator`] trait and [`BlockRng`]
//!
//! Trait [`Generator`] may be implemented by block-generators; that is PRNGs
//! whose output is a *block* of words, such as `[u32; 16]`.
//!
//! The struct [`BlockRng`] wraps such a [`Generator`] together with an output
//! buffer and implements several methods (e.g. [`BlockRng::next_word`]) to
//! assist in the implementation of [`TryRng`]. Note that (unlike in earlier
//! versions of `rand_core`) [`BlockRng`] itself does not implement [`TryRng`]
//! since in practice we found it was always beneficial to use a wrapper type
//! over [`BlockRng`].
//!
//! # Example
//!
//! ```
//! use core::convert::Infallible;
//! use rand_core::{Rng, SeedableRng, TryRng};
//! use rand_core::block::{Generator, BlockRng};
//!
//! struct MyRngCore {
//! // Generator state ...
//! # state: [u32; 8],
//! }
//!
//! impl Generator for MyRngCore {
//! type Output = [u32; 8];
//!
//! fn generate(&mut self, output: &mut Self::Output) {
//! // Write a new block to output...
//! # *output = self.state;
//! }
//! }
//!
//! // Our RNG is a wrapper over BlockRng
//! pub struct MyRng(BlockRng<MyRngCore>);
//!
//! impl SeedableRng for MyRng {
//! type Seed = [u8; 32];
//! fn from_seed(seed: Self::Seed) -> Self {
//! let core = MyRngCore {
//! // ...
//! # state: rand_core::utils::read_words(&seed),
//! };
//! MyRng(BlockRng::new(core))
//! }
//! }
//!
//! impl TryRng for MyRng {
//! type Error = Infallible;
//!
//! #[inline]
//! fn try_next_u32(&mut self) -> Result<u32, Infallible> {
//! Ok(self.0.next_word())
//! }
//!
//! #[inline]
//! fn try_next_u64(&mut self) -> Result<u64, Infallible> {
//! Ok(self.0.next_u64_from_u32())
//! }
//!
//! #[inline]
//! fn try_fill_bytes(&mut self, bytes: &mut [u8]) -> Result<(), Infallible> {
//! Ok(self.0.fill_bytes(bytes))
//! }
//! }
//!
//! // And if applicable: impl TryCryptoRng for MyRng {}
//!
//! let mut rng = MyRng::seed_from_u64(0);
//! println!("First value: {}", rng.next_u32());
//! # assert_eq!(rng.next_u32(), 1171109249);
//! ```
//!
//! [`TryRng`]: crate::TryRng
//! [`SeedableRng`]: crate::SeedableRng
use crate::utils::Word;
use core::fmt;
/// A random (block) generator
pub trait Generator {
/// The output type.
///
/// For use with [`rand_core::block`](crate::block) code this must be `[u32; _]` or `[u64; _]`.
type Output;
/// Generate a new block of `output`.
///
/// This must fill `output` with random data.
fn generate(&mut self, output: &mut Self::Output);
/// Destruct the output buffer
///
/// This method is called on [`Drop`] of the [`Self::Output`] buffer.
/// The default implementation does nothing.
#[inline]
fn drop(&mut self, output: &mut Self::Output) {
let _ = output;
}
}
/// RNG functionality for a block [`Generator`]
///
/// This type encompasses a [`Generator`] [`core`](Self::core) and a buffer.
/// It provides optimized implementations of methods required by an [`Rng`].
///
/// All values are consumed in-order of generation. No whole words (e.g. `u32`
/// or `u64`) are discarded, though where a word is partially used (e.g. for a
/// byte-fill whose length is not a multiple of the word size) the rest of the
/// word is discarded.
///
/// [`Rng`]: crate::Rng
#[derive(Clone)]
pub struct BlockRng<G: Generator> {
results: G::Output,
/// The *core* part of the RNG, implementing the `generate` function.
pub core: G,
}
// Custom Debug implementation that does not expose the contents of `results`.
impl<G> fmt::Debug for BlockRng<G>
where
G: Generator + fmt::Debug,
{
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.debug_struct("BlockRng")
.field("core", &self.core)
.finish_non_exhaustive()
}
}
impl<G: Generator> Drop for BlockRng<G> {
fn drop(&mut self) {
self.core.drop(&mut self.results);
}
}
impl<W: Word + Default, const N: usize, G: Generator<Output = [W; N]>> BlockRng<G> {
/// Create a new `BlockRng` from an existing RNG implementing
/// `Generator`. Results will be generated on first use.
#[inline]
pub fn new(core: G) -> BlockRng<G> {
let mut results = [W::default(); N];
results[0] = W::from_usize(N);
BlockRng { core, results }
}
/// Reconstruct from a core and a remaining-results buffer.
///
/// This may be used to deserialize using a `core` and the output of
/// [`Self::remaining_results`].
///
/// Returns `None` if `remaining_results` is too long.
pub fn reconstruct(core: G, remaining_results: &[W]) -> Option<Self> {
let mut results = [W::default(); N];
if remaining_results.len() < N {
let index = N - remaining_results.len();
results[index..].copy_from_slice(remaining_results);
results[0] = W::from_usize(index);
Some(BlockRng { results, core })
} else {
None
}
}
}
impl<W: Word, const N: usize, G: Generator<Output = [W; N]>> BlockRng<G> {
/// Get the index into the result buffer.
///
/// If this is equal to or larger than the size of the result buffer then
/// the buffer is "empty" and `generate()` must be called to produce new
/// results.
#[inline(always)]
fn index(&self) -> usize {
self.results[0].into_usize()
}
#[inline(always)]
fn set_index(&mut self, index: usize) {
debug_assert!(0 < index && index <= N);
self.results[0] = W::from_usize(index);
}
/// Re-generate buffer contents, skipping the first `n` words
///
/// Existing buffer contents are discarded. A new set of results is
/// generated (either immediately or when next required). The first `n`
/// words are skipped (this may be used to set a specific word position).
///
/// # Panics
///
/// This method will panic if `n >= N` where `N` is the buffer size (in
/// words).
#[inline]
pub fn reset_and_skip(&mut self, n: usize) {
if n == 0 {
self.set_index(N);
return;
}
assert!(n < N);
self.core.generate(&mut self.results);
self.set_index(n);
}
/// Get the number of words consumed since the start of the block
///
/// The result is in the range `0..N` where `N` is the buffer size (in
/// words).
#[inline]
pub fn word_offset(&self) -> usize {
let index = self.index();
if index >= N { 0 } else { index }
}
/// Access the unused part of the results buffer
///
/// The length of the returned slice is guaranteed to be less than the
/// length of `<Self as Generator>::Output` (i.e. less than `N` where
/// `Output = [W; N]`).
///
/// This is a low-level interface intended for serialization.
/// Results are not marked as consumed.
#[inline]
pub fn remaining_results(&self) -> &[W] {
let index = self.index();
&self.results[index..]
}
/// Generate the next word (e.g. `u32`)
#[inline]
pub fn next_word(&mut self) -> W {
let mut index = self.index();
if index >= N {
self.core.generate(&mut self.results);
index = 0;
}
let value = self.results[index];
self.set_index(index + 1);
value
}
}
impl<const N: usize, G: Generator<Output = [u32; N]>> BlockRng<G> {
/// Generate a `u64` from two `u32` words
#[inline]
pub fn next_u64_from_u32(&mut self) -> u64 {
let index = self.index();
let mut new_index;
let (mut lo, mut hi);
if index < N - 1 {
lo = self.results[index];
hi = self.results[index + 1];
new_index = index + 2;
} else {
lo = self.results[N - 1];
self.core.generate(&mut self.results);
hi = self.results[0];
new_index = 1;
if index >= N {
lo = hi;
hi = self.results[1];
new_index = 2;
}
}
self.set_index(new_index);
(u64::from(hi) << 32) | u64::from(lo)
}
}
impl<W: Word, const N: usize, G: Generator<Output = [W; N]>> BlockRng<G> {
/// Fill `dest`
#[inline]
pub fn fill_bytes(&mut self, dest: &mut [u8]) {
let mut read_len = 0;
let mut index = self.index();
while read_len < dest.len() {
if index >= N {
self.core.generate(&mut self.results);
index = 0;
}
let size = core::mem::size_of::<W>();
let mut chunks = dest[read_len..].chunks_exact_mut(size);
let mut src = self.results[index..].iter();
let zipped = chunks.by_ref().zip(src.by_ref());
let num_chunks = zipped.len();
zipped.for_each(|(chunk, src)| chunk.copy_from_slice(src.to_le_bytes().as_ref()));
index += num_chunks;
read_len += num_chunks * size;
if let Some(src) = src.next() {
// We have consumed all full chunks of dest, but not src.
let dest_rem = chunks.into_remainder();
let n = dest_rem.len();
if n > 0 {
dest_rem.copy_from_slice(&src.to_le_bytes().as_ref()[..n]);
index += 1;
debug_assert_eq!(read_len + n, dest.len());
}
break;
}
}
self.set_index(index);
}
}
+272
View File
@@ -0,0 +1,272 @@
// Hide badges from generated docs
//! <style> .badges { display: none; } </style>
#![no_std]
#![doc = include_str!("../README.md")]
#![doc(
html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png",
html_favicon_url = "https://www.rust-lang.org/favicon.ico"
)]
use core::ops::DerefMut;
pub use core::convert::Infallible;
pub mod block;
pub mod utils;
mod seedable_rng;
mod unwrap_err;
mod word;
pub use seedable_rng::SeedableRng;
pub use unwrap_err::UnwrapErr;
/// Trait for infallible random number generators
///
/// `Rng` is a sub-trait of [`TryRng`] for infallible generators.
///
/// # Requirements
///
/// See [`TryRng`#Requirements] which also apply here.
///
/// # Usage
///
/// The [`rand`] crate provides higher level functionality, for example
/// generation of floating-point values, uniform ranged sampling and shuffling
/// sequences. In particular, [`rand::RngExt`] is an extension trait over `Rng`
/// providing many of the methods one might expect to be able to use on an RNG.
///
/// # Implementing `Rng`
///
/// Implement [`TryRng`] with <code>type Error = [core::convert::Infallible][]</code>.
///
/// [`rand`]: https://docs.rs/rand/
/// [`rand::RngExt`]: https://docs.rs/rand/latest/rand/trait.RngExt.html
/// [`fill_bytes`]: Rng::fill_bytes
/// [`next_u32`]: Rng::next_u32
/// [`next_u64`]: Rng::next_u64
pub trait Rng: TryRng<Error = Infallible> {
/// Return the next random `u32`.
fn next_u32(&mut self) -> u32;
/// Return the next random `u64`.
fn next_u64(&mut self) -> u64;
/// Fill `dest` with random data.
///
/// This method should guarantee that `dest` is entirely filled
/// with new data, and may panic if this is impossible
/// (e.g. reading past the end of a file that is being used as the
/// source of randomness).
fn fill_bytes(&mut self, dst: &mut [u8]);
}
impl<R> Rng for R
where
R: TryRng<Error = Infallible> + ?Sized,
{
#[inline]
fn next_u32(&mut self) -> u32 {
match self.try_next_u32() {
Ok(x) => x,
}
}
#[inline]
fn next_u64(&mut self) -> u64 {
match self.try_next_u64() {
Ok(x) => x,
}
}
#[inline]
fn fill_bytes(&mut self, dst: &mut [u8]) {
match self.try_fill_bytes(dst) {
Ok(()) => (),
}
}
}
/// A marker trait for securely unpredictable infallible RNGs
///
/// This is a convenient trait alias for <code>[TryCryptoRng]<Error = [Infallible]></code>.
/// It is equivalent to the trait sum <code>[Rng] + [TryCryptoRng]</code>.
pub trait CryptoRng: Rng + TryCryptoRng<Error = Infallible> {}
impl<R> CryptoRng for R where R: TryCryptoRng<Error = Infallible> + ?Sized {}
/// Base trait for random number generators and random data sources
///
/// This trait provides a base interface designed to support efficient usage of
/// (`u32`, `u64`) word generators, block generators and random data sources.
/// There is no required relationship between the output of each method or any
/// requirement to use all generated random bits; for example an implementation
/// of [`try_fill_bytes`](Self::try_fill_bytes) may discard some generated bytes
/// to avoid storing a partially used word or block.
///
/// # Requirements
///
/// ### Quality and length
///
/// Implementions should produce bits uniformly: each output value should be
/// equally likely, without observable patterns in successive outputs or
/// between the output streams of multiple instances of an implementation using
/// different seeds or streams (where supported by the implementation).
///
/// Pathological implementations (e.g. constant or counting generators which
/// rarely change some bits) may cause issues in consumers of random data, for
/// example dead-locks in rejection samplers and obviously non-random output
/// (e.g. a counting generator may result in apparently-constant output from a
/// uniform-ranged distribution).
///
/// Cryptographically unpredictable output is not a requirement of this trait,
/// but is a requirement of [`TryCryptoRng`].
///
/// In practice, most implementations are pseudo-random number generators with a
/// finite *period* or *cycle length*, and (among non-cryptographic PRNGs)
/// statistical anomalies may appear long before a cycle occurs. An
/// implementation should ensure its period is sufficiently long that no
/// anomalies are likely to appear in usage and/or document its limitations.
///
/// For more on PRNG quality and period, see [The Rust Rand Book: Quality][0].
///
/// [0]: https://rust-random.github.io/book/guide-rngs.html#quality
///
/// ### Reproducibility
///
/// Algorithmic generators implementing [`SeedableRng`] should normally have
/// *portable, reproducible* output, i.e. fix Endianness when converting values
/// to avoid platform differences, and avoid making any changes which affect
/// output (except by communicating that the release has breaking changes).
/// See also [The Rust Rand Book: Reproducibility][1].
///
/// [1]: https://rust-random.github.io/book/crate-reprod.html
///
/// # Usage
///
/// Often, usage of the infallible trait [`Rng`] or its extension trait
/// [`rand::RngExt`] is preferred to direct usage of `TryRng`.
//
/// Many implementations of `TryRng` (those with <code>type Error = [Infallible][]</code>)
/// already implement [`Rng`]; in other cases [`UnwrapErr`] may be used to obtain
/// an implementation of [`Rng`].
///
/// # Implementing `TryRng`
///
/// Most algorithmic generators (i.e. pseudo-random number generators or PRNGs)
/// never fail; in this case type `Error` should be [`Infallible`]; in this case
/// trait `Rng` is implemented automatically. Cycling is not considered an
/// error.
///
/// Small PRNGs often yield either `u32` or `u64` natively.
/// Module [`crate::utils`] provides utilities to help implement other methods.
///
/// Byte sources may implement [`try_fill_bytes`](Self::try_fill_bytes)
/// natively.
/// Module [`crate::utils`] provides utilities to help implement other methods.
///
/// Block generators (which produce `[u32; N]` or `[u64; N]` for some fixed `N`)
/// should make use of the [`crate::block`] module.
///
/// With regards to other traits:
///
/// - **Do not** implement [`Default`] for seedable pseudorandom generators,
/// though the trait may be implemented for stateless interfaces and
/// auto-seeding generators.
/// - **Do** implement [`SeedableRng`] for seedable pseudorandom generators. See
/// [Reproducibility](#reproducibility) above.
/// - Implement [`Clone`] for non-cryptographic PRNGs but consider not doing so
/// for cryptographic generators to avoid the risk of key-stream duplication.
/// - **Do not** implement [`Copy`] since accidental copies may cause repeated
/// values.
/// - Implement [`Debug`](core::fmt::Debug), except that cryptographic PRNGs
/// should use a custom implementation which avoids leaking internal state (or
/// the subset of this derived from the key).
/// - [`Eq`] and [`PartialEq`] could be implemented, but are probably not useful.
///
/// [`rand::RngExt`]: https://docs.rs/rand/latest/rand/trait.RngExt.html
pub trait TryRng {
/// The type returned in the event of a RNG error.
///
/// Use type [`Infallible`] (re-exported by `rand_core`) for infallible implementations.
type Error: core::error::Error;
/// Return the next random `u32`.
fn try_next_u32(&mut self) -> Result<u32, Self::Error>;
/// Return the next random `u64`.
fn try_next_u64(&mut self) -> Result<u64, Self::Error>;
/// Fill `dst` entirely with random data.
fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Self::Error>;
}
impl<R: DerefMut> TryRng for R
where
R::Target: TryRng,
{
type Error = <R::Target as TryRng>::Error;
#[inline]
fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
self.deref_mut().try_next_u32()
}
#[inline]
fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
self.deref_mut().try_next_u64()
}
#[inline]
fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Self::Error> {
self.deref_mut().try_fill_bytes(dst)
}
}
/// A marker trait over [`TryRng`] for securely unpredictable RNGs
///
/// This marker trait indicates that the implementing generator is intended,
/// when correctly seeded and protected from side-channel attacks such as a
/// leaking of state, to be a cryptographically secure generator. This trait is
/// provided as a tool to aid review of cryptographic code, but does not by
/// itself guarantee suitability for cryptographic applications.
///
/// Formally, a CSPRNG (Cryptographically Secure Pseudo-Random Number Generator)
/// should satisfy an additional property over other generators: assuming that
/// the generator has been appropriately seeded and has unknown state, then
/// given the first *k* bits of an algorithm's output
/// sequence, it should not be possible using polynomial-time algorithms to
/// predict the next bit with probability significantly greater than 50%.
///
/// An optional property of CSPRNGs is backtracking resistance: if the CSPRNG's
/// state is revealed, it will not be computationally-feasible to reconstruct
/// prior output values. This property is not required by `CryptoRng`.
///
/// Implementors of `TryCryptoRng` should only implement [`Default`] if a
/// default-constructed instance is itself a secure generator, for example
/// [`getrandom::SysRng`] which is a stateless interface.
///
/// [`getrandom::SysRng`]: https://docs.rs/getrandom/latest/getrandom/struct.SysRng.html
pub trait TryCryptoRng: TryRng {}
impl<R: DerefMut> TryCryptoRng for R where R::Target: TryCryptoRng {}
/// DEPRECATED: stub trait to print a deprecation warning and aid discovering that [`Rng`] is the
/// replacement.
// TODO: remove prior to v1.x.
#[deprecated(since = "0.10.0", note = "use `Rng` instead")]
pub trait RngCore: Rng {}
#[allow(deprecated)]
impl<R: Rng> RngCore for R {}
/// DEPRECATED: stub trait to print a deprecation warning and aid discovering that [`TryRng`] is the
/// replacement.
// TODO: remove prior to v1.x.
#[deprecated(since = "0.10.0", note = "use `TryRng` instead")]
pub trait TryRngCore: TryRng {
/// Error type.
type Error: core::error::Error;
}
#[allow(deprecated)]
impl<R: TryRng> TryRngCore for R {
type Error = R::Error;
}
+206
View File
@@ -0,0 +1,206 @@
use crate::{Rng, TryRng};
/// A random number generator that can be explicitly seeded.
///
/// This trait encapsulates the low-level functionality common to all
/// pseudo-random number generators (PRNGs, or algorithmic generators).
///
/// A generator implementing `SeedableRng` will usually be deterministic, but
/// beware that portability and reproducibility of results **is not implied**.
/// Refer to documentation of the generator, noting that generators named after
/// a specific algorithm are usually tested for reproducibility against a
/// reference vector, while `SmallRng` and `StdRng` specifically opt out of
/// reproducibility guarantees.
pub trait SeedableRng: Sized {
/// Seed type, which is restricted to types mutably-dereferenceable as `u8`
/// arrays (we recommend `[u8; N]` for some `N`).
///
/// It is recommended to seed PRNGs with a seed of at least circa 100 bits,
/// which means an array of `[u8; 12]` or greater to avoid picking RNGs with
/// partially overlapping periods.
///
/// For cryptographic RNG's a seed of 256 bits is recommended, `[u8; 32]`.
///
///
/// # Implementing `SeedableRng` for RNGs with large seeds
///
/// Note that [`Default`] is not implemented for large arrays `[u8; N]` with
/// `N` > 32. To be able to implement the traits required by `SeedableRng`
/// for RNGs with such large seeds, the newtype pattern can be used:
///
/// ```
/// use rand_core::SeedableRng;
///
/// const N: usize = 64;
/// #[derive(Clone)]
/// pub struct MyRngSeed(pub [u8; N]);
/// # #[allow(dead_code)]
/// pub struct MyRng(MyRngSeed);
///
/// impl Default for MyRngSeed {
/// fn default() -> MyRngSeed {
/// MyRngSeed([0; N])
/// }
/// }
///
/// impl AsRef<[u8]> for MyRngSeed {
/// fn as_ref(&self) -> &[u8] {
/// &self.0
/// }
/// }
///
/// impl AsMut<[u8]> for MyRngSeed {
/// fn as_mut(&mut self) -> &mut [u8] {
/// &mut self.0
/// }
/// }
///
/// impl SeedableRng for MyRng {
/// type Seed = MyRngSeed;
///
/// fn from_seed(seed: MyRngSeed) -> MyRng {
/// MyRng(seed)
/// }
/// }
/// ```
type Seed: Clone + Default + AsRef<[u8]> + AsMut<[u8]>;
/// Create a new PRNG using the given seed.
///
/// PRNG implementations are allowed to assume that bits in the seed are
/// well distributed. That means usually that the number of one and zero
/// bits are roughly equal, and values like 0, 1 and (size - 1) are unlikely.
/// Note that many non-cryptographic PRNGs will show poor quality output
/// if this is not adhered to. If you wish to seed from simple numbers, use
/// `seed_from_u64` instead.
///
/// All PRNG implementations should be reproducible unless otherwise noted:
/// given a fixed `seed`, the same sequence of output should be produced
/// on all runs, library versions and architectures (e.g. check endianness).
/// Any "value-breaking" changes to the generator should require bumping at
/// least the minor version and documentation of the change.
///
/// It is not required that this function yield the same state as a
/// reference implementation of the PRNG given equivalent seed; if necessary
/// another constructor replicating behaviour from a reference
/// implementation can be added.
///
/// PRNG implementations should make sure `from_seed` never panics. In the
/// case that some special values (like an all zero seed) are not viable
/// seeds it is preferable to map these to alternative constant value(s),
/// for example `0xBAD5EEDu32` or `0x0DDB1A5E5BAD5EEDu64` ("odd biases? bad
/// seed"). This is assuming only a small number of values must be rejected.
fn from_seed(seed: Self::Seed) -> Self;
/// Create a new PRNG using a `u64` seed.
///
/// This is a convenience-wrapper around `from_seed` to allow construction
/// of any `SeedableRng` from a simple `u64` value. It is designed such that
/// low Hamming Weight numbers like 0 and 1 can be used and should still
/// result in good, independent seeds to the PRNG which is returned.
///
/// This **is not suitable for cryptography**, as should be clear given that
/// the input size is only 64 bits.
///
/// Implementations for PRNGs *may* provide their own implementations of
/// this function, but the default implementation should be good enough for
/// all purposes. *Changing* the implementation of this function should be
/// considered a value-breaking change.
fn seed_from_u64(mut state: u64) -> Self {
let mut seed = Self::Seed::default();
let mut iter = seed.as_mut().chunks_exact_mut(4);
for chunk in &mut iter {
chunk.copy_from_slice(&pcg32(&mut state));
}
let rem = iter.into_remainder();
if !rem.is_empty() {
rem.copy_from_slice(&pcg32(&mut state)[..rem.len()]);
}
Self::from_seed(seed)
}
/// Create a new PRNG seeded from an infallible `Rng`.
///
/// This may be useful when needing to rapidly seed many PRNGs from a master
/// PRNG, and to allow forking of PRNGs. It may be considered deterministic.
///
/// The master PRNG should be at least as high quality as the child PRNGs.
/// When seeding non-cryptographic child PRNGs, we recommend using a
/// different algorithm for the master PRNG (ideally a CSPRNG) to avoid
/// correlations between the child PRNGs. If this is not possible (e.g.
/// forking using small non-crypto PRNGs) ensure that your PRNG has a good
/// mixing function on the output or consider use of a hash function with
/// `from_seed`.
///
/// Note that seeding `XorShiftRng` from another `XorShiftRng` provides an
/// extreme example of what can go wrong: the new PRNG will be a clone
/// of the parent.
///
/// PRNG implementations are allowed to assume that a good RNG is provided
/// for seeding, and that it is cryptographically secure when appropriate.
/// As of `rand` 0.7 / `rand_core` 0.5, implementations overriding this
/// method should ensure the implementation satisfies reproducibility
/// (in prior versions this was not required).
///
/// [`rand`]: https://docs.rs/rand
fn from_rng<R: Rng + ?Sized>(rng: &mut R) -> Self {
let mut seed = Self::Seed::default();
rng.fill_bytes(seed.as_mut());
Self::from_seed(seed)
}
/// Create a new PRNG seeded from a potentially fallible `Rng`.
///
/// See [`from_rng`][SeedableRng::from_rng] docs for more information.
fn try_from_rng<R: TryRng + ?Sized>(rng: &mut R) -> Result<Self, R::Error> {
let mut seed = Self::Seed::default();
rng.try_fill_bytes(seed.as_mut())?;
Ok(Self::from_seed(seed))
}
/// Fork this PRNG
///
/// This creates a new PRNG from the current one by initializing a new one and
/// seeding it from the current one.
///
/// This is useful when initializing a PRNG for a thread
fn fork(&mut self) -> Self
where
Self: Rng,
{
Self::from_rng(self)
}
/// Fork this PRNG
///
/// This creates a new PRNG from the current one by initializing a new one and
/// seeding it from the current one.
///
/// This is useful when initializing a PRNG for a thread.
///
/// This is the failable equivalent to [`SeedableRng::fork`]
fn try_fork(&mut self) -> Result<Self, Self::Error>
where
Self: TryRng,
{
Self::try_from_rng(self)
}
}
/// PCG32 generator function
fn pcg32(state: &mut u64) -> [u8; 4] {
const MUL: u64 = 0x5851_F42D_4C95_7F2D;
const INC: u64 = 0xA176_54E4_6FBE_17F3;
// We advance the state first (to get away from the input value,
// in case it has low Hamming Weight).
*state = state.wrapping_mul(MUL).wrapping_add(INC);
let state = *state;
// Use PCG output function with to_le to generate x:
let xorshifted = (((state >> 18) ^ state) >> 27) as u32;
let rot = (state >> 59) as u32;
let x = xorshifted.rotate_right(rot);
x.to_le_bytes()
}
+70
View File
@@ -0,0 +1,70 @@
use crate::{Infallible, TryCryptoRng, TryRng};
/// Wrapper around [`TryRng`] implementation which implements [`Rng`][crate::Rng]
/// by panicking on potential errors.
///
/// # Examples
///
/// ```rust
/// # use rand_core::{UnwrapErr, TryRng, Rng};
/// fn with_try_rng<R: TryRng>(mut rng: R) {
/// // rng does not impl Rng:
/// let _ = rng.try_next_u32(); // okay
/// // let _ = rng.next_u32(); // error
///
/// // An adapter borrowing rng:
/// let _ = UnwrapErr(&mut rng).next_u32();
///
/// // An adapter moving rng:
/// let mut rng = UnwrapErr(rng);
/// let _ = rng.next_u32();
/// }
///
/// fn call_with_unsized_try_rng<R: TryRng + ?Sized>(rng: &mut R) {
/// // R is unsized, thus we must use &mut R:
/// let mut rng = UnwrapErr(rng);
/// let _ = rng.next_u32();
/// }
/// ```
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash)]
pub struct UnwrapErr<R: TryRng>(pub R);
impl<R: TryRng> TryRng for UnwrapErr<R> {
type Error = Infallible;
#[inline]
fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
self.0.try_next_u32().map_err(panic_msg)
}
#[inline]
fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
self.0.try_next_u64().map_err(panic_msg)
}
#[inline]
fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Self::Error> {
self.0.try_fill_bytes(dst).map_err(panic_msg)
}
}
fn panic_msg(err: impl core::error::Error) -> Infallible {
panic!("rand_core::UnwrapErr: failed to unwrap: {err}")
}
impl<R: TryCryptoRng> TryCryptoRng for UnwrapErr<R> {}
impl<'r, R: TryRng + ?Sized> UnwrapErr<&'r mut R> {
/// Reborrow with a new lifetime
///
/// Rust allows references like `&T` or `&mut T` to be "reborrowed" through
/// coercion: essentially, the pointer is copied under a new, shorter, lifetime.
/// Until rfcs#1403 lands, reborrows on user types require a method call.
#[inline(always)]
pub fn re<'b>(&'b mut self) -> UnwrapErr<&'b mut R>
where
'r: 'b,
{
UnwrapErr(self.0)
}
}
+151
View File
@@ -0,0 +1,151 @@
//! Utilties to aid trait implementations
//!
//! ## Portability
//!
//! For cross-platform reproducibility, Little-Endian order (least-significant
//! part first) has been chosen as the standard for inter-type conversion.
//! For example, [`next_u64_via_u32`] generates two `u32` values `x, y`,
//! then outputs `(y << 32) | x`.
//!
//! Byte-swapping (like the std `to_le` functions) is only needed to convert
//! to/from byte sequences, and since its purpose is reproducibility,
//! non-reproducible sources (e.g. `OsRng`) need not bother with it.
//!
//! ## Implementing [`TryRng`]
//!
//! Usually an implementation of [`TryRng`] will implement one of the three
//! methods over its internal source. The following helpers are provided for
//! the remaining implementations.
//!
//! **`fn try_next_u32`:**
//! - `self.next_u64() as u32`
//! - `(self.next_u64() >> 32) as u32`
//! - <code>[next_word_via_fill][](self)</code>
//!
//! **`fn try_next_u64`:**
//! - <code>[next_u64_via_u32][](self)</code>
//! - <code>[next_word_via_fill][](self)</code>
//!
//! **`fn try_fill_bytes`:**
//! - <code>[fill_bytes_via_next_word][](self, dest)</code>
//!
//! ## Implementing [`SeedableRng`]
//!
//! In many cases, [`SeedableRng::Seed`] must be converted to `[u32; _]` or
//! `[u64; _]`. [`read_words`] may be used for this.
//!
//! [`SeedableRng`]: crate::SeedableRng
//! [`SeedableRng::Seed`]: crate::SeedableRng::Seed
//!
//! ## Example
//!
//! We demonstrate a simple multiplicative congruential generator (MCG), taken
//! from M.E. O'Neill's blog post [Does It Beat the Minimal Standard?][0].
//!
//! [0]: https://www.pcg-random.org/posts/does-it-beat-the-minimal-standard.html
//!
//! ```
//! use core::convert::Infallible;
//! use rand_core::{Rng, SeedableRng, TryRng, utils};
//!
//! pub struct Mcg128(u128);
//!
//! impl SeedableRng for Mcg128 {
//! type Seed = [u8; 16];
//!
//! #[inline]
//! fn from_seed(seed: Self::Seed) -> Self {
//! // Always use little-endian byte order to ensure portable results
//! Self(u128::from_le_bytes(seed))
//! }
//! }
//!
//! impl TryRng for Mcg128 {
//! type Error = Infallible;
//!
//! #[inline]
//! fn try_next_u32(&mut self) -> Result<u32, Infallible> {
//! Ok((self.next_u64() >> 32) as u32)
//! }
//!
//! #[inline]
//! fn try_next_u64(&mut self) -> Result<u64, Infallible> {
//! self.0 = self.0.wrapping_mul(0x0fc94e3bf4e9ab32866458cd56f5e605);
//! Ok((self.0 >> 64) as u64)
//! }
//!
//! #[inline]
//! fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Infallible> {
//! utils::fill_bytes_via_next_word(dst, || self.try_next_u64())
//! }
//! }
//! #
//! # let mut rng = Mcg128::seed_from_u64(42);
//! # assert_eq!(rng.next_u32(), 3443086493);
//! # assert_eq!(rng.next_u64(), 3462997187007721903);
//! # let mut buf = [0u8; 5];
//! # rng.fill_bytes(&mut buf);
//! # assert_eq!(buf, [154, 23, 43, 68, 75]);
//! ```
use crate::TryRng;
pub use crate::word::Word;
/// Generate a `u64` using `next_u32`, little-endian order.
#[inline]
pub fn next_u64_via_u32<R: TryRng + ?Sized>(rng: &mut R) -> Result<u64, R::Error> {
// Use LE; we explicitly generate one value before the next.
let x = u64::from(rng.try_next_u32()?);
let y = u64::from(rng.try_next_u32()?);
Ok((y << 32) | x)
}
/// Fill `dst` with bytes using `next_word`
///
/// This may be used to implement `fill_bytes` over `next_u32` or
/// `next_u64`. Words are used in order of generation. The last word may be
/// partially discarded.
#[inline]
pub fn fill_bytes_via_next_word<E, W: Word>(
dst: &mut [u8],
mut next_word: impl FnMut() -> Result<W, E>,
) -> Result<(), E> {
let mut chunks = dst.chunks_exact_mut(size_of::<W>());
for chunk in &mut chunks {
let val = next_word()?;
chunk.copy_from_slice(val.to_le_bytes().as_ref());
}
let rem = chunks.into_remainder();
if !rem.is_empty() {
let val = next_word()?.to_le_bytes();
rem.copy_from_slice(&val.as_ref()[..rem.len()]);
}
Ok(())
}
/// Generate a `u32` or `u64` word using `fill_bytes`
pub fn next_word_via_fill<W: Word, R: TryRng>(rng: &mut R) -> Result<W, R::Error> {
let mut buf: W::Bytes = Default::default();
rng.try_fill_bytes(buf.as_mut())?;
Ok(W::from_le_bytes(buf))
}
/// Reads an array of words from a byte slice
///
/// Words are read from `src` in order, using LE conversion from bytes.
///
/// # Panics
///
/// Panics if `size_of_val(src) != size_of::<[W; N]>()`.
#[inline(always)]
pub fn read_words<W: Word, const N: usize>(src: &[u8]) -> [W; N] {
assert_eq!(size_of_val(src), size_of::<[W; N]>());
let mut dst = [W::from_usize(0); N];
let chunks = src.chunks_exact(size_of::<W>());
for (out, chunk) in dst.iter_mut().zip(chunks) {
let mut buf: W::Bytes = Default::default();
buf.as_mut().copy_from_slice(chunk);
*out = W::from_le_bytes(buf);
}
dst
}
+66
View File
@@ -0,0 +1,66 @@
//! The [`Word`] trait
/// A marker trait for supported "word" types.
///
/// This is implemented for: `u32`, `u64`.
pub trait Word: sealed::Sealed {}
impl Word for u32 {}
impl Word for u64 {}
mod sealed {
/// Sealed trait implemented for `u32` and `u64`.
pub trait Sealed: Default + Copy + TryFrom<usize> + Eq + core::hash::Hash {
type Bytes: Default + Sized + AsRef<[u8]> + AsMut<[u8]>;
fn from_le_bytes(bytes: Self::Bytes) -> Self;
fn to_le_bytes(self) -> Self::Bytes;
fn from_usize(val: usize) -> Self;
fn into_usize(self) -> usize;
}
impl Sealed for u32 {
type Bytes = [u8; 4];
#[inline(always)]
fn from_le_bytes(bytes: Self::Bytes) -> Self {
Self::from_le_bytes(bytes)
}
#[inline(always)]
fn to_le_bytes(self) -> Self::Bytes {
Self::to_le_bytes(self)
}
#[inline(always)]
fn from_usize(val: usize) -> Self {
val.try_into().unwrap()
}
#[inline(always)]
fn into_usize(self) -> usize {
self.try_into().unwrap()
}
}
impl Sealed for u64 {
type Bytes = [u8; 8];
#[inline(always)]
fn from_le_bytes(bytes: Self::Bytes) -> Self {
Self::from_le_bytes(bytes)
}
#[inline(always)]
fn to_le_bytes(self) -> Self::Bytes {
Self::to_le_bytes(self)
}
#[inline(always)]
fn from_usize(val: usize) -> Self {
val.try_into().unwrap()
}
#[inline(always)]
fn into_usize(self) -> usize {
self.try_into().unwrap()
}
}
}
+70
View File
@@ -0,0 +1,70 @@
//! Tests for the `block` module items
use rand_core::{
SeedableRng,
block::{BlockRng, Generator},
};
const RESULTS_LEN: usize = 16;
#[derive(Debug, Clone)]
struct DummyRng {
counter: u32,
}
impl Generator for DummyRng {
type Output = [u32; RESULTS_LEN];
fn generate(&mut self, output: &mut Self::Output) {
for item in output {
*item = self.counter;
self.counter = self.counter.wrapping_add(3511615421);
}
}
}
impl SeedableRng for DummyRng {
type Seed = [u8; 4];
fn from_seed(seed: Self::Seed) -> Self {
DummyRng {
counter: u32::from_le_bytes(seed),
}
}
}
#[test]
fn blockrng_next_u32_vs_next_u64() {
let mut rng1 = BlockRng::new(DummyRng::from_seed([1, 2, 3, 4]));
let mut rng2 = rng1.clone();
let mut rng3 = rng1.clone();
let mut a = [0; 16];
a[..4].copy_from_slice(&rng1.next_word().to_le_bytes());
a[4..12].copy_from_slice(&rng1.next_u64_from_u32().to_le_bytes());
a[12..].copy_from_slice(&rng1.next_word().to_le_bytes());
let mut b = [0; 16];
b[..4].copy_from_slice(&rng2.next_word().to_le_bytes());
b[4..8].copy_from_slice(&rng2.next_word().to_le_bytes());
b[8..].copy_from_slice(&rng2.next_u64_from_u32().to_le_bytes());
assert_eq!(a, b);
let mut c = [0; 16];
c[..8].copy_from_slice(&rng3.next_u64_from_u32().to_le_bytes());
c[8..12].copy_from_slice(&rng3.next_word().to_le_bytes());
c[12..].copy_from_slice(&rng3.next_word().to_le_bytes());
assert_eq!(a, c);
}
#[test]
fn blockrng_next_u64() {
let mut rng = BlockRng::new(DummyRng::from_seed([1, 2, 3, 4]));
let result_size = RESULTS_LEN;
for _i in 0..result_size / 2 - 1 {
rng.next_u64_from_u32();
}
rng.next_word();
let _ = rng.next_u64_from_u32();
assert_eq!(rng.word_offset(), 1);
}
+158
View File
@@ -0,0 +1,158 @@
//! Main `rand_core` tests
use rand_core::{CryptoRng, Infallible, Rng, SeedableRng, TryCryptoRng, TryRng, UnwrapErr, utils};
#[test]
fn test_seed_from_u64() {
struct SeedableNum(u64);
impl SeedableRng for SeedableNum {
type Seed = [u8; 8];
fn from_seed(seed: Self::Seed) -> Self {
let x: [u64; 1] = utils::read_words(&seed);
SeedableNum(x[0])
}
}
const N: usize = 8;
const SEEDS: [u64; N] = [0u64, 1, 2, 3, 4, 8, 16, -1i64 as u64];
let mut results = [0u64; N];
for (i, seed) in SEEDS.iter().enumerate() {
let SeedableNum(x) = SeedableNum::seed_from_u64(*seed);
results[i] = x;
}
for (i1, r1) in results.iter().enumerate() {
let weight = r1.count_ones();
// This is the binomial distribution B(64, 0.5), so chance of
// weight < 20 is binocdf(19, 64, 0.5) = 7.8e-4, and same for
// weight > 44.
assert!((20..=44).contains(&weight));
for (i2, r2) in results.iter().enumerate() {
if i1 == i2 {
continue;
}
let diff_weight = (r1 ^ r2).count_ones();
assert!(diff_weight >= 20);
}
}
// value-breakage test:
assert_eq!(results[0], 5029875928683246316);
}
// A stub RNG.
struct SomeRng;
impl TryRng for SomeRng {
type Error = Infallible;
fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
unimplemented!()
}
fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
unimplemented!()
}
fn try_fill_bytes(&mut self, _dst: &mut [u8]) -> Result<(), Self::Error> {
unimplemented!()
}
}
impl TryCryptoRng for SomeRng {}
#[test]
fn dyn_rng_to_tryrng() {
// Illustrates the need for `+ ?Sized` bound in `impl<R: Rng> TryRng for R`.
// A method in another crate taking a fallible RNG
fn third_party_api(_rng: &mut (impl TryRng + ?Sized)) -> bool {
true
}
// A method in our crate requiring an infallible RNG
fn my_api(rng: &mut dyn Rng) -> bool {
// We want to call the method above
third_party_api(rng)
}
assert!(my_api(&mut SomeRng));
}
#[test]
fn dyn_cryptorng_to_trycryptorng() {
// Illustrates the need for `+ ?Sized` bound in `impl<R: CryptoRng> TryCryptoRng for R`.
// A method in another crate taking a fallible RNG
fn third_party_api(_rng: &mut (impl TryCryptoRng + ?Sized)) -> bool {
true
}
// A method in our crate requiring an infallible RNG
fn my_api(rng: &mut dyn CryptoRng) -> bool {
// We want to call the method above
third_party_api(rng)
}
assert!(my_api(&mut SomeRng));
}
#[test]
fn dyn_unwrap_mut_tryrng() {
// Illustrates that UnwrapMut may be used over &mut R where R: TryRng
fn third_party_api(_rng: &mut impl Rng) -> bool {
true
}
fn my_api(rng: &mut (impl TryRng + ?Sized)) -> bool {
let mut infallible_rng = UnwrapErr(rng);
third_party_api(&mut infallible_rng)
}
assert!(my_api(&mut SomeRng));
}
#[test]
fn dyn_unwrap_mut_trycryptorng() {
// Crypto variant of the above
fn third_party_api(_rng: &mut impl CryptoRng) -> bool {
true
}
fn my_api(rng: &mut (impl TryCryptoRng + ?Sized)) -> bool {
let mut infallible_rng = UnwrapErr(rng);
third_party_api(&mut infallible_rng)
}
assert!(my_api(&mut SomeRng));
}
#[test]
fn reborrow_unwrap_mut() {
struct FourRng;
impl TryRng for FourRng {
type Error = Infallible;
fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
Ok(4)
}
fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
unimplemented!()
}
fn try_fill_bytes(&mut self, _: &mut [u8]) -> Result<(), Self::Error> {
unimplemented!()
}
}
let mut rng = FourRng;
let mut rng = UnwrapErr(&mut rng);
assert_eq!(rng.next_u32(), 4);
{
let mut rng2 = rng.re();
assert_eq!(rng2.next_u32(), 4);
// Make sure rng2 is dropped.
}
assert_eq!(rng.next_u32(), 4);
}
+70
View File
@@ -0,0 +1,70 @@
//! Tests for the `utils` module items
use rand_core::{Infallible, Rng, TryRng, utils};
struct DummyRng(u32);
impl TryRng for DummyRng {
type Error = Infallible;
fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
self.0 = self.0.wrapping_mul(3);
Ok(self.0)
}
fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
utils::next_u64_via_u32(self)
}
fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Self::Error> {
utils::fill_bytes_via_next_word(dst, || self.try_next_u32())
}
}
#[test]
fn test_next_u64_via_u32() {
let mut rng = DummyRng(0xF973_F2EC);
assert_eq!(rng.next_u64(), 0xC513_8A4C_EC5B_D8C4);
assert_eq!(rng.next_u64(), 0xEDAF_DCAC_4F3A_9EE4);
assert_eq!(rng.next_u64(), 0x5B2E_C20C_C90F_9604);
}
#[test]
fn test_fill_bytes_via_next_word() {
let mut rng = DummyRng(0xF973_F2EC);
let mut buf = [0u8; 8];
let dst = &mut buf[..3];
rng.fill_bytes(dst);
assert_eq!(dst, &[196, 216, 91]);
let dst = &mut buf[..5];
rng.fill_bytes(dst);
assert_eq!(dst, &[76, 138, 19, 197, 228]);
let dst = &mut buf[..];
rng.fill_bytes(dst);
assert_eq!(dst, &[172, 220, 175, 237, 4, 150, 15, 201]);
}
#[test]
fn test_read_words() {
use utils::read_words;
let bytes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
let buf: [u32; 4] = read_words(&bytes);
assert_eq!(buf[0], 0x0403_0201);
assert_eq!(buf[3], 0x100F_0E0D);
let buf: [u32; 3] = read_words(&bytes[1..13]); // unaligned
assert_eq!(buf[0], 0x0504_0302);
assert_eq!(buf[2], 0x0D0C_0B0A);
let buf: [u64; 2] = read_words(&bytes);
assert_eq!(buf[0], 0x0807_0605_0403_0201);
assert_eq!(buf[1], 0x100F_0E0D_0C0B_0A09);
let buf: [u64; 1] = read_words(&bytes[7..15]); // unaligned
assert_eq!(buf[0], 0x0F0E_0D0C_0B0A_0908);
}