diff options
author | Daniel Mueller <deso@posteo.net> | 2020-04-04 14:39:19 -0700 |
---|---|---|
committer | Daniel Mueller <deso@posteo.net> | 2020-04-04 14:39:19 -0700 |
commit | d0d9683df8398696147e7ee1fcffb2e4e957008c (patch) | |
tree | 4baa76712a76f4d072ee3936c07956580b230820 /rand/rand_core | |
parent | 203e691f46d591a2cc8acdfd850fa9f5b0fb8a98 (diff) | |
download | nitrocli-d0d9683df8398696147e7ee1fcffb2e4e957008c.tar.gz nitrocli-d0d9683df8398696147e7ee1fcffb2e4e957008c.tar.bz2 |
Remove vendored dependencies
While it appears that by now we actually can get successful builds
without Cargo insisting on Internet access by virtue of using the
--frozen flag, maintaining vendored dependencies is somewhat of a pain
point. This state will also get worse with upcoming changes that replace
argparse in favor of structopt and pull in a slew of new dependencies by
doing so. Then there is also the repository structure aspect, which is
non-standard due to the way we vendor dependencies and a potential
source of confusion.
In order to fix these problems, this change removes all the vendored
dependencies we have.
Delete subrepo argparse/:argparse
Delete subrepo base32/:base32
Delete subrepo cc/:cc
Delete subrepo cfg-if/:cfg-if
Delete subrepo getrandom/:getrandom
Delete subrepo lazy-static/:lazy-static
Delete subrepo libc/:libc
Delete subrepo nitrokey-sys/:nitrokey-sys
Delete subrepo nitrokey/:nitrokey
Delete subrepo rand/:rand
Diffstat (limited to 'rand/rand_core')
-rw-r--r-- | rand/rand_core/CHANGELOG.md | 58 | ||||
-rw-r--r-- | rand/rand_core/COPYRIGHT | 12 | ||||
-rw-r--r-- | rand/rand_core/Cargo.toml | 28 | ||||
-rw-r--r-- | rand/rand_core/LICENSE-APACHE | 201 | ||||
-rw-r--r-- | rand/rand_core/LICENSE-MIT | 26 | ||||
-rw-r--r-- | rand/rand_core/README.md | 82 | ||||
-rw-r--r-- | rand/rand_core/src/block.rs | 437 | ||||
-rw-r--r-- | rand/rand_core/src/error.rs | 190 | ||||
-rw-r--r-- | rand/rand_core/src/impls.rs | 158 | ||||
-rw-r--r-- | rand/rand_core/src/le.rs | 68 | ||||
-rw-r--r-- | rand/rand_core/src/lib.rs | 492 | ||||
-rw-r--r-- | rand/rand_core/src/os.rs | 85 |
12 files changed, 0 insertions, 1837 deletions
diff --git a/rand/rand_core/CHANGELOG.md b/rand/rand_core/CHANGELOG.md deleted file mode 100644 index dfdd692..0000000 --- a/rand/rand_core/CHANGELOG.md +++ /dev/null @@ -1,58 +0,0 @@ -# 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.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/rand/rand_core/COPYRIGHT b/rand/rand_core/COPYRIGHT deleted file mode 100644 index 468d907..0000000 --- a/rand/rand_core/COPYRIGHT +++ /dev/null @@ -1,12 +0,0 @@ -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/rand/rand_core/Cargo.toml b/rand/rand_core/Cargo.toml deleted file mode 100644 index e52af5f..0000000 --- a/rand/rand_core/Cargo.toml +++ /dev/null @@ -1,28 +0,0 @@ -[package] -name = "rand_core" -version = "0.5.1" -authors = ["The Rand Project Developers", "The Rust Project Developers"] -license = "MIT OR Apache-2.0" -readme = "README.md" -repository = "https://github.com/rust-random/rand" -documentation = "https://rust-random.github.io/rand/rand_core/" -homepage = "https://crates.io/crates/rand_core" -description = """ -Core random number generator traits and tools for implementation. -""" -keywords = ["random", "rng"] -categories = ["algorithms", "no-std"] -edition = "2018" - -[badges] -travis-ci = { repository = "rust-random/rand" } -appveyor = { repository = "rust-random/rand" } - -[features] -std = ["alloc", "getrandom", "getrandom/std"] # use std library; should be default but for above bug -alloc = [] # enables Vec and Box support without std -serde1 = ["serde"] # enables serde for BlockRng wrapper - -[dependencies] -serde = { version = "1", features = ["derive"], optional = true } -getrandom = { version = "0.1", optional = true } diff --git a/rand/rand_core/LICENSE-APACHE b/rand/rand_core/LICENSE-APACHE deleted file mode 100644 index 17d7468..0000000 --- a/rand/rand_core/LICENSE-APACHE +++ /dev/null @@ -1,201 +0,0 @@ - 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. - -Copyright [yyyy] [name of copyright owner] - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - https://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. diff --git a/rand/rand_core/LICENSE-MIT b/rand/rand_core/LICENSE-MIT deleted file mode 100644 index d93b5ba..0000000 --- a/rand/rand_core/LICENSE-MIT +++ /dev/null @@ -1,26 +0,0 @@ -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/rand/rand_core/README.md b/rand/rand_core/README.md deleted file mode 100644 index 467e66f..0000000 --- a/rand/rand_core/README.md +++ /dev/null @@ -1,82 +0,0 @@ -# rand_core - -[![Build Status](https://travis-ci.org/rust-random/rand.svg)](https://travis-ci.org/rust-random/rand) -[![Build Status](https://ci.appveyor.com/api/projects/status/github/rust-random/rand?svg=true)](https://ci.appveyor.com/project/rust-random/rand) -[![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.32+-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.5.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/rand/rand_core/src/block.rs b/rand/rand_core/src/block.rs deleted file mode 100644 index 0ab7458..0000000 --- a/rand/rand_core/src/block.rs +++ /dev/null @@ -1,437 +0,0 @@ -// 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 -//! -//! ```norun -//! use rand_core::block::{BlockRngCore, BlockRng}; -//! -//! struct MyRngCore; -//! -//! impl BlockRngCore for MyRngCore { -//! type Results = [u32; 16]; -//! -//! fn generate(&mut self, results: &mut Self::Results) { -//! unimplemented!() -//! } -//! } -//! -//! impl SeedableRng for MyRngCore { -//! type Seed = unimplemented!(); -//! fn from_seed(seed: Self::Seed) -> Self { -//! unimplemented!() -//! } -//! } -//! -//! // optionally, also implement CryptoRng for MyRngCore -//! -//! // Final RNG. -//! type MyRng = BlockRng<u32, MyRngCore>; -//! ``` -//! -//! [`BlockRngCore`]: crate::block::BlockRngCore -//! [`fill_bytes`]: RngCore::fill_bytes - -use core::convert::AsRef; -use core::{fmt, ptr}; -#[cfg(feature="serde1")] use serde::{Serialize, Deserialize}; -use crate::{RngCore, CryptoRng, SeedableRng, Error}; -use crate::impls::{fill_via_u32_chunks, fill_via_u64_chunks}; - -/// 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 thown 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))] -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| { - if cfg!(any(target_endian = "little")) { - // requires little-endian CPU - #[allow(clippy::cast_ptr_alignment)] // false positive - let ptr: *const u64 = results[index..=index+1].as_ptr() as *const u64; - unsafe { ptr::read_unaligned(ptr) } - } else { - let x = u64::from(results[index]); - let y = u64::from(results[index + 1]); - (y << 32) | x - } - }; - - 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 * 2 - self.half_used as usize; - if index >= self.results.as_ref().len() * 2 { - self.core.generate(&mut self.results); - self.index = 0; - // `self.half_used` is by definition `false` - self.half_used = false; - index = 0; - } - - self.half_used = !self.half_used; - self.index += self.half_used as usize; - - // Index as if this is a u32 slice. - unsafe { - let results = - &*(self.results.as_ref() as *const [u64] as *const [u32]); - if cfg!(target_endian = "little") { - *results.get_unchecked(index) - } else { - *results.get_unchecked(index ^ 1) - } - } - } - - #[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> {} diff --git a/rand/rand_core/src/error.rs b/rand/rand_core/src/error.rs deleted file mode 100644 index 30b095c..0000000 --- a/rand/rand_core/src/error.rs +++ /dev/null @@ -1,190 +0,0 @@ -// 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; - - -/// 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 { - /// 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")] - #[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")] - #[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")] - #[inline] - pub fn take_inner(self) -> Box<dyn std::error::Error + Send + Sync + 'static> { - self.inner - } - - /// 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. - pub const INTERNAL_START: u32 = 1 << 31; - - /// Codes at or above this point can be used by users to define their own - /// custom errors. - pub const CUSTOM_START: u32 = (1 << 31) + (1 << 30); - - /// 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 `Diplay` 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 {} diff --git a/rand/rand_core/src/impls.rs b/rand/rand_core/src/impls.rs deleted file mode 100644 index dee4ed1..0000000 --- a/rand/rand_core/src/impls.rs +++ /dev/null @@ -1,158 +0,0 @@ -// 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 core::ptr::copy_nonoverlapping; -use core::slice; -use core::cmp::min; -use core::mem::size_of; -use crate::RngCore; - - -/// 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]); - } -} - -macro_rules! impl_uint_from_fill { - ($rng:expr, $ty:ty, $N:expr) => ({ - debug_assert!($N == size_of::<$ty>()); - - let mut int: $ty = 0; - unsafe { - let ptr = &mut int as *mut $ty as *mut u8; - let slice = slice::from_raw_parts_mut(ptr, $N); - $rng.fill_bytes(slice); - } - int - }); -} - -macro_rules! fill_via_chunks { - ($src:expr, $dst:expr, $ty:ty, $size:expr) => ({ - let chunk_size_u8 = min($src.len() * $size, $dst.len()); - let chunk_size = (chunk_size_u8 + $size - 1) / $size; - if cfg!(target_endian="little") { - unsafe { - copy_nonoverlapping( - $src.as_ptr() as *const u8, - $dst.as_mut_ptr(), - chunk_size_u8); - } - } else { - for (&n, chunk) in $src.iter().zip($dst.chunks_mut($size)) { - let tmp = n.to_le(); - let src_ptr = &tmp as *const $ty as *const u8; - unsafe { - copy_nonoverlapping(src_ptr, - chunk.as_mut_ptr(), - chunk.len()); - } - } - } - - (chunk_size, chunk_size_u8) - }); -} - -/// 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, u32, 4) -} - -/// 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, u64, 8) -} - -/// Implement `next_u32` via `fill_bytes`, little-endian order. -pub fn next_u32_via_fill<R: RngCore + ?Sized>(rng: &mut R) -> u32 { - impl_uint_from_fill!(rng, u32, 4) -} - -/// Implement `next_u64` via `fill_bytes`, little-endian order. -pub fn next_u64_via_fill<R: RngCore + ?Sized>(rng: &mut R) -> u64 { - impl_uint_from_fill!(rng, u64, 8) -} - -// TODO: implement tests for the above diff --git a/rand/rand_core/src/le.rs b/rand/rand_core/src/le.rs deleted file mode 100644 index 266651f..0000000 --- a/rand/rand_core/src/le.rs +++ /dev/null @@ -1,68 +0,0 @@ -// 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::ptr; - -macro_rules! read_slice { - ($src:expr, $dst:expr, $size:expr, $which:ident) => {{ - assert_eq!($src.len(), $size * $dst.len()); - - unsafe { - ptr::copy_nonoverlapping( - $src.as_ptr(), - $dst.as_mut_ptr() as *mut u8, - $src.len()); - } - for v in $dst.iter_mut() { - *v = v.$which(); - } - }}; -} - -/// Reads unsigned 32 bit integers from `src` into `dst`. -/// Borrowed from the `byteorder` crate. -#[inline] -pub fn read_u32_into(src: &[u8], dst: &mut [u32]) { - read_slice!(src, dst, 4, to_le); -} - -/// Reads unsigned 64 bit integers from `src` into `dst`. -/// Borrowed from the `byteorder` crate. -#[inline] -pub fn read_u64_into(src: &[u8], dst: &mut [u64]) { - read_slice!(src, dst, 8, to_le); -} - -#[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/rand/rand_core/src/lib.rs b/rand/rand_core/src/lib.rs deleted file mode 100644 index d8e0189..0000000 --- a/rand/rand_core/src/lib.rs +++ /dev/null @@ -1,492 +0,0 @@ -// 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))))] - -#![allow(clippy::unreadable_literal)] - -#![cfg_attr(not(feature="std"), no_std)] - - -use core::default::Default; -use core::convert::AsMut; -use core::ptr::copy_nonoverlapping; - -#[cfg(all(feature="alloc", not(feature="std")))] extern crate alloc; -#[cfg(all(feature="alloc", not(feature="std")))] use alloc::boxed::Box; - -pub use error::Error; -#[cfg(feature="getrandom")] pub use os::OsRng; - - -mod error; -pub mod block; -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 [`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. -/// -/// 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 implementators 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 - /// [`fill_bytes`](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 [`next_u32`](impls::next_u64_via_u32) or via - /// [`fill_bytes`](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 [`next_u*`](impls::fill_bytes_via_next) or - /// via [`try_fill_bytes`](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 [`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. - /// - /// [`fill_bytes`]: RngCore::fill_bytes - 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 consided *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 {} - -/// 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-dereferencable 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 - const MUL: u64 = 6364136223846793005; - const INC: u64 = 11634580027462260723; - - let mut seed = Self::Seed::default(); - for chunk in seed.as_mut().chunks_mut(4) { - // 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); - - // 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).to_le(); - - unsafe { - let p = &x as *const u32 as *const u8; - copy_nonoverlapping(p, chunk.as_mut_ptr(), chunk.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 - /// [`rand_os`]: https://docs.rs/rand_os - 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")] - 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 an `CryptoRng`. -impl<'a, R: CryptoRng + ?Sized> CryptoRng for &'a mut R {} - -// Implement `CryptoRng` for boxed references to an `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!(weight >= 20 && weight <= 44); - - 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/rand/rand_core/src/os.rs b/rand/rand_core/src/os.rs deleted file mode 100644 index fc23a57..0000000 --- a/rand/rand_core/src/os.rs +++ /dev/null @@ -1,85 +0,0 @@ -// 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. -// Note: keep this code in sync with the rand_os crate! - -use getrandom::getrandom; -use crate::{CryptoRng, RngCore, Error, impls}; - -/// A random number generator that retrieves randomness from 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 -#[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); -} |