diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-19 00:47:55 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-19 00:47:55 +0000 |
commit | 26a029d407be480d791972afb5975cf62c9360a6 (patch) | |
tree | f435a8308119effd964b339f76abb83a57c29483 /third_party/rust/rand_core | |
parent | Initial commit. (diff) | |
download | firefox-26a029d407be480d791972afb5975cf62c9360a6.tar.xz firefox-26a029d407be480d791972afb5975cf62c9360a6.zip |
Adding upstream version 124.0.1.upstream/124.0.1
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'third_party/rust/rand_core')
-rw-r--r-- | third_party/rust/rand_core/.cargo-checksum.json | 1 | ||||
-rw-r--r-- | third_party/rust/rand_core/CHANGELOG.md | 94 | ||||
-rw-r--r-- | third_party/rust/rand_core/COPYRIGHT | 12 | ||||
-rw-r--r-- | third_party/rust/rand_core/Cargo.toml | 63 | ||||
-rw-r--r-- | third_party/rust/rand_core/LICENSE-APACHE | 187 | ||||
-rw-r--r-- | third_party/rust/rand_core/LICENSE-MIT | 26 | ||||
-rw-r--r-- | third_party/rust/rand_core/README.md | 81 | ||||
-rw-r--r-- | third_party/rust/rand_core/src/block.rs | 539 | ||||
-rw-r--r-- | third_party/rust/rand_core/src/error.rs | 228 | ||||
-rw-r--r-- | third_party/rust/rand_core/src/impls.rs | 207 | ||||
-rw-r--r-- | third_party/rust/rand_core/src/le.rs | 56 | ||||
-rw-r--r-- | third_party/rust/rand_core/src/lib.rs | 531 | ||||
-rw-r--r-- | third_party/rust/rand_core/src/os.rs | 85 |
13 files changed, 2110 insertions, 0 deletions
diff --git a/third_party/rust/rand_core/.cargo-checksum.json b/third_party/rust/rand_core/.cargo-checksum.json new file mode 100644 index 0000000000..067463e3e6 --- /dev/null +++ b/third_party/rust/rand_core/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"a33a4318dd822ef757ec79c5e6027d50d9feee5c40f85d9aadf0f598eb7ef1b7","COPYRIGHT":"90eb64f0279b0d9432accfa6023ff803bc4965212383697eee27a0f426d5f8d5","Cargo.toml":"4a6762f8364d1a60f1436f4ba7d710de22465722340d2028101fcbd68e89396f","LICENSE-APACHE":"6df43f6f4b5d4587f3d8d71e45532c688fd168afa5fe89d571cb32fa09c4ef51","LICENSE-MIT":"209fbbe0ad52d9235e37badf9cadfe4dbdc87203179c0899e738b39ade42177b","README.md":"bb3bd3831adc9eaabbcea108ab7f02f5837e9d2f81e872ffd7d340ad466df4de","src/block.rs":"c0b606dc404a1f4b25eebf388e9c0da583ee571214cdcb0bac1b592450d6b4fa","src/error.rs":"c34af905a9ffbae65970f508a9e74480b56747128d05ad350475150898fc6452","src/impls.rs":"b861532f8a3500de6bd0e926b3677a15261df4b12d253e4a8fd6acc5e64f1d36","src/le.rs":"f302239d09cc8d915aa8d4fe46c32c8981900cb20d42b12eef9c34e2e820bc88","src/lib.rs":"df270489b859465fce144098d5e709b318d9f3b703a92f4a28e5f74334119107","src/os.rs":"47849479e19c43dd01259eb14be7b4daf8474d23567dc32a1547c10b108b7069"},"package":"ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"}
\ No newline at end of file diff --git a/third_party/rust/rand_core/CHANGELOG.md b/third_party/rust/rand_core/CHANGELOG.md new file mode 100644 index 0000000000..75fcbc667c --- /dev/null +++ b/third_party/rust/rand_core/CHANGELOG.md @@ -0,0 +1,94 @@ +# Changelog +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [0.6.4] - 2022-09-15 +- Fix unsoundness in `<BlockRng64 as RngCore>::next_u32` (#1160) +- Reduce use of `unsafe` and improve gen_bytes performance (#1180) +- Add `CryptoRngCore` trait (#1187, #1230) + +## [0.6.3] - 2021-06-15 +### Changed +- Improved bound for `serde` impls on `BlockRng` (#1130) +- Minor doc additions (#1118) + +## [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 (#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 (#1082) +### Other +- Enable all stable features in the playground (#1081) + +## [0.6.0] - 2020-12-08 +### Breaking changes +- Bump MSRV to 1.36, various code improvements (#1011) +- Update to getrandom v0.2 (#1041) +- Fix: `next_u32_via_fill` and `next_u64_via_fill` now use LE as documented (#1061) + +### Other +- Reduce usage of `unsafe` (#962, #963, #1011) +- Annotate feature-gates in documentation (#1019) +- Document available error codes (#1061) +- Various documentation tweaks +- Fix some clippy warnings (#1036) +- Apply rustfmt (#926) + +## [0.5.1] - 2019-08-28 +- `OsRng` added to `rand_core` (#863) +- `Error::INTERNAL_START` and `Error::CUSTOM_START` constants (#864) +- `Error::raw_os_error` method (#864) +- `Debug` and `Display` formatting for `getrandom` error codes without `std` (#864) +### Changed +- `alloc` feature in `no_std` is available since Rust 1.36 (#856) +- Added `#[inline]` to `Error` conversion methods (#864) + +## [0.5.0] - 2019-06-06 +### Changed +- Enable testing with Miri and fix incorrect pointer usages (#779, #780, #781, #783, #784) +- Rewrite `Error` type and adjust API (#800) +- Adjust usage of `#[inline]` for `BlockRng` and `BlockRng64` + +## [0.4.0] - 2019-01-24 +### Changed +- Disable the `std` feature by default (#702) + +## [0.3.0] - 2018-09-24 +### Added +- Add `SeedableRng::seed_from_u64` for convenient seeding. (#537) + +## [0.2.1] - 2018-06-08 +### Added +- References to a `CryptoRng` now also implement `CryptoRng`. (#470) + +## [0.2.0] - 2018-05-21 +### Changed +- Enable the `std` feature by default. (#409) +- Remove `BlockRng{64}::inner` and `BlockRng::inner_mut`; instead making `core` public +- Change `BlockRngCore::Results` bound to also require `AsMut<[Self::Item]>`. (#419) +### Added +- Add `BlockRng{64}::index` and `BlockRng{64}::generate_and_set`. (#374, #419) +- Implement `std::io::Read` for RngCore. (#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`. (#288) +- Add modules to help implementing RNGs `impl` and `le`. (#209, #228) +- Add `Error` and `ErrorKind`. (#225) +- Add `CryptoRng` marker trait. (#273) +- Add `BlockRngCore` trait. (#281) +- Add `BlockRng` and `BlockRng64` wrappers to help implementations. (#281, #325) +- Add `RngCore::try_fill_bytes`. (#225) +### Changed +- Revise the `SeedableRng` trait. (#233) +- Remove default implementations for `RngCore::next_u64` and `RngCore::fill_bytes`. (#288) + +## [0.0.1] - 2017-09-14 (yanked) +Experimental version as part of the rand crate refactor. diff --git a/third_party/rust/rand_core/COPYRIGHT b/third_party/rust/rand_core/COPYRIGHT new file mode 100644 index 0000000000..468d907caf --- /dev/null +++ b/third_party/rust/rand_core/COPYRIGHT @@ -0,0 +1,12 @@ +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. + +The Rand project includes code from the Rust project +published under these same licenses. diff --git a/third_party/rust/rand_core/Cargo.toml b/third_party/rust/rand_core/Cargo.toml new file mode 100644 index 0000000000..fd8c96d9bc --- /dev/null +++ b/third_party/rust/rand_core/Cargo.toml @@ -0,0 +1,63 @@ +# 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 = "2018" +name = "rand_core" +version = "0.6.4" +authors = [ + "The Rand Project Developers", + "The Rust Project Developers", +] +description = """ +Core random number generator 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" + +[package.metadata.docs.rs] +all-features = true +rustdoc-args = [ + "--cfg", + "doc_cfg", +] + +[package.metadata.playground] +all-features = true + +[dependencies.getrandom] +version = "0.2" +optional = true + +[dependencies.serde] +version = "1" +features = ["derive"] +optional = true + +[features] +alloc = [] +serde1 = ["serde"] +std = [ + "alloc", + "getrandom", + "getrandom/std", +] diff --git a/third_party/rust/rand_core/LICENSE-APACHE b/third_party/rust/rand_core/LICENSE-APACHE new file mode 100644 index 0000000000..455787c233 --- /dev/null +++ b/third_party/rust/rand_core/LICENSE-APACHE @@ -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. diff --git a/third_party/rust/rand_core/LICENSE-MIT b/third_party/rust/rand_core/LICENSE-MIT new file mode 100644 index 0000000000..d93b5baf34 --- /dev/null +++ b/third_party/rust/rand_core/LICENSE-MIT @@ -0,0 +1,26 @@ +Copyright 2018 Developers of the Rand project +Copyright (c) 2014 The Rust 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. diff --git a/third_party/rust/rand_core/README.md b/third_party/rust/rand_core/README.md new file mode 100644 index 0000000000..d32dd6853d --- /dev/null +++ b/third_party/rust/rand_core/README.md @@ -0,0 +1,81 @@ +# rand_core + +[![Test Status](https://github.com/rust-random/rand/workflows/Tests/badge.svg?event=push)](https://github.com/rust-random/rand/actions) +[![Latest version](https://img.shields.io/crates/v/rand_core.svg)](https://crates.io/crates/rand_core) +[![Book](https://img.shields.io/badge/book-master-yellow.svg)](https://rust-random.github.io/book/) +[![API](https://img.shields.io/badge/api-master-yellow.svg)](https://rust-random.github.io/rand/rand_core) +[![API](https://docs.rs/rand_core/badge.svg)](https://docs.rs/rand_core) +[![Minimum rustc version](https://img.shields.io/badge/rustc-1.36+-lightgray.svg)](https://github.com/rust-random/rand#rust-version-requirements) + +Core traits and error types of the [rand] library, plus tools for implementing +RNGs. + +This crate is intended for use when implementing the core trait, `RngCore`; it +defines the core traits to be implemented as well as several small functions to +aid in their implementation and types required for error handling. + +The main [rand] crate re-exports most items defined in this crate, along with +tools to convert the integer samples generated by `RngCore` to many different +applications (including sampling from restricted ranges, conversion to floating +point, list permutations and secure initialisation of RNGs). Most users should +prefer to use the main [rand] crate. + +Links: + +- [API documentation (master)](https://rust-random.github.io/rand/rand_core) +- [API documentation (docs.rs)](https://docs.rs/rand_core) +- [Changelog](https://github.com/rust-random/rand/blob/master/rand_core/CHANGELOG.md) + +[rand]: https://crates.io/crates/rand + + +## Functionality + +The `rand_core` crate provides: + +- base random number generator traits +- error-reporting types +- functionality to aid implementation of RNGs + +The traits and error types are also available via `rand`. + +## Versions + +The current version is: +``` +rand_core = "0.6.0" +``` + +Rand libs have inter-dependencies and make use of the +[semver trick](https://github.com/dtolnay/semver-trick/) in order to make traits +compatible across crate versions. (This is especially important for `RngCore` +and `SeedableRng`.) A few crate releases are thus compatibility shims, +depending on the *next* lib version (e.g. `rand_core` versions `0.2.2` and +`0.3.1`). This means, for example, that `rand_core_0_4_0::SeedableRng` and +`rand_core_0_3_0::SeedableRng` are distinct, incompatible traits, which can +cause build errors. Usually, running `cargo update` is enough to fix any issues. + +## Crate Features + +`rand_core` supports `no_std` and `alloc`-only configurations, as well as full +`std` functionality. The differences between `no_std` and full `std` are small, +comprising `RngCore` support for `Box<R>` types where `R: RngCore`, +`std::io::Read` support for types supporting `RngCore`, and +extensions to the `Error` type's functionality. + +The `std` feature is *not enabled by default*. This is primarily to avoid build +problems where one crate implicitly requires `rand_core` with `std` support and +another crate requires `rand` *without* `std` support. However, the `rand` crate +continues to enable `std` support by default, both for itself and `rand_core`. + +The `serde1` feature can be used to derive `Serialize` and `Deserialize` for RNG +implementations that use the `BlockRng` or `BlockRng64` wrappers. + + +# License + +`rand_core` is distributed under the terms of both the MIT license and the +Apache License (Version 2.0). + +See [LICENSE-APACHE](LICENSE-APACHE) and [LICENSE-MIT](LICENSE-MIT), and +[COPYRIGHT](COPYRIGHT) for details. diff --git a/third_party/rust/rand_core/src/block.rs b/third_party/rust/rand_core/src/block.rs new file mode 100644 index 0000000000..d311b68cfe --- /dev/null +++ b/third_party/rust/rand_core/src/block.rs @@ -0,0 +1,539 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! The `BlockRngCore` trait and implementation helpers +//! +//! The [`BlockRngCore`] trait exists to assist in the implementation of RNGs +//! which generate a block of data in a cache instead of returning generated +//! values directly. +//! +//! Usage of this trait is optional, but provides two advantages: +//! implementations only need to concern themselves with generation of the +//! block, not the various [`RngCore`] methods (especially [`fill_bytes`], where +//! the optimal implementations are not trivial), and this allows +//! `ReseedingRng` (see [`rand`](https://docs.rs/rand) crate) perform periodic +//! reseeding with very low overhead. +//! +//! # Example +//! +//! ```no_run +//! use rand_core::{RngCore, SeedableRng}; +//! use rand_core::block::{BlockRngCore, BlockRng}; +//! +//! struct MyRngCore; +//! +//! impl BlockRngCore for MyRngCore { +//! type Item = u32; +//! type Results = [u32; 16]; +//! +//! fn generate(&mut self, results: &mut Self::Results) { +//! unimplemented!() +//! } +//! } +//! +//! impl SeedableRng for MyRngCore { +//! type Seed = [u8; 32]; +//! fn from_seed(seed: Self::Seed) -> Self { +//! unimplemented!() +//! } +//! } +//! +//! // optionally, also implement CryptoRng for MyRngCore +//! +//! // Final RNG. +//! let mut rng = BlockRng::<MyRngCore>::seed_from_u64(0); +//! println!("First value: {}", rng.next_u32()); +//! ``` +//! +//! [`BlockRngCore`]: crate::block::BlockRngCore +//! [`fill_bytes`]: RngCore::fill_bytes + +use crate::impls::{fill_via_u32_chunks, fill_via_u64_chunks}; +use crate::{CryptoRng, Error, RngCore, SeedableRng}; +use core::convert::AsRef; +use core::fmt; +#[cfg(feature = "serde1")] +use serde::{Deserialize, Serialize}; + +/// A trait for RNGs which do not generate random numbers individually, but in +/// blocks (typically `[u32; N]`). This technique is commonly used by +/// cryptographic RNGs to improve performance. +/// +/// See the [module][crate::block] documentation for details. +pub trait BlockRngCore { + /// Results element type, e.g. `u32`. + type Item; + + /// Results type. This is the 'block' an RNG implementing `BlockRngCore` + /// generates, which will usually be an array like `[u32; 16]`. + type Results: AsRef<[Self::Item]> + AsMut<[Self::Item]> + Default; + + /// Generate a new block of results. + fn generate(&mut self, results: &mut Self::Results); +} + +/// A wrapper type implementing [`RngCore`] for some type implementing +/// [`BlockRngCore`] with `u32` array buffer; i.e. this can be used to implement +/// a full RNG from just a `generate` function. +/// +/// The `core` field may be accessed directly but the results buffer may not. +/// PRNG implementations can simply use a type alias +/// (`pub type MyRng = BlockRng<MyRngCore>;`) but might prefer to use a +/// wrapper type (`pub struct MyRng(BlockRng<MyRngCore>);`); the latter must +/// re-implement `RngCore` but hides the implementation details and allows +/// extra functionality to be defined on the RNG +/// (e.g. `impl MyRng { fn set_stream(...){...} }`). +/// +/// `BlockRng` has heavily optimized implementations of the [`RngCore`] methods +/// reading values from the results buffer, as well as +/// calling [`BlockRngCore::generate`] directly on the output array when +/// [`fill_bytes`] / [`try_fill_bytes`] is called on a large array. These methods +/// also handle the bookkeeping of when to generate a new batch of values. +/// +/// No whole generated `u32` values are thrown away and all values are consumed +/// in-order. [`next_u32`] simply takes the next available `u32` value. +/// [`next_u64`] is implemented by combining two `u32` values, least +/// significant first. [`fill_bytes`] and [`try_fill_bytes`] consume a whole +/// number of `u32` values, converting each `u32` to a byte slice in +/// little-endian order. If the requested byte length is not a multiple of 4, +/// some bytes will be discarded. +/// +/// See also [`BlockRng64`] which uses `u64` array buffers. Currently there is +/// no direct support for other buffer types. +/// +/// For easy initialization `BlockRng` also implements [`SeedableRng`]. +/// +/// [`next_u32`]: RngCore::next_u32 +/// [`next_u64`]: RngCore::next_u64 +/// [`fill_bytes`]: RngCore::fill_bytes +/// [`try_fill_bytes`]: RngCore::try_fill_bytes +#[derive(Clone)] +#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))] +#[cfg_attr( + feature = "serde1", + serde( + bound = "for<'x> R: Serialize + Deserialize<'x> + Sized, for<'x> R::Results: Serialize + Deserialize<'x>" + ) +)] +pub struct BlockRng<R: BlockRngCore + ?Sized> { + results: R::Results, + index: usize, + /// The *core* part of the RNG, implementing the `generate` function. + pub core: R, +} + +// Custom Debug implementation that does not expose the contents of `results`. +impl<R: BlockRngCore + fmt::Debug> fmt::Debug for BlockRng<R> { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.debug_struct("BlockRng") + .field("core", &self.core) + .field("result_len", &self.results.as_ref().len()) + .field("index", &self.index) + .finish() + } +} + +impl<R: BlockRngCore> BlockRng<R> { + /// Create a new `BlockRng` from an existing RNG implementing + /// `BlockRngCore`. Results will be generated on first use. + #[inline] + pub fn new(core: R) -> BlockRng<R> { + let results_empty = R::Results::default(); + BlockRng { + core, + index: results_empty.as_ref().len(), + results: results_empty, + } + } + + /// 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)] + pub fn index(&self) -> usize { + self.index + } + + /// Reset the number of available results. + /// This will force a new set of results to be generated on next use. + #[inline] + pub fn reset(&mut self) { + self.index = self.results.as_ref().len(); + } + + /// Generate a new set of results immediately, setting the index to the + /// given value. + #[inline] + pub fn generate_and_set(&mut self, index: usize) { + assert!(index < self.results.as_ref().len()); + self.core.generate(&mut self.results); + self.index = index; + } +} + +impl<R: BlockRngCore<Item = u32>> RngCore for BlockRng<R> +where + <R as BlockRngCore>::Results: AsRef<[u32]> + AsMut<[u32]>, +{ + #[inline] + fn next_u32(&mut self) -> u32 { + if self.index >= self.results.as_ref().len() { + self.generate_and_set(0); + } + + let value = self.results.as_ref()[self.index]; + self.index += 1; + value + } + + #[inline] + fn next_u64(&mut self) -> u64 { + let read_u64 = |results: &[u32], index| { + let data = &results[index..=index + 1]; + u64::from(data[1]) << 32 | u64::from(data[0]) + }; + + let len = self.results.as_ref().len(); + + let index = self.index; + if index < len - 1 { + self.index += 2; + // Read an u64 from the current index + read_u64(self.results.as_ref(), index) + } else if index >= len { + self.generate_and_set(2); + read_u64(self.results.as_ref(), 0) + } else { + let x = u64::from(self.results.as_ref()[len - 1]); + self.generate_and_set(1); + let y = u64::from(self.results.as_ref()[0]); + (y << 32) | x + } + } + + #[inline] + fn fill_bytes(&mut self, dest: &mut [u8]) { + let mut read_len = 0; + while read_len < dest.len() { + if self.index >= self.results.as_ref().len() { + self.generate_and_set(0); + } + let (consumed_u32, filled_u8) = + fill_via_u32_chunks(&self.results.as_ref()[self.index..], &mut dest[read_len..]); + + self.index += consumed_u32; + read_len += filled_u8; + } + } + + #[inline(always)] + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { + self.fill_bytes(dest); + Ok(()) + } +} + +impl<R: BlockRngCore + SeedableRng> SeedableRng for BlockRng<R> { + type Seed = R::Seed; + + #[inline(always)] + fn from_seed(seed: Self::Seed) -> Self { + Self::new(R::from_seed(seed)) + } + + #[inline(always)] + fn seed_from_u64(seed: u64) -> Self { + Self::new(R::seed_from_u64(seed)) + } + + #[inline(always)] + fn from_rng<S: RngCore>(rng: S) -> Result<Self, Error> { + Ok(Self::new(R::from_rng(rng)?)) + } +} + +/// A wrapper type implementing [`RngCore`] for some type implementing +/// [`BlockRngCore`] with `u64` array buffer; i.e. this can be used to implement +/// a full RNG from just a `generate` function. +/// +/// This is similar to [`BlockRng`], but specialized for algorithms that operate +/// on `u64` values. +/// +/// No whole generated `u64` values are thrown away and all values are consumed +/// in-order. [`next_u64`] simply takes the next available `u64` value. +/// [`next_u32`] is however a bit special: half of a `u64` is consumed, leaving +/// the other half in the buffer. If the next function called is [`next_u32`] +/// then the other half is then consumed, however both [`next_u64`] and +/// [`fill_bytes`] discard the rest of any half-consumed `u64`s when called. +/// +/// [`fill_bytes`] and [`try_fill_bytes`] consume a whole number of `u64` +/// values. If the requested length is not a multiple of 8, some bytes will be +/// discarded. +/// +/// [`next_u32`]: RngCore::next_u32 +/// [`next_u64`]: RngCore::next_u64 +/// [`fill_bytes`]: RngCore::fill_bytes +/// [`try_fill_bytes`]: RngCore::try_fill_bytes +#[derive(Clone)] +#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))] +pub struct BlockRng64<R: BlockRngCore + ?Sized> { + results: R::Results, + index: usize, + half_used: bool, // true if only half of the previous result is used + /// The *core* part of the RNG, implementing the `generate` function. + pub core: R, +} + +// Custom Debug implementation that does not expose the contents of `results`. +impl<R: BlockRngCore + fmt::Debug> fmt::Debug for BlockRng64<R> { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.debug_struct("BlockRng64") + .field("core", &self.core) + .field("result_len", &self.results.as_ref().len()) + .field("index", &self.index) + .field("half_used", &self.half_used) + .finish() + } +} + +impl<R: BlockRngCore> BlockRng64<R> { + /// Create a new `BlockRng` from an existing RNG implementing + /// `BlockRngCore`. Results will be generated on first use. + #[inline] + pub fn new(core: R) -> BlockRng64<R> { + let results_empty = R::Results::default(); + BlockRng64 { + core, + index: results_empty.as_ref().len(), + half_used: false, + results: results_empty, + } + } + + /// 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)] + pub fn index(&self) -> usize { + self.index + } + + /// Reset the number of available results. + /// This will force a new set of results to be generated on next use. + #[inline] + pub fn reset(&mut self) { + self.index = self.results.as_ref().len(); + self.half_used = false; + } + + /// Generate a new set of results immediately, setting the index to the + /// given value. + #[inline] + pub fn generate_and_set(&mut self, index: usize) { + assert!(index < self.results.as_ref().len()); + self.core.generate(&mut self.results); + self.index = index; + self.half_used = false; + } +} + +impl<R: BlockRngCore<Item = u64>> RngCore for BlockRng64<R> +where + <R as BlockRngCore>::Results: AsRef<[u64]> + AsMut<[u64]>, +{ + #[inline] + fn next_u32(&mut self) -> u32 { + let mut index = self.index - self.half_used as usize; + if index >= self.results.as_ref().len() { + self.core.generate(&mut self.results); + self.index = 0; + index = 0; + // `self.half_used` is by definition `false` + self.half_used = false; + } + + let shift = 32 * (self.half_used as usize); + + self.half_used = !self.half_used; + self.index += self.half_used as usize; + + (self.results.as_ref()[index] >> shift) as u32 + } + + #[inline] + fn next_u64(&mut self) -> u64 { + if self.index >= self.results.as_ref().len() { + self.core.generate(&mut self.results); + self.index = 0; + } + + let value = self.results.as_ref()[self.index]; + self.index += 1; + self.half_used = false; + value + } + + #[inline] + fn fill_bytes(&mut self, dest: &mut [u8]) { + let mut read_len = 0; + self.half_used = false; + while read_len < dest.len() { + if self.index as usize >= self.results.as_ref().len() { + self.core.generate(&mut self.results); + self.index = 0; + } + + let (consumed_u64, filled_u8) = fill_via_u64_chunks( + &self.results.as_ref()[self.index as usize..], + &mut dest[read_len..], + ); + + self.index += consumed_u64; + read_len += filled_u8; + } + } + + #[inline(always)] + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { + self.fill_bytes(dest); + Ok(()) + } +} + +impl<R: BlockRngCore + SeedableRng> SeedableRng for BlockRng64<R> { + type Seed = R::Seed; + + #[inline(always)] + fn from_seed(seed: Self::Seed) -> Self { + Self::new(R::from_seed(seed)) + } + + #[inline(always)] + fn seed_from_u64(seed: u64) -> Self { + Self::new(R::seed_from_u64(seed)) + } + + #[inline(always)] + fn from_rng<S: RngCore>(rng: S) -> Result<Self, Error> { + Ok(Self::new(R::from_rng(rng)?)) + } +} + +impl<R: BlockRngCore + CryptoRng> CryptoRng for BlockRng<R> {} + +#[cfg(test)] +mod test { + use crate::{SeedableRng, RngCore}; + use crate::block::{BlockRng, BlockRng64, BlockRngCore}; + + #[derive(Debug, Clone)] + struct DummyRng { + counter: u32, + } + + impl BlockRngCore for DummyRng { + type Item = u32; + + type Results = [u32; 16]; + + fn generate(&mut self, results: &mut Self::Results) { + for r in results { + *r = 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::<DummyRng>::from_seed([1, 2, 3, 4]); + let mut rng2 = rng1.clone(); + let mut rng3 = rng1.clone(); + + let mut a = [0; 16]; + (&mut a[..4]).copy_from_slice(&rng1.next_u32().to_le_bytes()); + (&mut a[4..12]).copy_from_slice(&rng1.next_u64().to_le_bytes()); + (&mut a[12..]).copy_from_slice(&rng1.next_u32().to_le_bytes()); + + let mut b = [0; 16]; + (&mut b[..4]).copy_from_slice(&rng2.next_u32().to_le_bytes()); + (&mut b[4..8]).copy_from_slice(&rng2.next_u32().to_le_bytes()); + (&mut b[8..]).copy_from_slice(&rng2.next_u64().to_le_bytes()); + assert_eq!(a, b); + + let mut c = [0; 16]; + (&mut c[..8]).copy_from_slice(&rng3.next_u64().to_le_bytes()); + (&mut c[8..12]).copy_from_slice(&rng3.next_u32().to_le_bytes()); + (&mut c[12..]).copy_from_slice(&rng3.next_u32().to_le_bytes()); + assert_eq!(a, c); + } + + #[derive(Debug, Clone)] + struct DummyRng64 { + counter: u64, + } + + impl BlockRngCore for DummyRng64 { + type Item = u64; + + type Results = [u64; 8]; + + fn generate(&mut self, results: &mut Self::Results) { + for r in results { + *r = self.counter; + self.counter = self.counter.wrapping_add(2781463553396133981); + } + } + } + + impl SeedableRng for DummyRng64 { + type Seed = [u8; 8]; + + fn from_seed(seed: Self::Seed) -> Self { + DummyRng64 { counter: u64::from_le_bytes(seed) } + } + } + + #[test] + fn blockrng64_next_u32_vs_next_u64() { + let mut rng1 = BlockRng64::<DummyRng64>::from_seed([1, 2, 3, 4, 5, 6, 7, 8]); + let mut rng2 = rng1.clone(); + let mut rng3 = rng1.clone(); + + let mut a = [0; 16]; + (&mut a[..4]).copy_from_slice(&rng1.next_u32().to_le_bytes()); + (&mut a[4..12]).copy_from_slice(&rng1.next_u64().to_le_bytes()); + (&mut a[12..]).copy_from_slice(&rng1.next_u32().to_le_bytes()); + + let mut b = [0; 16]; + (&mut b[..4]).copy_from_slice(&rng2.next_u32().to_le_bytes()); + (&mut b[4..8]).copy_from_slice(&rng2.next_u32().to_le_bytes()); + (&mut b[8..]).copy_from_slice(&rng2.next_u64().to_le_bytes()); + assert_ne!(a, b); + assert_eq!(&a[..4], &b[..4]); + assert_eq!(&a[4..12], &b[8..]); + + let mut c = [0; 16]; + (&mut c[..8]).copy_from_slice(&rng3.next_u64().to_le_bytes()); + (&mut c[8..12]).copy_from_slice(&rng3.next_u32().to_le_bytes()); + (&mut c[12..]).copy_from_slice(&rng3.next_u32().to_le_bytes()); + assert_eq!(b, c); + } +} diff --git a/third_party/rust/rand_core/src/error.rs b/third_party/rust/rand_core/src/error.rs new file mode 100644 index 0000000000..411896f2c4 --- /dev/null +++ b/third_party/rust/rand_core/src/error.rs @@ -0,0 +1,228 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Error types + +use core::fmt; +use core::num::NonZeroU32; + +#[cfg(feature = "std")] use std::boxed::Box; + +/// Error type of random number generators +/// +/// In order to be compatible with `std` and `no_std`, this type has two +/// possible implementations: with `std` a boxed `Error` trait object is stored, +/// while with `no_std` we merely store an error code. +pub struct Error { + #[cfg(feature = "std")] + inner: Box<dyn std::error::Error + Send + Sync + 'static>, + #[cfg(not(feature = "std"))] + code: NonZeroU32, +} + +impl Error { + /// Codes at or above this point can be used by users to define their own + /// custom errors. + /// + /// This has a fixed value of `(1 << 31) + (1 << 30) = 0xC000_0000`, + /// therefore the number of values available for custom codes is `1 << 30`. + /// + /// This is identical to [`getrandom::Error::CUSTOM_START`](https://docs.rs/getrandom/latest/getrandom/struct.Error.html#associatedconstant.CUSTOM_START). + pub const CUSTOM_START: u32 = (1 << 31) + (1 << 30); + /// Codes below this point represent OS Errors (i.e. positive i32 values). + /// Codes at or above this point, but below [`Error::CUSTOM_START`] are + /// reserved for use by the `rand` and `getrandom` crates. + /// + /// This is identical to [`getrandom::Error::INTERNAL_START`](https://docs.rs/getrandom/latest/getrandom/struct.Error.html#associatedconstant.INTERNAL_START). + pub const INTERNAL_START: u32 = 1 << 31; + + /// Construct from any type supporting `std::error::Error` + /// + /// Available only when configured with `std`. + /// + /// See also `From<NonZeroU32>`, which is available with and without `std`. + #[cfg(feature = "std")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "std")))] + #[inline] + pub fn new<E>(err: E) -> Self + where + E: Into<Box<dyn std::error::Error + Send + Sync + 'static>>, + { + Error { inner: err.into() } + } + + /// Reference the inner error (`std` only) + /// + /// When configured with `std`, this is a trivial operation and never + /// panics. Without `std`, this method is simply unavailable. + #[cfg(feature = "std")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "std")))] + #[inline] + pub fn inner(&self) -> &(dyn std::error::Error + Send + Sync + 'static) { + &*self.inner + } + + /// Unwrap the inner error (`std` only) + /// + /// When configured with `std`, this is a trivial operation and never + /// panics. Without `std`, this method is simply unavailable. + #[cfg(feature = "std")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "std")))] + #[inline] + pub fn take_inner(self) -> Box<dyn std::error::Error + Send + Sync + 'static> { + self.inner + } + + /// Extract the raw OS error code (if this error came from the OS) + /// + /// This method is identical to `std::io::Error::raw_os_error()`, except + /// that it works in `no_std` contexts. If this method returns `None`, the + /// error value can still be formatted via the `Display` implementation. + #[inline] + pub fn raw_os_error(&self) -> Option<i32> { + #[cfg(feature = "std")] + { + if let Some(e) = self.inner.downcast_ref::<std::io::Error>() { + return e.raw_os_error(); + } + } + match self.code() { + Some(code) if u32::from(code) < Self::INTERNAL_START => Some(u32::from(code) as i32), + _ => None, + } + } + + /// Retrieve the error code, if any. + /// + /// If this `Error` was constructed via `From<NonZeroU32>`, then this method + /// will return this `NonZeroU32` code (for `no_std` this is always the + /// case). Otherwise, this method will return `None`. + #[inline] + pub fn code(&self) -> Option<NonZeroU32> { + #[cfg(feature = "std")] + { + self.inner.downcast_ref::<ErrorCode>().map(|c| c.0) + } + #[cfg(not(feature = "std"))] + { + Some(self.code) + } + } +} + +impl fmt::Debug for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + #[cfg(feature = "std")] + { + write!(f, "Error {{ inner: {:?} }}", self.inner) + } + #[cfg(all(feature = "getrandom", not(feature = "std")))] + { + getrandom::Error::from(self.code).fmt(f) + } + #[cfg(not(feature = "getrandom"))] + { + write!(f, "Error {{ code: {} }}", self.code) + } + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + #[cfg(feature = "std")] + { + write!(f, "{}", self.inner) + } + #[cfg(all(feature = "getrandom", not(feature = "std")))] + { + getrandom::Error::from(self.code).fmt(f) + } + #[cfg(not(feature = "getrandom"))] + { + write!(f, "error code {}", self.code) + } + } +} + +impl From<NonZeroU32> for Error { + #[inline] + fn from(code: NonZeroU32) -> Self { + #[cfg(feature = "std")] + { + Error { + inner: Box::new(ErrorCode(code)), + } + } + #[cfg(not(feature = "std"))] + { + Error { code } + } + } +} + +#[cfg(feature = "getrandom")] +impl From<getrandom::Error> for Error { + #[inline] + fn from(error: getrandom::Error) -> Self { + #[cfg(feature = "std")] + { + Error { + inner: Box::new(error), + } + } + #[cfg(not(feature = "std"))] + { + Error { code: error.code() } + } + } +} + +#[cfg(feature = "std")] +impl std::error::Error for Error { + #[inline] + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + self.inner.source() + } +} + +#[cfg(feature = "std")] +impl From<Error> for std::io::Error { + #[inline] + fn from(error: Error) -> Self { + if let Some(code) = error.raw_os_error() { + std::io::Error::from_raw_os_error(code) + } else { + std::io::Error::new(std::io::ErrorKind::Other, error) + } + } +} + +#[cfg(feature = "std")] +#[derive(Debug, Copy, Clone)] +struct ErrorCode(NonZeroU32); + +#[cfg(feature = "std")] +impl fmt::Display for ErrorCode { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "error code {}", self.0) + } +} + +#[cfg(feature = "std")] +impl std::error::Error for ErrorCode {} + +#[cfg(test)] +mod test { + #[cfg(feature = "getrandom")] + #[test] + fn test_error_codes() { + // Make sure the values are the same as in `getrandom`. + assert_eq!(super::Error::CUSTOM_START, getrandom::Error::CUSTOM_START); + assert_eq!(super::Error::INTERNAL_START, getrandom::Error::INTERNAL_START); + } +} diff --git a/third_party/rust/rand_core/src/impls.rs b/third_party/rust/rand_core/src/impls.rs new file mode 100644 index 0000000000..4b7688c5c8 --- /dev/null +++ b/third_party/rust/rand_core/src/impls.rs @@ -0,0 +1,207 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Helper functions for implementing `RngCore` functions. +//! +//! For cross-platform reproducibility, these functions all use Little Endian: +//! least-significant part first. For example, `next_u64_via_u32` takes `u32` +//! values `x, y`, then outputs `(y << 32) | x`. To implement `next_u32` +//! from `next_u64` in little-endian order, one should use `next_u64() as u32`. +//! +//! 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. + +use crate::RngCore; +use core::cmp::min; + +/// Implement `next_u64` via `next_u32`, little-endian order. +pub fn next_u64_via_u32<R: RngCore + ?Sized>(rng: &mut R) -> u64 { + // Use LE; we explicitly generate one value before the next. + let x = u64::from(rng.next_u32()); + let y = u64::from(rng.next_u32()); + (y << 32) | x +} + +/// Implement `fill_bytes` via `next_u64` and `next_u32`, little-endian order. +/// +/// The fastest way to fill a slice is usually to work as long as possible with +/// integers. That is why this method mostly uses `next_u64`, and only when +/// there are 4 or less bytes remaining at the end of the slice it uses +/// `next_u32` once. +pub fn fill_bytes_via_next<R: RngCore + ?Sized>(rng: &mut R, dest: &mut [u8]) { + let mut left = dest; + while left.len() >= 8 { + let (l, r) = { left }.split_at_mut(8); + left = r; + let chunk: [u8; 8] = rng.next_u64().to_le_bytes(); + l.copy_from_slice(&chunk); + } + let n = left.len(); + if n > 4 { + let chunk: [u8; 8] = rng.next_u64().to_le_bytes(); + left.copy_from_slice(&chunk[..n]); + } else if n > 0 { + let chunk: [u8; 4] = rng.next_u32().to_le_bytes(); + left.copy_from_slice(&chunk[..n]); + } +} + +trait Observable: Copy { + type Bytes: AsRef<[u8]>; + fn to_le_bytes(self) -> Self::Bytes; + + // Contract: observing self is memory-safe (implies no uninitialised padding) + fn as_byte_slice(x: &[Self]) -> &[u8]; +} +impl Observable for u32 { + type Bytes = [u8; 4]; + fn to_le_bytes(self) -> Self::Bytes { + self.to_le_bytes() + } + fn as_byte_slice(x: &[Self]) -> &[u8] { + let ptr = x.as_ptr() as *const u8; + let len = x.len() * core::mem::size_of::<Self>(); + unsafe { core::slice::from_raw_parts(ptr, len) } + } +} +impl Observable for u64 { + type Bytes = [u8; 8]; + fn to_le_bytes(self) -> Self::Bytes { + self.to_le_bytes() + } + fn as_byte_slice(x: &[Self]) -> &[u8] { + let ptr = x.as_ptr() as *const u8; + let len = x.len() * core::mem::size_of::<Self>(); + unsafe { core::slice::from_raw_parts(ptr, len) } + } +} + +fn fill_via_chunks<T: Observable>(src: &[T], dest: &mut [u8]) -> (usize, usize) { + let size = core::mem::size_of::<T>(); + let byte_len = min(src.len() * size, dest.len()); + let num_chunks = (byte_len + size - 1) / size; + + if cfg!(target_endian = "little") { + // On LE we can do a simple copy, which is 25-50% faster: + dest[..byte_len].copy_from_slice(&T::as_byte_slice(&src[..num_chunks])[..byte_len]); + } else { + // This code is valid on all arches, but slower than the above: + let mut i = 0; + let mut iter = dest[..byte_len].chunks_exact_mut(size); + for chunk in &mut iter { + chunk.copy_from_slice(src[i].to_le_bytes().as_ref()); + i += 1; + } + let chunk = iter.into_remainder(); + if !chunk.is_empty() { + chunk.copy_from_slice(&src[i].to_le_bytes().as_ref()[..chunk.len()]); + } + } + + (num_chunks, byte_len) +} + +/// Implement `fill_bytes` by reading chunks from the output buffer of a block +/// based RNG. +/// +/// The return values are `(consumed_u32, filled_u8)`. +/// +/// `filled_u8` is the number of filled bytes in `dest`, which may be less than +/// the length of `dest`. +/// `consumed_u32` is the number of words consumed from `src`, which is the same +/// as `filled_u8 / 4` rounded up. +/// +/// # Example +/// (from `IsaacRng`) +/// +/// ```ignore +/// fn fill_bytes(&mut self, dest: &mut [u8]) { +/// let mut read_len = 0; +/// while read_len < dest.len() { +/// if self.index >= self.rsl.len() { +/// self.isaac(); +/// } +/// +/// let (consumed_u32, filled_u8) = +/// impls::fill_via_u32_chunks(&mut self.rsl[self.index..], +/// &mut dest[read_len..]); +/// +/// self.index += consumed_u32; +/// read_len += filled_u8; +/// } +/// } +/// ``` +pub fn fill_via_u32_chunks(src: &[u32], dest: &mut [u8]) -> (usize, usize) { + fill_via_chunks(src, dest) +} + +/// Implement `fill_bytes` by reading chunks from the output buffer of a block +/// based RNG. +/// +/// The return values are `(consumed_u64, filled_u8)`. +/// `filled_u8` is the number of filled bytes in `dest`, which may be less than +/// the length of `dest`. +/// `consumed_u64` is the number of words consumed from `src`, which is the same +/// as `filled_u8 / 8` rounded up. +/// +/// See `fill_via_u32_chunks` for an example. +pub fn fill_via_u64_chunks(src: &[u64], dest: &mut [u8]) -> (usize, usize) { + fill_via_chunks(src, dest) +} + +/// Implement `next_u32` via `fill_bytes`, little-endian order. +pub fn next_u32_via_fill<R: RngCore + ?Sized>(rng: &mut R) -> u32 { + let mut buf = [0; 4]; + rng.fill_bytes(&mut buf); + u32::from_le_bytes(buf) +} + +/// Implement `next_u64` via `fill_bytes`, little-endian order. +pub fn next_u64_via_fill<R: RngCore + ?Sized>(rng: &mut R) -> u64 { + let mut buf = [0; 8]; + rng.fill_bytes(&mut buf); + u64::from_le_bytes(buf) +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn test_fill_via_u32_chunks() { + let src = [1, 2, 3]; + let mut dst = [0u8; 11]; + assert_eq!(fill_via_u32_chunks(&src, &mut dst), (3, 11)); + assert_eq!(dst, [1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0]); + + let mut dst = [0u8; 13]; + assert_eq!(fill_via_u32_chunks(&src, &mut dst), (3, 12)); + assert_eq!(dst, [1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 0]); + + let mut dst = [0u8; 5]; + assert_eq!(fill_via_u32_chunks(&src, &mut dst), (2, 5)); + assert_eq!(dst, [1, 0, 0, 0, 2]); + } + + #[test] + fn test_fill_via_u64_chunks() { + let src = [1, 2]; + let mut dst = [0u8; 11]; + assert_eq!(fill_via_u64_chunks(&src, &mut dst), (2, 11)); + assert_eq!(dst, [1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0]); + + let mut dst = [0u8; 17]; + assert_eq!(fill_via_u64_chunks(&src, &mut dst), (2, 16)); + assert_eq!(dst, [1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0]); + + let mut dst = [0u8; 5]; + assert_eq!(fill_via_u64_chunks(&src, &mut dst), (1, 5)); + assert_eq!(dst, [1, 0, 0, 0, 0]); + } +} diff --git a/third_party/rust/rand_core/src/le.rs b/third_party/rust/rand_core/src/le.rs new file mode 100644 index 0000000000..ed42e57f47 --- /dev/null +++ b/third_party/rust/rand_core/src/le.rs @@ -0,0 +1,56 @@ +// Copyright 2018 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Little-Endian utilities +//! +//! Little-Endian order has been chosen for internal usage; this makes some +//! useful functions available. + +use core::convert::TryInto; + +/// Reads unsigned 32 bit integers from `src` into `dst`. +#[inline] +pub fn read_u32_into(src: &[u8], dst: &mut [u32]) { + assert!(src.len() >= 4 * dst.len()); + for (out, chunk) in dst.iter_mut().zip(src.chunks_exact(4)) { + *out = u32::from_le_bytes(chunk.try_into().unwrap()); + } +} + +/// Reads unsigned 64 bit integers from `src` into `dst`. +#[inline] +pub fn read_u64_into(src: &[u8], dst: &mut [u64]) { + assert!(src.len() >= 8 * dst.len()); + for (out, chunk) in dst.iter_mut().zip(src.chunks_exact(8)) { + *out = u64::from_le_bytes(chunk.try_into().unwrap()); + } +} + +#[test] +fn test_read() { + let bytes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]; + + let mut buf = [0u32; 4]; + read_u32_into(&bytes, &mut buf); + assert_eq!(buf[0], 0x04030201); + assert_eq!(buf[3], 0x100F0E0D); + + let mut buf = [0u32; 3]; + read_u32_into(&bytes[1..13], &mut buf); // unaligned + assert_eq!(buf[0], 0x05040302); + assert_eq!(buf[2], 0x0D0C0B0A); + + let mut buf = [0u64; 2]; + read_u64_into(&bytes, &mut buf); + assert_eq!(buf[0], 0x0807060504030201); + assert_eq!(buf[1], 0x100F0E0D0C0B0A09); + + let mut buf = [0u64; 1]; + read_u64_into(&bytes[7..15], &mut buf); // unaligned + assert_eq!(buf[0], 0x0F0E0D0C0B0A0908); +} diff --git a/third_party/rust/rand_core/src/lib.rs b/third_party/rust/rand_core/src/lib.rs new file mode 100644 index 0000000000..1234a566c0 --- /dev/null +++ b/third_party/rust/rand_core/src/lib.rs @@ -0,0 +1,531 @@ +// Copyright 2018 Developers of the Rand project. +// Copyright 2017-2018 The Rust Project Developers. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Random number generation traits +//! +//! This crate is mainly of interest to crates publishing implementations of +//! [`RngCore`]. Other users are encouraged to use the [`rand`] crate instead +//! which re-exports the main traits and error types. +//! +//! [`RngCore`] is the core trait implemented by algorithmic pseudo-random number +//! generators and external random-number sources. +//! +//! [`SeedableRng`] is an extension trait for construction from fixed seeds and +//! other random number generators. +//! +//! [`Error`] is provided for error-handling. It is safe to use in `no_std` +//! environments. +//! +//! The [`impls`] and [`le`] sub-modules include a few small functions to assist +//! implementation of [`RngCore`]. +//! +//! [`rand`]: https://docs.rs/rand + +#![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", + html_root_url = "https://rust-random.github.io/rand/" +)] +#![deny(missing_docs)] +#![deny(missing_debug_implementations)] +#![doc(test(attr(allow(unused_variables), deny(warnings))))] +#![cfg_attr(doc_cfg, feature(doc_cfg))] +#![no_std] + +use core::convert::AsMut; +use core::default::Default; + +#[cfg(feature = "std")] extern crate std; +#[cfg(feature = "alloc")] extern crate alloc; +#[cfg(feature = "alloc")] use alloc::boxed::Box; + +pub use error::Error; +#[cfg(feature = "getrandom")] pub use os::OsRng; + + +pub mod block; +mod error; +pub mod impls; +pub mod le; +#[cfg(feature = "getrandom")] mod os; + + +/// The core of a random number generator. +/// +/// This trait encapsulates the low-level functionality common to all +/// generators, and is the "back end", to be implemented by generators. +/// End users should normally use the `Rng` trait from the [`rand`] crate, +/// which is automatically implemented for every type implementing `RngCore`. +/// +/// Three different methods for generating random data are provided since the +/// optimal implementation of each is dependent on the type of generator. There +/// is no required relationship between the output of each; e.g. many +/// implementations of [`fill_bytes`] consume a whole number of `u32` or `u64` +/// values and drop any remaining unused bytes. The same can happen with the +/// [`next_u32`] and [`next_u64`] methods, implementations may discard some +/// random bits for efficiency. +/// +/// The [`try_fill_bytes`] method is a variant of [`fill_bytes`] allowing error +/// handling; it is not deemed sufficiently useful to add equivalents for +/// [`next_u32`] or [`next_u64`] since the latter methods are almost always used +/// with algorithmic generators (PRNGs), which are normally infallible. +/// +/// Implementers should produce bits uniformly. Pathological RNGs (e.g. always +/// returning the same value, or never setting certain bits) can break rejection +/// sampling used by random distributions, and also break other RNGs when +/// seeding them via [`SeedableRng::from_rng`]. +/// +/// 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). +/// +/// Typically an RNG will implement only one of the methods available +/// in this trait directly, then use the helper functions from the +/// [`impls`] module to implement the other methods. +/// +/// It is recommended that implementations also implement: +/// +/// - `Debug` with a custom implementation which *does not* print any internal +/// state (at least, [`CryptoRng`]s should not risk leaking state through +/// `Debug`). +/// - `Serialize` and `Deserialize` (from Serde), preferably making Serde +/// support optional at the crate level in PRNG libs. +/// - `Clone`, if possible. +/// - *never* implement `Copy` (accidental copies may cause repeated values). +/// - *do not* implement `Default` for pseudorandom generators, but instead +/// implement [`SeedableRng`], to guide users towards proper seeding. +/// External / hardware RNGs can choose to implement `Default`. +/// - `Eq` and `PartialEq` could be implemented, but are probably not useful. +/// +/// # Example +/// +/// A simple example, obviously not generating very *random* output: +/// +/// ``` +/// #![allow(dead_code)] +/// use rand_core::{RngCore, Error, impls}; +/// +/// struct CountingRng(u64); +/// +/// impl RngCore for CountingRng { +/// fn next_u32(&mut self) -> u32 { +/// self.next_u64() as u32 +/// } +/// +/// fn next_u64(&mut self) -> u64 { +/// self.0 += 1; +/// self.0 +/// } +/// +/// fn fill_bytes(&mut self, dest: &mut [u8]) { +/// impls::fill_bytes_via_next(self, dest) +/// } +/// +/// fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { +/// Ok(self.fill_bytes(dest)) +/// } +/// } +/// ``` +/// +/// [`rand`]: https://docs.rs/rand +/// [`try_fill_bytes`]: RngCore::try_fill_bytes +/// [`fill_bytes`]: RngCore::fill_bytes +/// [`next_u32`]: RngCore::next_u32 +/// [`next_u64`]: RngCore::next_u64 +pub trait RngCore { + /// Return the next random `u32`. + /// + /// RNGs must implement at least one method from this trait directly. In + /// the case this method is not implemented directly, it can be implemented + /// using `self.next_u64() as u32` or via [`impls::next_u32_via_fill`]. + fn next_u32(&mut self) -> u32; + + /// Return the next random `u64`. + /// + /// RNGs must implement at least one method from this trait directly. In + /// the case this method is not implemented directly, it can be implemented + /// via [`impls::next_u64_via_u32`] or via [`impls::next_u64_via_fill`]. + fn next_u64(&mut self) -> u64; + + /// Fill `dest` with random data. + /// + /// RNGs must implement at least one method from this trait directly. In + /// the case this method is not implemented directly, it can be implemented + /// via [`impls::fill_bytes_via_next`] or + /// via [`RngCore::try_fill_bytes`]; if this generator can + /// fail the implementation must choose how best to handle errors here + /// (e.g. panic with a descriptive message or log a warning and retry a few + /// times). + /// + /// 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, dest: &mut [u8]); + + /// Fill `dest` entirely with random data. + /// + /// This is the only method which allows an RNG to report errors while + /// generating random data thus making this the primary method implemented + /// by external (true) RNGs (e.g. `OsRng`) which can fail. It may be used + /// directly to generate keys and to seed (infallible) PRNGs. + /// + /// Other than error handling, this method is identical to [`RngCore::fill_bytes`]; + /// thus this may be implemented using `Ok(self.fill_bytes(dest))` or + /// `fill_bytes` may be implemented with + /// `self.try_fill_bytes(dest).unwrap()` or more specific error handling. + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error>; +} + +/// A marker trait used to indicate that an [`RngCore`] or [`BlockRngCore`] +/// implementation is supposed to be cryptographically secure. +/// +/// *Cryptographically secure generators*, also known as *CSPRNGs*, should +/// satisfy an additional properties over other generators: 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%. +/// +/// Some generators may satisfy an additional property, however this is not +/// required by this trait: if the CSPRNG's state is revealed, it should not be +/// computationally-feasible to reconstruct output prior to this. Some other +/// generators allow backwards-computation and are considered *reversible*. +/// +/// Note that this trait is provided for guidance only and cannot guarantee +/// suitability for cryptographic applications. In general it should only be +/// implemented for well-reviewed code implementing well-regarded algorithms. +/// +/// Note also that use of a `CryptoRng` does not protect against other +/// weaknesses such as seeding from a weak entropy source or leaking state. +/// +/// [`BlockRngCore`]: block::BlockRngCore +pub trait CryptoRng {} + +/// An extension trait that is automatically implemented for any type +/// implementing [`RngCore`] and [`CryptoRng`]. +/// +/// It may be used as a trait object, and supports upcasting to [`RngCore`] via +/// the [`CryptoRngCore::as_rngcore`] method. +/// +/// # Example +/// +/// ``` +/// use rand_core::CryptoRngCore; +/// +/// #[allow(unused)] +/// fn make_token(rng: &mut dyn CryptoRngCore) -> [u8; 32] { +/// let mut buf = [0u8; 32]; +/// rng.fill_bytes(&mut buf); +/// buf +/// } +/// ``` +pub trait CryptoRngCore: CryptoRng + RngCore { + /// Upcast to an [`RngCore`] trait object. + fn as_rngcore(&mut self) -> &mut dyn RngCore; +} + +impl<T: CryptoRng + RngCore> CryptoRngCore for T { + fn as_rngcore(&mut self) -> &mut dyn RngCore { + self + } +} + +/// 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). +/// +/// [`rand`]: https://docs.rs/rand +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 the required traits `core::default::Default` and + /// `core::convert::AsMut<u8>` are 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; + /// pub struct MyRngSeed(pub [u8; N]); + /// pub struct MyRng(MyRngSeed); + /// + /// impl Default for MyRngSeed { + /// fn default() -> MyRngSeed { + /// MyRngSeed([0; N]) + /// } + /// } + /// + /// 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: Sized + Default + 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 { + // We use PCG32 to generate a u32 sequence, and copy to the seed + fn pcg32(state: &mut u64) -> [u8; 4] { + const MUL: u64 = 6364136223846793005; + const INC: u64 = 11634580027462260723; + + // 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() + } + + 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 another `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: RngCore>(mut rng: R) -> Result<Self, Error> { + let mut seed = Self::Seed::default(); + rng.try_fill_bytes(seed.as_mut())?; + Ok(Self::from_seed(seed)) + } + + /// Creates a new instance of the RNG seeded via [`getrandom`]. + /// + /// This method is the recommended way to construct non-deterministic PRNGs + /// since it is convenient and secure. + /// + /// In case the overhead of using [`getrandom`] to seed *many* PRNGs is an + /// issue, one may prefer to seed from a local PRNG, e.g. + /// `from_rng(thread_rng()).unwrap()`. + /// + /// # Panics + /// + /// If [`getrandom`] is unable to provide secure entropy this method will panic. + /// + /// [`getrandom`]: https://docs.rs/getrandom + #[cfg(feature = "getrandom")] + #[cfg_attr(doc_cfg, doc(cfg(feature = "getrandom")))] + fn from_entropy() -> Self { + let mut seed = Self::Seed::default(); + if let Err(err) = getrandom::getrandom(seed.as_mut()) { + panic!("from_entropy failed: {}", err); + } + Self::from_seed(seed) + } +} + +// Implement `RngCore` for references to an `RngCore`. +// Force inlining all functions, so that it is up to the `RngCore` +// implementation and the optimizer to decide on inlining. +impl<'a, R: RngCore + ?Sized> RngCore for &'a mut R { + #[inline(always)] + fn next_u32(&mut self) -> u32 { + (**self).next_u32() + } + + #[inline(always)] + fn next_u64(&mut self) -> u64 { + (**self).next_u64() + } + + #[inline(always)] + fn fill_bytes(&mut self, dest: &mut [u8]) { + (**self).fill_bytes(dest) + } + + #[inline(always)] + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { + (**self).try_fill_bytes(dest) + } +} + +// Implement `RngCore` for boxed references to an `RngCore`. +// Force inlining all functions, so that it is up to the `RngCore` +// implementation and the optimizer to decide on inlining. +#[cfg(feature = "alloc")] +impl<R: RngCore + ?Sized> RngCore for Box<R> { + #[inline(always)] + fn next_u32(&mut self) -> u32 { + (**self).next_u32() + } + + #[inline(always)] + fn next_u64(&mut self) -> u64 { + (**self).next_u64() + } + + #[inline(always)] + fn fill_bytes(&mut self, dest: &mut [u8]) { + (**self).fill_bytes(dest) + } + + #[inline(always)] + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { + (**self).try_fill_bytes(dest) + } +} + +#[cfg(feature = "std")] +impl std::io::Read for dyn RngCore { + fn read(&mut self, buf: &mut [u8]) -> Result<usize, std::io::Error> { + self.try_fill_bytes(buf)?; + Ok(buf.len()) + } +} + +// Implement `CryptoRng` for references to a `CryptoRng`. +impl<'a, R: CryptoRng + ?Sized> CryptoRng for &'a mut R {} + +// Implement `CryptoRng` for boxed references to a `CryptoRng`. +#[cfg(feature = "alloc")] +impl<R: CryptoRng + ?Sized> CryptoRng for Box<R> {} + +#[cfg(test)] +mod test { + use super::*; + + #[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 mut x = [0u64; 1]; + le::read_u64_into(&seed, &mut x); + 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); + } +} diff --git a/third_party/rust/rand_core/src/os.rs b/third_party/rust/rand_core/src/os.rs new file mode 100644 index 0000000000..6cd1b9cf5d --- /dev/null +++ b/third_party/rust/rand_core/src/os.rs @@ -0,0 +1,85 @@ +// Copyright 2019 Developers of the Rand project. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Interface to the random number generator of the operating system. + +use crate::{impls, CryptoRng, Error, RngCore}; +use getrandom::getrandom; + +/// A random number generator that retrieves randomness from the +/// operating system. +/// +/// This is a zero-sized struct. It can be freely constructed with `OsRng`. +/// +/// The implementation is provided by the [getrandom] crate. Refer to +/// [getrandom] documentation for details. +/// +/// This struct is only available when specifying the crate feature `getrandom` +/// or `std`. When using the `rand` lib, it is also available as `rand::rngs::OsRng`. +/// +/// # Blocking and error handling +/// +/// It is possible that when used during early boot the first call to `OsRng` +/// will block until the system's RNG is initialised. It is also possible +/// (though highly unlikely) for `OsRng` to fail on some platforms, most +/// likely due to system mis-configuration. +/// +/// After the first successful call, it is highly unlikely that failures or +/// significant delays will occur (although performance should be expected to +/// be much slower than a user-space PRNG). +/// +/// # Usage example +/// ``` +/// use rand_core::{RngCore, OsRng}; +/// +/// let mut key = [0u8; 16]; +/// OsRng.fill_bytes(&mut key); +/// let random_u64 = OsRng.next_u64(); +/// ``` +/// +/// [getrandom]: https://crates.io/crates/getrandom +#[cfg_attr(doc_cfg, doc(cfg(feature = "getrandom")))] +#[derive(Clone, Copy, Debug, Default)] +pub struct OsRng; + +impl CryptoRng for OsRng {} + +impl RngCore for OsRng { + fn next_u32(&mut self) -> u32 { + impls::next_u32_via_fill(self) + } + + fn next_u64(&mut self) -> u64 { + impls::next_u64_via_fill(self) + } + + fn fill_bytes(&mut self, dest: &mut [u8]) { + if let Err(e) = self.try_fill_bytes(dest) { + panic!("Error: {}", e); + } + } + + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { + getrandom(dest)?; + Ok(()) + } +} + +#[test] +fn test_os_rng() { + let x = OsRng.next_u64(); + let y = OsRng.next_u64(); + assert!(x != 0); + assert!(x != y); +} + +#[test] +fn test_construction() { + let mut rng = OsRng::default(); + assert!(rng.next_u64() != 0); +} |