From d0d9683df8398696147e7ee1fcffb2e4e957008c Mon Sep 17 00:00:00 2001 From: Daniel Mueller Date: Sat, 4 Apr 2020 14:39:19 -0700 Subject: 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 --- rand/.github/ISSUE_TEMPLATE/compile-issue.md | 16 - rand/.github/ISSUE_TEMPLATE/feature_request.md | 18 - rand/.github/ISSUE_TEMPLATE/other.md | 10 - rand/.gitignore | 4 - rand/.travis.yml | 315 ------ rand/CHANGELOG.md | 568 ---------- rand/COPYRIGHT | 12 - rand/Cargo.toml | 90 -- rand/LICENSE-APACHE | 201 ---- rand/LICENSE-MIT | 26 - rand/README.md | 118 --- rand/appveyor.yml | 49 - rand/benches/generators.rs | 220 ---- rand/benches/misc.rs | 140 --- rand/benches/seq.rs | 177 ---- rand/benches/weighted.rs | 36 - rand/examples/monte-carlo.rs | 48 - rand/examples/monty-hall.rs | 112 -- rand/rand_chacha/CHANGELOG.md | 18 - rand/rand_chacha/COPYRIGHT | 12 - rand/rand_chacha/Cargo.toml | 28 - rand/rand_chacha/LICENSE-APACHE | 201 ---- rand/rand_chacha/LICENSE-MIT | 26 - rand/rand_chacha/README.md | 49 - rand/rand_chacha/src/chacha.rs | 452 -------- rand/rand_chacha/src/lib.rs | 30 - rand/rand_core/CHANGELOG.md | 58 -- rand/rand_core/COPYRIGHT | 12 - rand/rand_core/Cargo.toml | 28 - rand/rand_core/LICENSE-APACHE | 201 ---- rand/rand_core/LICENSE-MIT | 26 - rand/rand_core/README.md | 82 -- rand/rand_core/src/block.rs | 437 -------- rand/rand_core/src/error.rs | 190 ---- rand/rand_core/src/impls.rs | 158 --- rand/rand_core/src/le.rs | 68 -- rand/rand_core/src/lib.rs | 492 --------- rand/rand_core/src/os.rs | 85 -- rand/rand_distr/CHANGELOG.md | 21 - rand/rand_distr/COPYRIGHT | 12 - rand/rand_distr/Cargo.toml | 27 - rand/rand_distr/LICENSE-APACHE | 201 ---- rand/rand_distr/LICENSE-MIT | 25 - rand/rand_distr/README.md | 42 - rand/rand_distr/benches/distributions.rs | 316 ------ rand/rand_distr/src/binomial.rs | 329 ------ rand/rand_distr/src/cauchy.rs | 120 --- rand/rand_distr/src/dirichlet.rs | 154 --- rand/rand_distr/src/exponential.rs | 145 --- rand/rand_distr/src/gamma.rs | 485 --------- rand/rand_distr/src/lib.rs | 134 --- rand/rand_distr/src/normal.rs | 219 ---- rand/rand_distr/src/pareto.rs | 89 -- rand/rand_distr/src/pert.rs | 132 --- rand/rand_distr/src/poisson.rs | 233 ----- rand/rand_distr/src/triangular.rs | 125 --- rand/rand_distr/src/unit_ball.rs | 69 -- rand/rand_distr/src/unit_circle.rs | 99 -- rand/rand_distr/src/unit_disc.rs | 66 -- rand/rand_distr/src/unit_sphere.rs | 94 -- rand/rand_distr/src/utils.rs | 234 ----- rand/rand_distr/src/weibull.rs | 86 -- rand/rand_distr/src/ziggurat_tables.rs | 279 ----- rand/rand_distr/tests/uniformity.rs | 59 -- rand/rand_hc/CHANGELOG.md | 16 - rand/rand_hc/COPYRIGHT | 12 - rand/rand_hc/Cargo.toml | 22 - rand/rand_hc/LICENSE-APACHE | 201 ---- rand/rand_hc/LICENSE-MIT | 25 - rand/rand_hc/README.md | 45 - rand/rand_hc/src/hc128.rs | 464 --------- rand/rand_hc/src/lib.rs | 23 - rand/rand_isaac/CHANGELOG.md | 21 - rand/rand_isaac/COPYRIGHT | 12 - rand/rand_isaac/Cargo.toml | 31 - rand/rand_isaac/LICENSE-APACHE | 201 ---- rand/rand_isaac/LICENSE-MIT | 26 - rand/rand_isaac/README.md | 47 - rand/rand_isaac/src/isaac.rs | 476 --------- rand/rand_isaac/src/isaac64.rs | 466 --------- rand/rand_isaac/src/isaac_array.rs | 136 --- rand/rand_isaac/src/lib.rs | 27 - rand/rand_jitter/CHANGELOG.md | 32 - rand/rand_jitter/COPYRIGHT | 12 - rand/rand_jitter/Cargo.toml | 30 - rand/rand_jitter/LICENSE-APACHE | 201 ---- rand/rand_jitter/LICENSE-MIT | 26 - rand/rand_jitter/README.md | 119 --- rand/rand_jitter/benches/mod.rs | 17 - rand/rand_jitter/src/error.rs | 77 -- rand/rand_jitter/src/lib.rs | 750 ------------- rand/rand_jitter/src/platform.rs | 44 - rand/rand_jitter/tests/mod.rs | 28 - rand/rand_os/CHANGELOG.md | 35 - rand/rand_os/COPYRIGHT | 12 - rand/rand_os/Cargo.toml | 26 - rand/rand_os/LICENSE-APACHE | 201 ---- rand/rand_os/LICENSE-MIT | 26 - rand/rand_os/README.md | 35 - rand/rand_os/src/lib.rs | 106 -- rand/rand_pcg/CHANGELOG.md | 24 - rand/rand_pcg/COPYRIGHT | 12 - rand/rand_pcg/Cargo.toml | 32 - rand/rand_pcg/LICENSE-APACHE | 201 ---- rand/rand_pcg/LICENSE-MIT | 26 - rand/rand_pcg/README.md | 43 - rand/rand_pcg/src/lib.rs | 49 - rand/rand_pcg/src/pcg128.rs | 225 ---- rand/rand_pcg/src/pcg64.rs | 127 --- rand/rand_pcg/tests/lcg128xsl64.rs | 55 - rand/rand_pcg/tests/lcg64xsh32.rs | 54 - rand/rand_pcg/tests/mcg128xsl64.rs | 54 - rand/rand_xorshift/CHANGELOG.md | 19 - rand/rand_xorshift/COPYRIGHT | 12 - rand/rand_xorshift/Cargo.toml | 31 - rand/rand_xorshift/LICENSE-APACHE | 201 ---- rand/rand_xorshift/LICENSE-MIT | 26 - rand/rand_xorshift/README.md | 45 - rand/rand_xorshift/src/lib.rs | 117 --- rand/rand_xorshift/tests/mod.rs | 89 -- rand/rand_xoshiro/CHANGELOG.md | 24 - rand/rand_xoshiro/COPYRIGHT | 12 - rand/rand_xoshiro/Cargo.toml | 25 - rand/rand_xoshiro/LICENSE-APACHE | 201 ---- rand/rand_xoshiro/LICENSE-MIT | 25 - rand/rand_xoshiro/README.md | 34 - rand/rand_xoshiro/src/common.rs | 243 ----- rand/rand_xoshiro/src/lib.rs | 94 -- rand/rand_xoshiro/src/splitmix64.rs | 149 --- rand/rand_xoshiro/src/xoroshiro128plus.rs | 130 --- rand/rand_xoshiro/src/xoroshiro128starstar.rs | 127 --- rand/rand_xoshiro/src/xoroshiro64star.rs | 102 -- rand/rand_xoshiro/src/xoroshiro64starstar.rs | 101 -- rand/rand_xoshiro/src/xoshiro128plus.rs | 112 -- rand/rand_xoshiro/src/xoshiro128starstar.rs | 111 -- rand/rand_xoshiro/src/xoshiro256plus.rs | 131 --- rand/rand_xoshiro/src/xoshiro256starstar.rs | 128 --- rand/rand_xoshiro/src/xoshiro512plus.rs | 122 --- rand/rand_xoshiro/src/xoshiro512starstar.rs | 122 --- rand/rand_xoshiro/tests/serde.rs | 83 -- rand/rustfmt.toml | 30 - rand/src/distributions/bernoulli.rs | 166 --- rand/src/distributions/binomial.rs | 313 ------ rand/src/distributions/cauchy.rs | 103 -- rand/src/distributions/dirichlet.rs | 128 --- rand/src/distributions/exponential.rs | 108 -- rand/src/distributions/float.rs | 259 ----- rand/src/distributions/gamma.rs | 371 ------- rand/src/distributions/integer.rs | 184 ---- rand/src/distributions/mod.rs | 381 ------- rand/src/distributions/normal.rs | 170 --- rand/src/distributions/other.rs | 220 ---- rand/src/distributions/pareto.rs | 67 -- rand/src/distributions/poisson.rs | 151 --- rand/src/distributions/triangular.rs | 79 -- rand/src/distributions/uniform.rs | 1270 ----------------------- rand/src/distributions/unit_circle.rs | 101 -- rand/src/distributions/unit_sphere.rs | 96 -- rand/src/distributions/utils.rs | 488 --------- rand/src/distributions/weibull.rs | 64 -- rand/src/distributions/weighted/alias_method.rs | 499 --------- rand/src/distributions/weighted/mod.rs | 363 ------- rand/src/distributions/ziggurat_tables.rs | 279 ----- rand/src/lib.rs | 720 ------------- rand/src/prelude.rs | 28 - rand/src/rngs/adapter/mod.rs | 15 - rand/src/rngs/adapter/read.rs | 148 --- rand/src/rngs/adapter/reseeding.rs | 357 ------- rand/src/rngs/entropy.rs | 76 -- rand/src/rngs/mock.rs | 64 -- rand/src/rngs/mod.rs | 119 --- rand/src/rngs/small.rs | 115 -- rand/src/rngs/std.rs | 100 -- rand/src/rngs/thread.rs | 124 --- rand/src/seq/index.rs | 409 -------- rand/src/seq/mod.rs | 791 -------------- rand/tests/wasm_bindgen/Cargo.toml | 16 - rand/tests/wasm_bindgen/js/index.js | 7 - rand/tests/wasm_bindgen/src/lib.rs | 49 - rand/utils/ci/install.sh | 49 - rand/utils/ci/install_cargo_web.sh | 15 - rand/utils/ci/miri.sh | 23 - rand/utils/ci/script.sh | 27 - rand/utils/ziggurat_tables.py | 125 --- 184 files changed, 25421 deletions(-) delete mode 100644 rand/.github/ISSUE_TEMPLATE/compile-issue.md delete mode 100644 rand/.github/ISSUE_TEMPLATE/feature_request.md delete mode 100644 rand/.github/ISSUE_TEMPLATE/other.md delete mode 100644 rand/.gitignore delete mode 100644 rand/.travis.yml delete mode 100644 rand/CHANGELOG.md delete mode 100644 rand/COPYRIGHT delete mode 100644 rand/Cargo.toml delete mode 100644 rand/LICENSE-APACHE delete mode 100644 rand/LICENSE-MIT delete mode 100644 rand/README.md delete mode 100644 rand/appveyor.yml delete mode 100644 rand/benches/generators.rs delete mode 100644 rand/benches/misc.rs delete mode 100644 rand/benches/seq.rs delete mode 100644 rand/benches/weighted.rs delete mode 100644 rand/examples/monte-carlo.rs delete mode 100644 rand/examples/monty-hall.rs delete mode 100644 rand/rand_chacha/CHANGELOG.md delete mode 100644 rand/rand_chacha/COPYRIGHT delete mode 100644 rand/rand_chacha/Cargo.toml delete mode 100644 rand/rand_chacha/LICENSE-APACHE delete mode 100644 rand/rand_chacha/LICENSE-MIT delete mode 100644 rand/rand_chacha/README.md delete mode 100644 rand/rand_chacha/src/chacha.rs delete mode 100644 rand/rand_chacha/src/lib.rs delete mode 100644 rand/rand_core/CHANGELOG.md delete mode 100644 rand/rand_core/COPYRIGHT delete mode 100644 rand/rand_core/Cargo.toml delete mode 100644 rand/rand_core/LICENSE-APACHE delete mode 100644 rand/rand_core/LICENSE-MIT delete mode 100644 rand/rand_core/README.md delete mode 100644 rand/rand_core/src/block.rs delete mode 100644 rand/rand_core/src/error.rs delete mode 100644 rand/rand_core/src/impls.rs delete mode 100644 rand/rand_core/src/le.rs delete mode 100644 rand/rand_core/src/lib.rs delete mode 100644 rand/rand_core/src/os.rs delete mode 100644 rand/rand_distr/CHANGELOG.md delete mode 100644 rand/rand_distr/COPYRIGHT delete mode 100644 rand/rand_distr/Cargo.toml delete mode 100644 rand/rand_distr/LICENSE-APACHE delete mode 100644 rand/rand_distr/LICENSE-MIT delete mode 100644 rand/rand_distr/README.md delete mode 100644 rand/rand_distr/benches/distributions.rs delete mode 100644 rand/rand_distr/src/binomial.rs delete mode 100644 rand/rand_distr/src/cauchy.rs delete mode 100644 rand/rand_distr/src/dirichlet.rs delete mode 100644 rand/rand_distr/src/exponential.rs delete mode 100644 rand/rand_distr/src/gamma.rs delete mode 100644 rand/rand_distr/src/lib.rs delete mode 100644 rand/rand_distr/src/normal.rs delete mode 100644 rand/rand_distr/src/pareto.rs delete mode 100644 rand/rand_distr/src/pert.rs delete mode 100644 rand/rand_distr/src/poisson.rs delete mode 100644 rand/rand_distr/src/triangular.rs delete mode 100644 rand/rand_distr/src/unit_ball.rs delete mode 100644 rand/rand_distr/src/unit_circle.rs delete mode 100644 rand/rand_distr/src/unit_disc.rs delete mode 100644 rand/rand_distr/src/unit_sphere.rs delete mode 100644 rand/rand_distr/src/utils.rs delete mode 100644 rand/rand_distr/src/weibull.rs delete mode 100644 rand/rand_distr/src/ziggurat_tables.rs delete mode 100644 rand/rand_distr/tests/uniformity.rs delete mode 100644 rand/rand_hc/CHANGELOG.md delete mode 100644 rand/rand_hc/COPYRIGHT delete mode 100644 rand/rand_hc/Cargo.toml delete mode 100644 rand/rand_hc/LICENSE-APACHE delete mode 100644 rand/rand_hc/LICENSE-MIT delete mode 100644 rand/rand_hc/README.md delete mode 100644 rand/rand_hc/src/hc128.rs delete mode 100644 rand/rand_hc/src/lib.rs delete mode 100644 rand/rand_isaac/CHANGELOG.md delete mode 100644 rand/rand_isaac/COPYRIGHT delete mode 100644 rand/rand_isaac/Cargo.toml delete mode 100644 rand/rand_isaac/LICENSE-APACHE delete mode 100644 rand/rand_isaac/LICENSE-MIT delete mode 100644 rand/rand_isaac/README.md delete mode 100644 rand/rand_isaac/src/isaac.rs delete mode 100644 rand/rand_isaac/src/isaac64.rs delete mode 100644 rand/rand_isaac/src/isaac_array.rs delete mode 100644 rand/rand_isaac/src/lib.rs delete mode 100644 rand/rand_jitter/CHANGELOG.md delete mode 100644 rand/rand_jitter/COPYRIGHT delete mode 100644 rand/rand_jitter/Cargo.toml delete mode 100644 rand/rand_jitter/LICENSE-APACHE delete mode 100644 rand/rand_jitter/LICENSE-MIT delete mode 100644 rand/rand_jitter/README.md delete mode 100644 rand/rand_jitter/benches/mod.rs delete mode 100644 rand/rand_jitter/src/error.rs delete mode 100644 rand/rand_jitter/src/lib.rs delete mode 100644 rand/rand_jitter/src/platform.rs delete mode 100644 rand/rand_jitter/tests/mod.rs delete mode 100644 rand/rand_os/CHANGELOG.md delete mode 100644 rand/rand_os/COPYRIGHT delete mode 100644 rand/rand_os/Cargo.toml delete mode 100644 rand/rand_os/LICENSE-APACHE delete mode 100644 rand/rand_os/LICENSE-MIT delete mode 100644 rand/rand_os/README.md delete mode 100644 rand/rand_os/src/lib.rs delete mode 100644 rand/rand_pcg/CHANGELOG.md delete mode 100644 rand/rand_pcg/COPYRIGHT delete mode 100644 rand/rand_pcg/Cargo.toml delete mode 100644 rand/rand_pcg/LICENSE-APACHE delete mode 100644 rand/rand_pcg/LICENSE-MIT delete mode 100644 rand/rand_pcg/README.md delete mode 100644 rand/rand_pcg/src/lib.rs delete mode 100644 rand/rand_pcg/src/pcg128.rs delete mode 100644 rand/rand_pcg/src/pcg64.rs delete mode 100644 rand/rand_pcg/tests/lcg128xsl64.rs delete mode 100644 rand/rand_pcg/tests/lcg64xsh32.rs delete mode 100644 rand/rand_pcg/tests/mcg128xsl64.rs delete mode 100644 rand/rand_xorshift/CHANGELOG.md delete mode 100644 rand/rand_xorshift/COPYRIGHT delete mode 100644 rand/rand_xorshift/Cargo.toml delete mode 100644 rand/rand_xorshift/LICENSE-APACHE delete mode 100644 rand/rand_xorshift/LICENSE-MIT delete mode 100644 rand/rand_xorshift/README.md delete mode 100644 rand/rand_xorshift/src/lib.rs delete mode 100644 rand/rand_xorshift/tests/mod.rs delete mode 100644 rand/rand_xoshiro/CHANGELOG.md delete mode 100644 rand/rand_xoshiro/COPYRIGHT delete mode 100644 rand/rand_xoshiro/Cargo.toml delete mode 100644 rand/rand_xoshiro/LICENSE-APACHE delete mode 100644 rand/rand_xoshiro/LICENSE-MIT delete mode 100644 rand/rand_xoshiro/README.md delete mode 100644 rand/rand_xoshiro/src/common.rs delete mode 100644 rand/rand_xoshiro/src/lib.rs delete mode 100644 rand/rand_xoshiro/src/splitmix64.rs delete mode 100644 rand/rand_xoshiro/src/xoroshiro128plus.rs delete mode 100644 rand/rand_xoshiro/src/xoroshiro128starstar.rs delete mode 100644 rand/rand_xoshiro/src/xoroshiro64star.rs delete mode 100644 rand/rand_xoshiro/src/xoroshiro64starstar.rs delete mode 100644 rand/rand_xoshiro/src/xoshiro128plus.rs delete mode 100644 rand/rand_xoshiro/src/xoshiro128starstar.rs delete mode 100644 rand/rand_xoshiro/src/xoshiro256plus.rs delete mode 100644 rand/rand_xoshiro/src/xoshiro256starstar.rs delete mode 100644 rand/rand_xoshiro/src/xoshiro512plus.rs delete mode 100644 rand/rand_xoshiro/src/xoshiro512starstar.rs delete mode 100644 rand/rand_xoshiro/tests/serde.rs delete mode 100644 rand/rustfmt.toml delete mode 100644 rand/src/distributions/bernoulli.rs delete mode 100644 rand/src/distributions/binomial.rs delete mode 100644 rand/src/distributions/cauchy.rs delete mode 100644 rand/src/distributions/dirichlet.rs delete mode 100644 rand/src/distributions/exponential.rs delete mode 100644 rand/src/distributions/float.rs delete mode 100644 rand/src/distributions/gamma.rs delete mode 100644 rand/src/distributions/integer.rs delete mode 100644 rand/src/distributions/mod.rs delete mode 100644 rand/src/distributions/normal.rs delete mode 100644 rand/src/distributions/other.rs delete mode 100644 rand/src/distributions/pareto.rs delete mode 100644 rand/src/distributions/poisson.rs delete mode 100644 rand/src/distributions/triangular.rs delete mode 100644 rand/src/distributions/uniform.rs delete mode 100644 rand/src/distributions/unit_circle.rs delete mode 100644 rand/src/distributions/unit_sphere.rs delete mode 100644 rand/src/distributions/utils.rs delete mode 100644 rand/src/distributions/weibull.rs delete mode 100644 rand/src/distributions/weighted/alias_method.rs delete mode 100644 rand/src/distributions/weighted/mod.rs delete mode 100644 rand/src/distributions/ziggurat_tables.rs delete mode 100644 rand/src/lib.rs delete mode 100644 rand/src/prelude.rs delete mode 100644 rand/src/rngs/adapter/mod.rs delete mode 100644 rand/src/rngs/adapter/read.rs delete mode 100644 rand/src/rngs/adapter/reseeding.rs delete mode 100644 rand/src/rngs/entropy.rs delete mode 100644 rand/src/rngs/mock.rs delete mode 100644 rand/src/rngs/mod.rs delete mode 100644 rand/src/rngs/small.rs delete mode 100644 rand/src/rngs/std.rs delete mode 100644 rand/src/rngs/thread.rs delete mode 100644 rand/src/seq/index.rs delete mode 100644 rand/src/seq/mod.rs delete mode 100644 rand/tests/wasm_bindgen/Cargo.toml delete mode 100644 rand/tests/wasm_bindgen/js/index.js delete mode 100644 rand/tests/wasm_bindgen/src/lib.rs delete mode 100644 rand/utils/ci/install.sh delete mode 100755 rand/utils/ci/install_cargo_web.sh delete mode 100644 rand/utils/ci/miri.sh delete mode 100644 rand/utils/ci/script.sh delete mode 100755 rand/utils/ziggurat_tables.py (limited to 'rand') diff --git a/rand/.github/ISSUE_TEMPLATE/compile-issue.md b/rand/.github/ISSUE_TEMPLATE/compile-issue.md deleted file mode 100644 index 8a8354b..0000000 --- a/rand/.github/ISSUE_TEMPLATE/compile-issue.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -name: Compile issue -about: Report / ask about a compilation issue -title: '' -labels: '' -assignees: '' - ---- - -# Common issues - -**Problem**: `rand_hc::Hc128Rng: rand_core::SeedableRng` (or other RNG) - -**Quick solution**: `cargo update` - -**Details**: This happens when multiple versions of the `rand_core` crate are in use. Check your `Cargo.lock` file for all versions of `rand_core`. Note that some versions (0.2.2 and 0.3.1) are compatibility shims and are not a problem by themselves. diff --git a/rand/.github/ISSUE_TEMPLATE/feature_request.md b/rand/.github/ISSUE_TEMPLATE/feature_request.md deleted file mode 100644 index 90c57c8..0000000 --- a/rand/.github/ISSUE_TEMPLATE/feature_request.md +++ /dev/null @@ -1,18 +0,0 @@ ---- -name: Feature request -about: Suggest an idea for this project -title: '' -labels: '' -assignees: '' - ---- - -## Background - -**What is your motivation?** - -**What type of application is this?** (E.g. cryptography, game, numerical simulation) - -## Feature request - -
diff --git a/rand/.github/ISSUE_TEMPLATE/other.md b/rand/.github/ISSUE_TEMPLATE/other.md deleted file mode 100644 index a3e76ca..0000000 --- a/rand/.github/ISSUE_TEMPLATE/other.md +++ /dev/null @@ -1,10 +0,0 @@ ---- -name: Other -about: empty template -title: '' -labels: '' -assignees: '' - ---- - - diff --git a/rand/.gitignore b/rand/.gitignore deleted file mode 100644 index ac38e81..0000000 --- a/rand/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -target -Cargo.lock -rand_wasm_bindgen_test*.[tj]s -rand_wasm_bindgen_test*.wasm diff --git a/rand/.travis.yml b/rand/.travis.yml deleted file mode 100644 index f3790dc..0000000 --- a/rand/.travis.yml +++ /dev/null @@ -1,315 +0,0 @@ -language: rust -sudo: false - -# We support too many combinations of Rust releases, crate features, operating -# systems, and architectures to even remotely test all combinations. -# Yet it turns out we can test most of these independent of each other, because -# they serve different goals or test different pieces of code. -# -# RUST RELEASES -# Goal: make sure we don't use language features unavailable on a certain -# version, and build without warnings. -# We have different builders use 4 Rust releases, a pinned stable release, -# the latest stable, beta and nightly. -# -# ARCHITECTURES -# Goal: test against issues caused by differences in endianness, pointer sizes, -# etc. -# We run tests on 4 different architectures. -# - x64_84, default on Travis (Linux) and AppVeyor (Windows) -# - i686, second AppVeyor (Windows) configuration -# - MIPS, big-endian Linux emulated with QEMU (thanks to Trust) -# - ARMv7, Android emulated with QEMU (thanks to Trust) -# -# OPERATING SYSTEMS -# Goal: test on many operating systems, to verify the OsRng code, which is -# mostly architecture-independent. -# We run tests on Linux, OS X, Windows, Android (emulated), and Node.js (using -# cargo-web). -# One builder cross-compiles for many of the remaining OSes, which ensures we -# keep building, but doesn't run tests. -# OSes supported by Rand but which we can't cross-compile because there -# is no pre-built standard library available: Dragonfly BSD, Haiku, OpenBSD. -# -# CRATE FEATURES, TESTS, AND SUB-CRATES -# Goal: Run unit tests, doctests, examples, and test benchmarks for all crates, -# in configurations that cover all interesting combinations of features. -# Tests run on rand: -# - test no_std support, but only the unit tests: -# `cargo test --tests --no-default-features` -# - test no_std support, including the alloc feature: -# cargo test --tests --no-default-features --features=alloc -# - run unit tests and doctests with all features which are available on stable: -# `cargo test --features=serde1,log` -# - test examples: -# `cargo test --examples` -# Additional tests on nightly: -# - run unit tests and doctests with all features which are available on nightly: -# `cargo test --all-features` -# - run benchmarks as tests: -# `cargo test --benches --features=nightly` -# Tests on subcrates: -# - select crates via --manifest-path (more reliable than --package) -# - test appropriate feature matrix -# -# TODO: SIMD support on stable releases -# NOTE: SIMD support is unreliable on nightly; we track the latest release -# NOTE: Test for alloc feature in no_std is not included here because it depends -# on the alloc crate stabilized in Rust 1.36. -matrix: - include: - - rust: 1.32.0 - env: DESCRIPTION="Linux, 1.32.0" - os: linux - script: - # Differs from standard script: rand_pcg features - - cargo test --tests --no-default-features - # TODO: add simd_support feature: - - cargo test --features=serde1,log - - cargo test --examples - - cargo test --manifest-path rand_core/Cargo.toml - - cargo test --manifest-path rand_core/Cargo.toml --no-default-features - - cargo test --manifest-path rand_distr/Cargo.toml - - cargo test --manifest-path rand_isaac/Cargo.toml --features=serde1 - # TODO: cannot test rand_pcg due to explicit dependency on i128 - - cargo test --manifest-path rand_xorshift/Cargo.toml --features=serde1 - - cargo test --manifest-path rand_xoshiro/Cargo.toml - - cargo test --manifest-path rand_chacha/Cargo.toml - - cargo test --manifest-path rand_hc/Cargo.toml - - cargo test --manifest-path rand_jitter/Cargo.toml - - cargo test --manifest-path rand_os/Cargo.toml - - - rust: 1.32.0 - env: DESCRIPTION="OSX, 1.32.0" - os: osx - script: - # Differs from standard script: rand_pcg features - - cargo test --tests --no-default-features - # TODO: add simd_support feature: - - cargo test --features=serde1,log - - cargo test --examples - - cargo test --manifest-path rand_core/Cargo.toml - - cargo test --manifest-path rand_core/Cargo.toml --no-default-features - - cargo test --manifest-path rand_distr/Cargo.toml - - cargo test --manifest-path rand_isaac/Cargo.toml --features=serde1 - # TODO: cannot test rand_pcg due to explicit dependency on i128 - - cargo test --manifest-path rand_xorshift/Cargo.toml --features=serde1 - - cargo test --manifest-path rand_xoshiro/Cargo.toml - - cargo test --manifest-path rand_chacha/Cargo.toml - - cargo test --manifest-path rand_hc/Cargo.toml - - cargo test --manifest-path rand_jitter/Cargo.toml - - cargo test --manifest-path rand_os/Cargo.toml - - - rust: stable - env: DESCRIPTION="Linux, stable" - - - rust: stable - env: DESCRIPTION="OSX+iOS, stable" - os: osx - install: - - rustup target add aarch64-apple-ios - script: - # Differs from standard script: includes aarch64-apple-ios cross-build - - cargo test --tests --no-default-features - # TODO: add simd_support feature: - - cargo test --features=serde1,log - - cargo test --examples - - cargo test --manifest-path rand_core/Cargo.toml - - cargo test --manifest-path rand_core/Cargo.toml --no-default-features - - cargo test --manifest-path rand_distr/Cargo.toml - - cargo test --manifest-path rand_isaac/Cargo.toml --features=serde1 - - cargo test --manifest-path rand_pcg/Cargo.toml --features=serde1 - - cargo test --manifest-path rand_xorshift/Cargo.toml --features=serde1 - - cargo test --manifest-path rand_xoshiro/Cargo.toml - - cargo test --manifest-path rand_chacha/Cargo.toml - - cargo test --manifest-path rand_hc/Cargo.toml - - cargo test --manifest-path rand_jitter/Cargo.toml - - cargo test --manifest-path rand_os/Cargo.toml - - cargo build --target=aarch64-apple-ios - - - rust: beta - env: DESCRIPTION="Linux, beta" - - - rust: nightly - os: linux - env: DESCRIPTION="Linux, nightly, docs" - install: - - cargo --list | egrep "^\s*deadlinks$" -q || cargo install cargo-deadlinks - - cargo deadlinks -V - before_script: - - pip install 'travis-cargo<0.2' --user && export PATH=$HOME/.local/bin:$PATH - script: - # Differs from standard script: all features, doc build - - cargo test --tests --no-default-features --features=alloc - - cargo test --all-features - - cargo test --benches --features=nightly - - cargo test --examples - - cargo test --manifest-path rand_core/Cargo.toml - - cargo test --manifest-path rand_core/Cargo.toml --no-default-features --features=alloc - - cargo test --manifest-path rand_distr/Cargo.toml - - cargo test --manifest-path rand_isaac/Cargo.toml --features=serde1 - - cargo test --manifest-path rand_pcg/Cargo.toml --features=serde1 - - cargo test --manifest-path rand_xorshift/Cargo.toml --features=serde1 - - cargo test --manifest-path rand_xoshiro/Cargo.toml - - cargo test --manifest-path rand_chacha/Cargo.toml - - cargo test --manifest-path rand_hc/Cargo.toml - - cargo test --manifest-path rand_jitter/Cargo.toml - - cargo test --manifest-path rand_os/Cargo.toml - # remove cached documentation, otherwise files from previous PRs can get included - - rm -rf target/doc - - cargo doc --no-deps --all --all-features - - cargo deadlinks --dir target/doc - after_success: - - travis-cargo --only nightly doc-upload - - - rust: nightly - os: osx - env: DESCRIPTION="OSX, nightly, docs" - install: - - cargo --list | egrep "^\s*deadlinks$" -q || cargo install cargo-deadlinks - - cargo deadlinks -V - script: - # Differs from standard script: all features, doc build - - cargo test --tests --no-default-features --features=alloc - - cargo test --all-features - - cargo test --benches --features=nightly - - cargo test --examples - - cargo test --manifest-path rand_core/Cargo.toml - - cargo test --manifest-path rand_core/Cargo.toml --no-default-features --features=alloc - - cargo test --manifest-path rand_distr/Cargo.toml - - cargo test --manifest-path rand_isaac/Cargo.toml --features=serde1 - - cargo test --manifest-path rand_pcg/Cargo.toml --features=serde1 - - cargo test --manifest-path rand_xorshift/Cargo.toml --features=serde1 - - cargo test --manifest-path rand_xoshiro/Cargo.toml - - cargo test --manifest-path rand_chacha/Cargo.toml - - cargo test --manifest-path rand_hc/Cargo.toml - - cargo test --manifest-path rand_jitter/Cargo.toml - - cargo test --manifest-path rand_os/Cargo.toml - # remove cached documentation, otherwise files from previous PRs can get included - - rm -rf target/doc - - cargo doc --no-deps --all --all-features - - cargo deadlinks --dir target/doc - - - rust: nightly - env: DESCRIPTION="WASM via emscripten, stdweb and wasm-bindgen" - install: - - rustup target add wasm32-unknown-unknown - - rustup target add wasm32-unknown-emscripten - - nvm install 9 - - ./utils/ci/install_cargo_web.sh - - cargo web prepare-emscripten - - cargo web -V - - cargo list | grep install-update || cargo install -f cargo-update - - cargo install-update -i cargo-update wasm-bindgen-cli wasm-pack - addons: - chrome: stable - script: - # Testing wasm32-unknown-emscripten fails because of rust-lang/rust#49877 - # However, we can still build and link all tests to make sure that works. - # This is actually useful as it finds stuff such as rust-random/rand#669 - - EMCC_CFLAGS="-s ERROR_ON_UNDEFINED_SYMBOLS=0" cargo web test --target wasm32-unknown-emscripten --no-run - #- cargo web test --target wasm32-unknown-emscripten - #- cargo web test --nodejs --target wasm32-unknown-emscripten - #- cargo build --target wasm32-unknown-unknown # without any features - - cargo build --target wasm32-unknown-unknown --features=wasm-bindgen - - cargo web test --target wasm32-unknown-unknown --features=stdweb - - cargo build --manifest-path tests/wasm_bindgen/Cargo.toml --target wasm32-unknown-unknown - - wasm-bindgen --nodejs target/wasm32-unknown-unknown/debug/rand_wasm_bindgen_test.wasm --out-dir tests/wasm_bindgen/js - - node tests/wasm_bindgen/js/index.js - - wasm-pack test --node tests/wasm_bindgen - - - rust: nightly - env: DESCRIPTION="cross-platform builder (doesn't run tests)" - install: - - rustup target add x86_64-sun-solaris - - rustup target add x86_64-unknown-cloudabi - - rustup target add x86_64-unknown-freebsd - #- rustup target add x86_64-unknown-fuchsia - - rustup target add x86_64-unknown-netbsd - - rustup target add x86_64-unknown-redox - script: - # Test the top-level crate with all features: - - cargo build --target=x86_64-sun-solaris --all-features - - cargo build --target=x86_64-unknown-cloudabi --all-features - - cargo build --target=x86_64-unknown-freebsd --all-features - #- cargo build --target=x86_64-unknown-fuchsia --all-features - - cargo build --target=x86_64-unknown-netbsd --all-features - - cargo build --target=x86_64-unknown-redox --all-features - - # Trust cross-built/emulated targets. We must repeat all non-default values. - - rust: stable - sudo: required - dist: trusty - services: docker - env: DESCRIPTION="Linux (MIPS, big-endian)" TARGET=mips-unknown-linux-gnu - install: - - sh utils/ci/install.sh - - source ~/.cargo/env || true - script: - - bash utils/ci/script.sh - - rust: stable - sudo: required - dist: trusty - services: docker - env: DESCRIPTION="Android (ARMv7)" TARGET=armv7-linux-androideabi - install: - - sh utils/ci/install.sh - - source ~/.cargo/env || true - script: - - bash utils/ci/script.sh - - rust: nightly - env: DESCRIPTION="no_std platform test" - install: - - rustup target add thumbv6m-none-eabi - script: - # Test the top-level crate with all features: - - cargo build --target=thumbv6m-none-eabi --no-default-features - - - rust: nightly - os: linux - env: DESCRIPTION="Miri, nightly" - script: - - sh utils/ci/miri.sh - -before_install: - - set -e - - rustup self update - -script: - - cargo test --tests --no-default-features - - cargo test --tests --no-default-features --features getrandom - - cargo test --tests --no-default-features --features=alloc - # TODO: add simd_support feature: - - cargo test --features=serde1,log - - cargo test --examples - - cargo test --manifest-path rand_core/Cargo.toml - - cargo test --manifest-path rand_core/Cargo.toml --no-default-features - - cargo test --manifest-path rand_core/Cargo.toml --no-default-features --features=alloc - - cargo test --manifest-path rand_distr/Cargo.toml - - cargo test --manifest-path rand_isaac/Cargo.toml --features=serde1 - - cargo test --manifest-path rand_pcg/Cargo.toml --features=serde1 - - cargo test --manifest-path rand_xorshift/Cargo.toml --features=serde1 - - cargo test --manifest-path rand_xoshiro/Cargo.toml - - cargo test --manifest-path rand_chacha/Cargo.toml - - cargo test --manifest-path rand_hc/Cargo.toml - - cargo test --manifest-path rand_jitter/Cargo.toml - - cargo test --manifest-path rand_os/Cargo.toml - -after_script: set +e - -cache: - cargo: true - directories: - - .local/share/cargo-web - -before_cache: - # Travis can't cache files that are not readable by "others" - - chmod -R a+r $HOME/.cargo - -env: - global: - secure: "BdDntVHSompN+Qxz5Rz45VI4ZqhD72r6aPl166FADlnkIwS6N6FLWdqs51O7G5CpoMXEDvyYrjmRMZe/GYLIG9cmqmn/wUrWPO+PauGiIuG/D2dmfuUNvSTRcIe7UQLXrfP3yyfZPgqsH6pSnNEVopquQKy3KjzqepgriOJtbyY=" - -notifications: - email: - on_success: never diff --git a/rand/CHANGELOG.md b/rand/CHANGELOG.md deleted file mode 100644 index a2ae496..0000000 --- a/rand/CHANGELOG.md +++ /dev/null @@ -1,568 +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). - -A [separate changelog is kept for rand_core](rand_core/CHANGELOG.md). - -You may also find the [Upgrade Guide](https://rust-random.github.io/book/update.html) useful. - -## [Unreleased] -- Fix `no_std` behaviour, appropriately enable c2-chacha's `std` feature (#844) -- Add a `no_std` target to CI to continously evaluate `no_std` status (#844) -- `alloc` feature in `no_std` is available since Rust 1.36 (#856) - -## [0.7.0] - 2019-06-28 - -### Fixes -- Fix incorrect pointer usages revealed by Miri testing (#780, #781) -- Fix (tiny!) bias in `Uniform` for 8- and 16-bit ints (#809) - -### Crate -- Bumped MSRV (min supported Rust version) to 1.32.0 -- Updated to Rust Edition 2018 (#823, #824) -- Removed dependence on `rand_xorshift`, `rand_isaac`, `rand_jitter` crates (#759, #765) -- Remove dependency on `winapi` (#724) -- Removed all `build.rs` files (#824) -- Removed code already deprecated in version 0.6 (#757) -- Removed the serde1 feature (It's still available for backwards compatibility, but it does not do anything. #830) -- Many documentation changes - -### rand_core -- Updated to `rand_core` 0.5.0 -- `Error` type redesigned with new API (#800) -- Move `from_entropy` method to `SeedableRng` and remove `FromEntropy` (#800) -- `SeedableRng::from_rng` is now expected to be value-stable (#815) - -### Standard RNGs -- OS interface moved from `rand_os` to new `getrandom` crate (#765, [getrandom](https://github.com/rust-random/getrandom)) -- Use ChaCha for `StdRng` and `ThreadRng` (#792) -- Feature-gate `SmallRng` (#792) -- `ThreadRng` now supports `Copy` (#758) -- Deprecated `EntropyRng` (#765) -- Enable fork protection of ReseedingRng without `std` (#724) - -### Distributions -- Many distributions have been moved to `rand_distr` (#761) -- `Bernoulli::new` constructor now returns a `Result` (#803) -- `Distribution::sample_iter` adjusted for more flexibility (#758) -- Added `distributions::weighted::alias_method::WeightedIndex` for `O(1)` sampling (#692) -- Support sampling `NonZeroU*` types with the `Standard` distribution (#728) -- Optimised `Binomial` distribution sampling (#735, #740, #752) -- Optimised SIMD float sampling (#739) - -### Sequences -- Make results portable across 32- and 64-bit by using `u32` samples for `usize` where possible (#809) - -## [0.6.5] - 2019-01-28 -### Crates -- Update `rand_core` to 0.4 (#703) -- Move `JitterRng` to its own crate (#685) -- Add a wasm-bindgen test crate (#696) - -### Platforms -- Fuchsia: Replaced fuchsia-zircon with fuchsia-cprng - -### Doc -- Use RFC 1946 for doc links (#691) -- Fix some doc links and notes (#711) - -## [0.6.4] - 2019-01-08 -### Fixes -- Move wasm-bindgen shims to correct crate (#686) -- Make `wasm32-unknown-unknown` compile but fail at run-time if missing bindingsg (#686) - -## [0.6.3] - 2019-01-04 -### Fixes -- Make the `std` feature require the optional `rand_os` dependency (#675) -- Re-export the optional WASM dependencies of `rand_os` from `rand` to avoid breakage (#674) - -## [0.6.2] - 2019-01-04 -### Additions -- Add `Default` for `ThreadRng` (#657) -- Move `rngs::OsRng` to `rand_os` sub-crate; clean up code; use as dependency (#643) ##BLOCKER## -- Add `rand_xoshiro` sub-crate, plus benchmarks (#642, #668) - -### Fixes -- Fix bias in `UniformInt::sample_single` (#662) -- Use `autocfg` instead of `rustc_version` for rustc version detection (#664) -- Disable `i128` and `u128` if the `target_os` is `emscripten` (#671: work-around Emscripten limitation) -- CI fixes (#660, #671) - -### Optimisations -- Optimise memory usage of `UnitCircle` and `UnitSphereSurface` distributions (no PR) - -## [0.6.1] - 2018-11-22 -- Support sampling `Duration` also for `no_std` (only since Rust 1.25) (#649) -- Disable default features of `libc` (#647) - -## [0.6.0] - 2018-11-14 - -### Project organisation -- Rand has moved from [rust-lang-nursery](https://github.com/rust-lang-nursery/rand) - to [rust-random](https://github.com/rust-random/rand)! (#578) -- Created [The Rust Random Book](https://rust-random.github.io/book/) - ([source](https://github.com/rust-random/book)) -- Update copyright and licence notices (#591, #611) -- Migrate policy documentation from the wiki (#544) - -### Platforms -- Add fork protection on Unix (#466) -- Added support for wasm-bindgen. (#541, #559, #562, #600) -- Enable `OsRng` for powerpc64, sparc and sparc64 (#609) -- Use `syscall` from `libc` on Linux instead of redefining it (#629) - -### RNGs -- Switch `SmallRng` to use PCG (#623) -- Implement `Pcg32` and `Pcg64Mcg` generators (#632) -- Move ISAAC RNGs to a dedicated crate (#551) -- Move Xorshift RNG to its own crate (#557) -- Move ChaCha and HC128 RNGs to dedicated crates (#607, #636) -- Remove usage of `Rc` from `ThreadRng` (#615) - -### Sampling and distributions -- Implement `Rng.gen_ratio()` and `Bernoulli::new_ratio()` (#491) -- Make `Uniform` strictly respect `f32` / `f64` high/low bounds (#477) -- Allow `gen_range` and `Uniform` to work on non-`Copy` types (#506) -- `Uniform` supports inclusive ranges: `Uniform::from(a..=b)`. This is - automatically enabled for Rust >= 1.27. (#566) -- Implement `TrustedLen` and `FusedIterator` for `DistIter` (#620) - -#### New distributions -- Add the `Dirichlet` distribution (#485) -- Added sampling from the unit sphere and circle. (#567) -- Implement the triangular distribution (#575) -- Implement the Weibull distribution (#576) -- Implement the Beta distribution (#574) - -#### Optimisations - -- Optimise `Bernoulli::new` (#500) -- Optimise `char` sampling (#519) -- Optimise sampling of `std::time::Duration` (#583) - -### Sequences -- Redesign the `seq` module (#483, #515) -- Add `WeightedIndex` and `choose_weighted` (#518, #547) -- Optimised and changed return type of the `sample_indices` function. (#479) -- Use `Iterator::size_hint()` to speed up `IteratorRandom::choose` (#593) - -### SIMD -- Support for generating SIMD types (#523, #542, #561, #630) - -### Other -- Revise CI scripts (#632, #635) -- Remove functionality already deprecated in 0.5 (#499) -- Support for `i128` and `u128` is automatically enabled for Rust >= 1.26. This - renders the `i128_support` feature obsolete. It still exists for backwards - compatibility but does not have any effect. This breaks programs using Rand - with `i128_support` on nightlies older than Rust 1.26. (#571) - - -## [0.5.5] - 2018-08-07 -### Documentation -- Fix links in documentation (#582) - - -## [0.5.4] - 2018-07-11 -### Platform support -- Make `OsRng` work via WASM/stdweb for WebWorkers - - -## [0.5.3] - 2018-06-26 -### Platform support -- OpenBSD, Bitrig: fix compilation (broken in 0.5.1) (#530) - - -## [0.5.2] - 2018-06-18 -### Platform support -- Hide `OsRng` and `JitterRng` on unsupported platforms (#512; fixes #503). - - -## [0.5.1] - 2018-06-08 - -### New distributions -- Added Cauchy distribution. (#474, #486) -- Added Pareto distribution. (#495) - -### Platform support and `OsRng` -- Remove blanket Unix implementation. (#484) -- Remove Wasm unimplemented stub. (#484) -- Dragonfly BSD: read from `/dev/random`. (#484) -- Bitrig: use `getentropy` like OpenBSD. (#484) -- Solaris: (untested) use `getrandom` if available, otherwise `/dev/random`. (#484) -- Emscripten, `stdweb`: split the read up in chunks. (#484) -- Emscripten, Haiku: don't do an extra blocking read from `/dev/random`. (#484) -- Linux, NetBSD, Solaris: read in blocking mode on first use in `fill_bytes`. (#484) -- Fuchsia, CloudABI: fix compilation (broken in Rand 0.5). (#484) - - -## [0.5.0] - 2018-05-21 - -### Crate features and organisation -- Minimum Rust version update: 1.22.0. (#239) -- Create a separate `rand_core` crate. (#288) -- Deprecate `rand_derive`. (#256) -- Add `prelude` (and module reorganisation). (#435) -- Add `log` feature. Logging is now available in `JitterRng`, `OsRng`, `EntropyRng` and `ReseedingRng`. (#246) -- Add `serde1` feature for some PRNGs. (#189) -- `stdweb` feature for `OsRng` support on WASM via stdweb. (#272, #336) - -### `Rng` trait -- Split `Rng` in `RngCore` and `Rng` extension trait. - `next_u32`, `next_u64` and `fill_bytes` are now part of `RngCore`. (#265) -- Add `Rng::sample`. (#256) -- Deprecate `Rng::gen_weighted_bool`. (#308) -- Add `Rng::gen_bool`. (#308) -- Remove `Rng::next_f32` and `Rng::next_f64`. (#273) -- Add optimized `Rng::fill` and `Rng::try_fill` methods. (#247) -- Deprecate `Rng::gen_iter`. (#286) -- Deprecate `Rng::gen_ascii_chars`. (#279) - -### `rand_core` crate -- `rand` now depends on new `rand_core` crate (#288) -- `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) -- Revise the `SeedableRng` trait. (#233) -- Remove default implementations for `RngCore::next_u64` and `RngCore::fill_bytes`. (#288) -- Add `RngCore::try_fill_bytes`. (#225) - -### Other traits and types -- Add `FromEntropy` trait. (#233, #375) -- Add `SmallRng` wrapper. (#296) -- Rewrite `ReseedingRng` to only work with `BlockRngCore` (substantial performance improvement). (#281) -- Deprecate `weak_rng`. Use `SmallRng` instead. (#296) -- Deprecate `AsciiGenerator`. (#279) - -### Random number generators -- Switch `StdRng` and `thread_rng` to HC-128. (#277) -- `StdRng` must now be created with `from_entropy` instead of `new` -- Change `thread_rng` reseeding threshold to 32 MiB. (#277) -- PRNGs no longer implement `Copy`. (#209) -- `Debug` implementations no longer show internals. (#209) -- Implement `Clone` for `ReseedingRng`, `JitterRng`, OsRng`. (#383, #384) -- Implement serialization for `XorShiftRng`, `IsaacRng` and `Isaac64Rng` under the `serde1` feature. (#189) -- Implement `BlockRngCore` for `ChaChaCore` and `Hc128Core`. (#281) -- All PRNGs are now portable across big- and little-endian architectures. (#209) -- `Isaac64Rng::next_u32` no longer throws away half the results. (#209) -- Add `IsaacRng::new_from_u64` and `Isaac64Rng::new_from_u64`. (#209) -- Add the HC-128 CSPRNG `Hc128Rng`. (#210) -- Change ChaCha20 to have 64-bit counter and 64-bit stream. (#349) -- Changes to `JitterRng` to get its size down from 2112 to 24 bytes. (#251) -- Various performance improvements to all PRNGs. - -### Platform support and `OsRng` -- Add support for CloudABI. (#224) -- Remove support for NaCl. (#225) -- WASM support for `OsRng` via stdweb, behind the `stdweb` feature. (#272, #336) -- Use `getrandom` on more platforms for Linux, and on Android. (#338) -- Use the `SecRandomCopyBytes` interface on macOS. (#322) -- On systems that do not have a syscall interface, only keep a single file descriptor open for `OsRng`. (#239) -- On Unix, first try a single read from `/dev/random`, then `/dev/urandom`. (#338) -- Better error handling and reporting in `OsRng` (using new error type). (#225) -- `OsRng` now uses non-blocking when available. (#225) -- Add `EntropyRng`, which provides `OsRng`, but has `JitterRng` as a fallback. (#235) - -### Distributions -- New `Distribution` trait. (#256) -- Add `Distribution::sample_iter` and `Rng::::sample_iter`. (#361) -- Deprecate `Rand`, `Sample` and `IndependentSample` traits. (#256) -- Add a `Standard` distribution (replaces most `Rand` implementations). (#256) -- Add `Binomial` and `Poisson` distributions. (#96) -- Add `Bernoulli` dsitribution. (#411) -- Add `Alphanumeric` distribution. (#279) -- Remove `Closed01` distribution, add `OpenClosed01`. (#274, #420) -- Rework `Range` type, making it possible to implement it for user types. (#274) -- Rename `Range` to `Uniform`. (#395) -- Add `Uniform::new_inclusive` for inclusive ranges. (#274) -- Use widening multiply method for much faster integer range reduction. (#274) -- `Standard` distribution for `char` uses `Uniform` internally. (#274) -- `Standard` distribution for `bool` uses sign test. (#274) -- Implement `Standard` distribution for `Wrapping`. (#436) -- Implement `Uniform` distribution for `Duration`. (#427) - - -## [0.4.3] - 2018-08-16 -### Fixed -- Use correct syscall number for PowerPC (#589) - - -## [0.4.2] - 2018-01-06 -### Changed -- Use `winapi` on Windows -- Update for Fuchsia OS -- Remove dev-dependency on `log` - - -## [0.4.1] - 2017-12-17 -### Added -- `no_std` support - - -## [0.4.0-pre.0] - 2017-12-11 -### Added -- `JitterRng` added as a high-quality alternative entropy source using the - system timer -- new `seq` module with `sample_iter`, `sample_slice`, etc. -- WASM support via dummy implementations (fail at run-time) -- Additional benchmarks, covering generators and new seq code - -### Changed -- `thread_rng` uses `JitterRng` if seeding from system time fails - (slower but more secure than previous method) - -### Deprecated - - `sample` function deprecated (replaced by `sample_iter`) - - -## [0.3.20] - 2018-01-06 -### Changed -- Remove dev-dependency on `log` -- Update `fuchsia-zircon` dependency to 0.3.2 - - -## [0.3.19] - 2017-12-27 -### Changed -- Require `log <= 0.3.8` for dev builds -- Update `fuchsia-zircon` dependency to 0.3 -- Fix broken links in docs (to unblock compiler docs testing CI) - - -## [0.3.18] - 2017-11-06 -### Changed -- `thread_rng` is seeded from the system time if `OsRng` fails -- `weak_rng` now uses `thread_rng` internally - - -## [0.3.17] - 2017-10-07 -### Changed - - Fuchsia: Magenta was renamed Zircon - -## [0.3.16] - 2017-07-27 -### Added -- Implement Debug for mote non-public types -- implement `Rand` for (i|u)i128 -- Support for Fuchsia - -### Changed -- Add inline attribute to SampleRange::construct_range. - This improves the benchmark for sample in 11% and for shuffle in 16%. -- Use `RtlGenRandom` instead of `CryptGenRandom` - - -## [0.3.15] - 2016-11-26 -### Added -- Add `Rng` trait method `choose_mut` -- Redox support - -### Changed -- Use `arc4rand` for `OsRng` on FreeBSD. -- Use `arc4random(3)` for `OsRng` on OpenBSD. - -### Fixed -- Fix filling buffers 4 GiB or larger with `OsRng::fill_bytes` on Windows - - -## [0.3.14] - 2016-02-13 -### Fixed -- Inline definitions from winapi/advapi32, wich decreases build times - - -## [0.3.13] - 2016-01-09 -### Fixed -- Compatible with Rust 1.7.0-nightly (needed some extra type annotations) - - -## [0.3.12] - 2015-11-09 -### Changed -- Replaced the methods in `next_f32` and `next_f64` with the technique described - Saito & Matsumoto at MCQMC'08. The new method should exhibit a slightly more - uniform distribution. -- Depend on libc 0.2 - -### Fixed -- Fix iterator protocol issue in `rand::sample` - - -## [0.3.11] - 2015-08-31 -### Added -- Implement `Rand` for arrays with n <= 32 - - -## [0.3.10] - 2015-08-17 -### Added -- Support for NaCl platforms - -### Changed -- Allow `Rng` to be `?Sized`, impl for `&mut R` and `Box` where `R: ?Sized + Rng` - - -## [0.3.9] - 2015-06-18 -### Changed -- Use `winapi` for Windows API things - -### Fixed -- Fixed test on stable/nightly -- Fix `getrandom` syscall number for aarch64-unknown-linux-gnu - - -## [0.3.8] - 2015-04-23 -### Changed -- `log` is a dev dependency - -### Fixed -- Fix race condition of atomics in `is_getrandom_available` - - -## [0.3.7] - 2015-04-03 -### Fixed -- Derive Copy/Clone changes - - -## [0.3.6] - 2015-04-02 -### Changed -- Move to stable Rust! - - -## [0.3.5] - 2015-04-01 -### Fixed -- Compatible with Rust master - - -## [0.3.4] - 2015-03-31 -### Added -- Implement Clone for `Weighted` - -### Fixed -- Compatible with Rust master - - -## [0.3.3] - 2015-03-26 -### Fixed -- Fix compile on Windows - - -## [0.3.2] - 2015-03-26 - - -## [0.3.1] - 2015-03-26 -### Fixed -- Fix compile on Windows - - -## [0.3.0] - 2015-03-25 -### Changed -- Update to use log version 0.3.x - - -## [0.2.1] - 2015-03-22 -### Fixed -- Compatible with Rust master -- Fixed iOS compilation - - -## [0.2.0] - 2015-03-06 -### Fixed -- Compatible with Rust master (move from `old_io` to `std::io`) - - -## [0.1.4] - 2015-03-04 -### Fixed -- Compatible with Rust master (use wrapping ops) - - -## [0.1.3] - 2015-02-20 -### Fixed -- Compatible with Rust master - -### Removed -- Removed Copy implementations from RNGs - - -## [0.1.2] - 2015-02-03 -### Added -- Imported functionality from `std::rand`, including: - - `StdRng`, `SeedableRng`, `TreadRng`, `weak_rng()` - - `ReaderRng`: A wrapper around any Reader to treat it as an RNG. -- Imported documentation from `std::rand` -- Imported tests from `std::rand` - - -## [0.1.1] - 2015-02-03 -### Added -- Migrate to a cargo-compatible directory structure. - -### Fixed -- Do not use entropy during `gen_weighted_bool(1)` - - -## [Rust 0.12.0] - 2014-10-09 -### Added -- Impl Rand for tuples of arity 11 and 12 -- Include ChaCha pseudorandom generator -- Add `next_f64` and `next_f32` to Rng -- Implement Clone for PRNGs - -### Changed -- Rename `TaskRng` to `ThreadRng` and `task_rng` to `thread_rng` (since a - runtime is removed from Rust). - -### Fixed -- Improved performance of ISAAC and ISAAC64 by 30% and 12 % respectively, by - informing the optimiser that indexing is never out-of-bounds. - -### Removed -- Removed the Deprecated `choose_option` - - -## [Rust 0.11.0] - 2014-07-02 -### Added -- document when to use `OSRng` in cryptographic context, and explain why we use `/dev/urandom` instead of `/dev/random` -- `Rng::gen_iter()` which will return an infinite stream of random values -- `Rng::gen_ascii_chars()` which will return an infinite stream of random ascii characters - -### Changed -- Now only depends on libcore! -- Remove `Rng.choose()`, rename `Rng.choose_option()` to `.choose()` -- Rename OSRng to OsRng -- The WeightedChoice structure is no longer built with a `Vec>`, - but rather a `&mut [Weighted]`. This means that the WeightedChoice - structure now has a lifetime associated with it. -- The `sample` method on `Rng` has been moved to a top-level function in the - `rand` module due to its dependence on `Vec`. - -### Removed -- `Rng::gen_vec()` was removed. Previous behavior can be regained with - `rng.gen_iter().take(n).collect()` -- `Rng::gen_ascii_str()` was removed. Previous behavior can be regained with - `rng.gen_ascii_chars().take(n).collect()` -- {IsaacRng, Isaac64Rng, XorShiftRng}::new() have all been removed. These all - relied on being able to use an OSRng for seeding, but this is no longer - available in librand (where these types are defined). To retain the same - functionality, these types now implement the `Rand` trait so they can be - generated with a random seed from another random number generator. This allows - the stdlib to use an OSRng to create seeded instances of these RNGs. -- Rand implementations for `Box` and `@T` were removed. These seemed to be - pretty rare in the codebase, and it allows for librand to not depend on - liballoc. Additionally, other pointer types like Rc and Arc were not - supported. -- Remove a slew of old deprecated functions - - -## [Rust 0.10] - 2014-04-03 -### Changed -- replace `Rng.shuffle's` functionality with `.shuffle_mut` -- bubble up IO errors when creating an OSRng - -### Fixed -- Use `fill()` instead of `read()` -- Rewrite OsRng in Rust for windows - -## [0.10-pre] - 2014-03-02 -### Added -- Seperate `rand` out of the standard library diff --git a/rand/COPYRIGHT b/rand/COPYRIGHT deleted file mode 100644 index 468d907..0000000 --- a/rand/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 or - or the MIT license - or , at your option. - -The Rand project includes code from the Rust project -published under these same licenses. diff --git a/rand/Cargo.toml b/rand/Cargo.toml deleted file mode 100644 index ef344a6..0000000 --- a/rand/Cargo.toml +++ /dev/null @@ -1,90 +0,0 @@ -[package] -name = "rand" -version = "0.7.0" -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/" -homepage = "https://crates.io/crates/rand" -description = """ -Random number generators and other randomness functionality. -""" -keywords = ["random", "rng"] -categories = ["algorithms", "no-std"] -exclude = ["/utils/*", "/.travis.yml", "/appveyor.yml", ".gitignore"] -autobenches = true -edition = "2018" - -[badges] -travis-ci = { repository = "rust-random/rand" } -appveyor = { repository = "rust-random/rand" } - -[features] -# Meta-features: -default = ["std"] # without "std" rand uses libcore -nightly = ["simd_support"] # enables all features requiring nightly rust -serde1 = [] # does nothing, deprecated - -# Optional dependencies: -std = ["rand_core/std", "rand_chacha/std", "alloc", "getrandom"] -alloc = ["rand_core/alloc"] # enables Vec and Box support (without std) -# re-export optional WASM dependencies to avoid breakage: -wasm-bindgen = ["getrandom_package/wasm-bindgen"] -stdweb = ["getrandom_package/stdweb"] -getrandom = ["getrandom_package", "rand_core/getrandom"] - -# Configuration: -simd_support = ["packed_simd"] # enables SIMD support -small_rng = ["rand_pcg"] # enables SmallRng - -[workspace] -members = [ - "rand_core", - "rand_distr", - "rand_jitter", - "rand_os", - "rand_isaac", - "rand_chacha", - "rand_hc", - "rand_pcg", - "rand_xorshift", - "rand_xoshiro", - "tests/wasm_bindgen", -] - -[dependencies] -rand_core = { path = "rand_core", version = "0.5" } -rand_pcg = { path = "rand_pcg", version = "0.2", optional = true } -# Do not depend on 'getrandom_package' directly; use the 'getrandom' feature! -getrandom_package = { version = "0.1.1", package = "getrandom", optional = true } -log = { version = "0.4", optional = true } - -[dependencies.packed_simd] -# NOTE: so far no version works reliably due to dependence on unstable features -version = "0.3" -# git = "https://github.com/rust-lang-nursery/packed_simd" -optional = true -features = ["into_bits"] - -[target.'cfg(unix)'.dependencies] -# Used for fork protection (reseeding.rs) -libc = { version = "0.2.22", default-features = false } - -# Emscripten does not support 128-bit integers, which are used by ChaCha code. -# We work around this by using a different RNG. -[target.'cfg(not(target_os = "emscripten"))'.dependencies] -rand_chacha = { path = "rand_chacha", version = "0.2.1", default-features = false } -[target.'cfg(target_os = "emscripten")'.dependencies] -rand_hc = { path = "rand_hc", version = "0.2" } - -[dev-dependencies] -rand_pcg = { path = "rand_pcg", version = "0.2" } -# Only for benches: -rand_hc = { path = "rand_hc", version = "0.2" } -rand_xoshiro = { path = "rand_xoshiro", version = "0.3" } -rand_isaac = { path = "rand_isaac", version = "0.2" } -rand_xorshift = { path = "rand_xorshift", version = "0.2" } - -[package.metadata.docs.rs] -all-features = true diff --git a/rand/LICENSE-APACHE b/rand/LICENSE-APACHE deleted file mode 100644 index 17d7468..0000000 --- a/rand/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/LICENSE-MIT b/rand/LICENSE-MIT deleted file mode 100644 index d93b5ba..0000000 --- a/rand/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/README.md b/rand/README.md deleted file mode 100644 index 5acbadb..0000000 --- a/rand/README.md +++ /dev/null @@ -1,118 +0,0 @@ -# Rand - -[![Build Status](https://travis-ci.org/rust-random/rand.svg?branch=master)](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) -[![Crate](https://img.shields.io/crates/v/rand.svg)](https://crates.io/crates/rand) -[![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) -[![API](https://docs.rs/rand/badge.svg)](https://docs.rs/rand) -[![Minimum rustc version](https://img.shields.io/badge/rustc-1.32+-lightgray.svg)](https://github.com/rust-random/rand#rust-version-requirements) - -A Rust library for random number generation. - -Rand provides utilities to generate random numbers, to convert them to useful -types and distributions, and some randomness-related algorithms. - -The core random number generation traits of Rand live in the [rand_core]( -https://crates.io/crates/rand_core) crate but are also exposed here; RNG -implementations should prefer to use `rand_core` while most other users should -depend on `rand`. - -Documentation: -- [The Rust Rand Book](https://rust-random.github.io/book) -- [API reference (master)](https://rust-random.github.io/rand) -- [API reference (docs.rs)](https://docs.rs/rand) - - -## Usage - -Add this to your `Cargo.toml`: - -```toml -[dependencies] -rand = "0.7" -``` - -To get started using Rand, see [The Book](https://rust-random.github.io/book). - - -## Versions - -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. - -The Rand lib is not yet stable, however we are careful to limit breaking changes -and warn via deprecation wherever possible. Patch versions never introduce -breaking changes. The following minor versions are supported: - -- Version 0.7 was released in June 2019, moving most non-uniform distributions - to an external crate, moving `from_entropy` to `SeedableRng`, and many small - changes and fixes. -- Version 0.6 was released in November 2018, redesigning the `seq` module, - moving most PRNGs to external crates, and many small changes. -- Version 0.5 was released in May 2018, as a major reorganisation - (introducing `RngCore` and `rand_core`, and deprecating `Rand` and the - previous distribution traits). -- Version 0.4 was released in December 2017, but contained almost no breaking - changes from the 0.3 series. - -A detailed [changelog](CHANGELOG.md) is available. - -When upgrading to the next minor series (especially 0.4 β†’ 0.5), we recommend -reading the [Upgrade Guide](https://rust-random.github.io/book/update.html). - -### Rust version requirements - -Since version 0.7, Rand requires **Rustc version 1.32 or greater**. -Rand 0.5 requires Rustc 1.22 or greater while versions -0.4 and 0.3 (since approx. June 2017) require Rustc version 1.15 or -greater. Subsets of the Rand code may work with older Rust versions, but this -is not supported. - -Travis CI always has a build with a pinned version of Rustc matching the oldest -supported Rust release. The current policy is that this can be updated in any -Rand release if required, but the change must be noted in the changelog. - -## Crate Features - -Rand is built with these features enabled by default: - -- `std` enables functionality dependent on the `std` lib -- `alloc` (implied by `std`) enables functionality requiring an allocator (when using this feature in `no_std`, Rand requires Rustc version 1.36 or greater) -- `getrandom` (implied by `std`) is an optional dependency providing the code - behind `rngs::OsRng` - -Optionally, the following dependencies can be enabled: - -- `log` enables logging via the `log` crate -- `stdweb` implies `getrandom/stdweb` to enable - `getrandom` support on `wasm32-unknown-unknown` -- `wasm-bindgen` implies `getrandom/wasm-bindgen` to enable - `getrandom` support on `wasm32-unknown-unknown` - -Additionally, these features configure Rand: - -- `small_rng` enables inclusion of the `SmallRng` PRNG -- `nightly` enables all experimental features -- `simd_support` (experimental) enables sampling of SIMD values - (uniformly random SIMD integers and floats) - -Rand supports limited functionality in `no_std` mode (enabled via -`default-features = false`). In this case, `OsRng` and `from_entropy` are -unavailable (unless `getrandom` is enabled), large parts of `seq` are -unavailable (unless `alloc` is enabled), and `thread_rng` and `random` are -unavailable. - -# License - -Rand 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/appveyor.yml b/rand/appveyor.yml deleted file mode 100644 index ef0b4bf..0000000 --- a/rand/appveyor.yml +++ /dev/null @@ -1,49 +0,0 @@ -environment: - - # At the time this was added AppVeyor was having troubles with checking - # revocation of SSL certificates of sites like static.rust-lang.org and what - # we think is crates.io. The libcurl HTTP client by default checks for - # revocation on Windows and according to a mailing list [1] this can be - # disabled. - # - # The `CARGO_HTTP_CHECK_REVOKE` env var here tells cargo to disable SSL - # revocation checking on Windows in libcurl. Note, though, that rustup, which - # we're using to download Rust here, also uses libcurl as the default backend. - # Unlike Cargo, however, rustup doesn't have a mechanism to disable revocation - # checking. To get rustup working we set `RUSTUP_USE_HYPER` which forces it to - # use the Hyper instead of libcurl backend. Both Hyper and libcurl use - # schannel on Windows but it appears that Hyper configures it slightly - # differently such that revocation checking isn't turned on by default. - # - # [1]: https://curl.haxx.se/mail/lib-2016-03/0202.html - RUSTUP_USE_HYPER: 1 - CARGO_HTTP_CHECK_REVOKE: false - - matrix: - - TARGET: x86_64-pc-windows-msvc - - TARGET: i686-pc-windows-msvc -install: - - appveyor DownloadFile https://win.rustup.rs/ -FileName rustup-init.exe - - rustup-init.exe -y --default-host %TARGET% --default-toolchain nightly - - set PATH=%PATH%;C:\Users\appveyor\.cargo\bin - - rustc -V - - cargo -V - -build: false - -test_script: - - cargo test --tests --no-default-features --features alloc - # TODO: use --all-features once simd_support is sufficiently stable: - - cargo test --features=serde1,log - - cargo test --benches --features=nightly - - cargo test --examples - - cargo test --manifest-path rand_core/Cargo.toml - - cargo test --manifest-path rand_core/Cargo.toml --no-default-features --features=alloc - - cargo test --manifest-path rand_distr/Cargo.toml - - cargo test --manifest-path rand_isaac/Cargo.toml --features=serde1 - - cargo test --manifest-path rand_pcg/Cargo.toml --features=serde1 - - cargo test --manifest-path rand_xorshift/Cargo.toml --features=serde1 - - cargo test --manifest-path rand_xoshiro/Cargo.toml - - cargo test --manifest-path rand_chacha/Cargo.toml - - cargo test --manifest-path rand_hc/Cargo.toml - - cargo test --manifest-path rand_os/Cargo.toml diff --git a/rand/benches/generators.rs b/rand/benches/generators.rs deleted file mode 100644 index 808bb67..0000000 --- a/rand/benches/generators.rs +++ /dev/null @@ -1,220 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#![feature(test)] -#![allow(non_snake_case)] - -extern crate test; - -const RAND_BENCH_N: u64 = 1000; -const BYTES_LEN: usize = 1024; - -use std::mem::size_of; -use test::{black_box, Bencher}; - -use rand::prelude::*; -use rand::rngs::adapter::ReseedingRng; -use rand::rngs::{OsRng, mock::StepRng}; -use rand_isaac::{IsaacRng, Isaac64Rng}; -use rand_chacha::{ChaCha20Core, ChaCha8Rng, ChaCha12Rng, ChaCha20Rng}; -use rand_hc::{Hc128Rng}; -use rand_pcg::{Pcg32, Pcg64, Pcg64Mcg}; -use rand_xorshift::XorShiftRng; -use rand_xoshiro::{Xoshiro256StarStar, Xoshiro256Plus, Xoshiro128StarStar, - Xoshiro128Plus, Xoroshiro128StarStar, Xoroshiro128Plus, SplitMix64, - Xoroshiro64StarStar, Xoroshiro64Star}; - -macro_rules! gen_bytes { - ($fnn:ident, $gen:expr) => { - #[bench] - fn $fnn(b: &mut Bencher) { - let mut rng = $gen; - let mut buf = [0u8; BYTES_LEN]; - b.iter(|| { - for _ in 0..RAND_BENCH_N { - rng.fill_bytes(&mut buf); - black_box(buf); - } - }); - b.bytes = BYTES_LEN as u64 * RAND_BENCH_N; - } - } -} - -gen_bytes!(gen_bytes_step, StepRng::new(0, 1)); -gen_bytes!(gen_bytes_xorshift, XorShiftRng::from_entropy()); -gen_bytes!(gen_bytes_xoshiro256starstar, Xoshiro256StarStar::from_entropy()); -gen_bytes!(gen_bytes_xoshiro256plus, Xoshiro256Plus::from_entropy()); -gen_bytes!(gen_bytes_xoshiro128starstar, Xoshiro128StarStar::from_entropy()); -gen_bytes!(gen_bytes_xoshiro128plus, Xoshiro128Plus::from_entropy()); -gen_bytes!(gen_bytes_xoroshiro128starstar, Xoroshiro128StarStar::from_entropy()); -gen_bytes!(gen_bytes_xoroshiro128plus, Xoroshiro128Plus::from_entropy()); -gen_bytes!(gen_bytes_xoroshiro64starstar, Xoroshiro64StarStar::from_entropy()); -gen_bytes!(gen_bytes_xoroshiro64star, Xoroshiro64Star::from_entropy()); -gen_bytes!(gen_bytes_splitmix64, SplitMix64::from_entropy()); -gen_bytes!(gen_bytes_pcg32, Pcg32::from_entropy()); -gen_bytes!(gen_bytes_pcg64, Pcg64::from_entropy()); -gen_bytes!(gen_bytes_pcg64mcg, Pcg64Mcg::from_entropy()); -gen_bytes!(gen_bytes_chacha8, ChaCha8Rng::from_entropy()); -gen_bytes!(gen_bytes_chacha12, ChaCha12Rng::from_entropy()); -gen_bytes!(gen_bytes_chacha20, ChaCha20Rng::from_entropy()); -gen_bytes!(gen_bytes_hc128, Hc128Rng::from_entropy()); -gen_bytes!(gen_bytes_isaac, IsaacRng::from_entropy()); -gen_bytes!(gen_bytes_isaac64, Isaac64Rng::from_entropy()); -gen_bytes!(gen_bytes_std, StdRng::from_entropy()); -#[cfg(feature="small_rng")] -gen_bytes!(gen_bytes_small, SmallRng::from_entropy()); -gen_bytes!(gen_bytes_os, OsRng); - -macro_rules! gen_uint { - ($fnn:ident, $ty:ty, $gen:expr) => { - #[bench] - fn $fnn(b: &mut Bencher) { - let mut rng = $gen; - b.iter(|| { - let mut accum: $ty = 0; - for _ in 0..RAND_BENCH_N { - accum = accum.wrapping_add(rng.gen::<$ty>()); - } - accum - }); - b.bytes = size_of::<$ty>() as u64 * RAND_BENCH_N; - } - } -} - -gen_uint!(gen_u32_step, u32, StepRng::new(0, 1)); -gen_uint!(gen_u32_xorshift, u32, XorShiftRng::from_entropy()); -gen_uint!(gen_u32_xoshiro256starstar, u32, Xoshiro256StarStar::from_entropy()); -gen_uint!(gen_u32_xoshiro256plus, u32, Xoshiro256Plus::from_entropy()); -gen_uint!(gen_u32_xoshiro128starstar, u32, Xoshiro128StarStar::from_entropy()); -gen_uint!(gen_u32_xoshiro128plus, u32, Xoshiro128Plus::from_entropy()); -gen_uint!(gen_u32_xoroshiro128starstar, u32, Xoroshiro128StarStar::from_entropy()); -gen_uint!(gen_u32_xoroshiro128plus, u32, Xoroshiro128Plus::from_entropy()); -gen_uint!(gen_u32_xoroshiro64starstar, u32, Xoroshiro64StarStar::from_entropy()); -gen_uint!(gen_u32_xoroshiro64star, u32, Xoroshiro64Star::from_entropy()); -gen_uint!(gen_u32_splitmix64, u32, SplitMix64::from_entropy()); -gen_uint!(gen_u32_pcg32, u32, Pcg32::from_entropy()); -gen_uint!(gen_u32_pcg64, u32, Pcg64::from_entropy()); -gen_uint!(gen_u32_pcg64mcg, u32, Pcg64Mcg::from_entropy()); -gen_uint!(gen_u32_chacha8, u32, ChaCha8Rng::from_entropy()); -gen_uint!(gen_u32_chacha12, u32, ChaCha12Rng::from_entropy()); -gen_uint!(gen_u32_chacha20, u32, ChaCha20Rng::from_entropy()); -gen_uint!(gen_u32_hc128, u32, Hc128Rng::from_entropy()); -gen_uint!(gen_u32_isaac, u32, IsaacRng::from_entropy()); -gen_uint!(gen_u32_isaac64, u32, Isaac64Rng::from_entropy()); -gen_uint!(gen_u32_std, u32, StdRng::from_entropy()); -#[cfg(feature="small_rng")] -gen_uint!(gen_u32_small, u32, SmallRng::from_entropy()); -gen_uint!(gen_u32_os, u32, OsRng); - -gen_uint!(gen_u64_step, u64, StepRng::new(0, 1)); -gen_uint!(gen_u64_xorshift, u64, XorShiftRng::from_entropy()); -gen_uint!(gen_u64_xoshiro256starstar, u64, Xoshiro256StarStar::from_entropy()); -gen_uint!(gen_u64_xoshiro256plus, u64, Xoshiro256Plus::from_entropy()); -gen_uint!(gen_u64_xoshiro128starstar, u64, Xoshiro128StarStar::from_entropy()); -gen_uint!(gen_u64_xoshiro128plus, u64, Xoshiro128Plus::from_entropy()); -gen_uint!(gen_u64_xoroshiro128starstar, u64, Xoroshiro128StarStar::from_entropy()); -gen_uint!(gen_u64_xoroshiro128plus, u64, Xoroshiro128Plus::from_entropy()); -gen_uint!(gen_u64_xoroshiro64starstar, u64, Xoroshiro64StarStar::from_entropy()); -gen_uint!(gen_u64_xoroshiro64star, u64, Xoroshiro64Star::from_entropy()); -gen_uint!(gen_u64_splitmix64, u64, SplitMix64::from_entropy()); -gen_uint!(gen_u64_pcg32, u64, Pcg32::from_entropy()); -gen_uint!(gen_u64_pcg64, u64, Pcg64::from_entropy()); -gen_uint!(gen_u64_pcg64mcg, u64, Pcg64Mcg::from_entropy()); -gen_uint!(gen_u64_chacha8, u64, ChaCha8Rng::from_entropy()); -gen_uint!(gen_u64_chacha12, u64, ChaCha12Rng::from_entropy()); -gen_uint!(gen_u64_chacha20, u64, ChaCha20Rng::from_entropy()); -gen_uint!(gen_u64_hc128, u64, Hc128Rng::from_entropy()); -gen_uint!(gen_u64_isaac, u64, IsaacRng::from_entropy()); -gen_uint!(gen_u64_isaac64, u64, Isaac64Rng::from_entropy()); -gen_uint!(gen_u64_std, u64, StdRng::from_entropy()); -#[cfg(feature="small_rng")] -gen_uint!(gen_u64_small, u64, SmallRng::from_entropy()); -gen_uint!(gen_u64_os, u64, OsRng); - -macro_rules! init_gen { - ($fnn:ident, $gen:ident) => { - #[bench] - fn $fnn(b: &mut Bencher) { - let mut rng = XorShiftRng::from_entropy(); - b.iter(|| { - let r2 = $gen::from_rng(&mut rng).unwrap(); - r2 - }); - } - } -} - -init_gen!(init_xorshift, XorShiftRng); -init_gen!(init_xoshiro256starstar, Xoshiro256StarStar); -init_gen!(init_xoshiro256plus, Xoshiro256Plus); -init_gen!(init_xoshiro128starstar, Xoshiro128StarStar); -init_gen!(init_xoshiro128plus, Xoshiro128Plus); -init_gen!(init_xoroshiro128starstar, Xoroshiro128StarStar); -init_gen!(init_xoroshiro128plus, Xoroshiro128Plus); -init_gen!(init_xoroshiro64starstar, Xoroshiro64StarStar); -init_gen!(init_xoroshiro64star, Xoroshiro64Star); -init_gen!(init_splitmix64, SplitMix64); -init_gen!(init_pcg32, Pcg32); -init_gen!(init_pcg64, Pcg64); -init_gen!(init_pcg64mcg, Pcg64Mcg); -init_gen!(init_hc128, Hc128Rng); -init_gen!(init_isaac, IsaacRng); -init_gen!(init_isaac64, Isaac64Rng); -init_gen!(init_chacha, ChaCha20Rng); - -const RESEEDING_BYTES_LEN: usize = 1024 * 1024; -const RESEEDING_BENCH_N: u64 = 16; - -macro_rules! reseeding_bytes { - ($fnn:ident, $thresh:expr) => { - #[bench] - fn $fnn(b: &mut Bencher) { - let mut rng = ReseedingRng::new(ChaCha20Core::from_entropy(), - $thresh * 1024, - OsRng); - let mut buf = [0u8; RESEEDING_BYTES_LEN]; - b.iter(|| { - for _ in 0..RESEEDING_BENCH_N { - rng.fill_bytes(&mut buf); - black_box(&buf); - } - }); - b.bytes = RESEEDING_BYTES_LEN as u64 * RESEEDING_BENCH_N; - } - } -} - -reseeding_bytes!(reseeding_chacha20_4k, 4); -reseeding_bytes!(reseeding_chacha20_16k, 16); -reseeding_bytes!(reseeding_chacha20_32k, 32); -reseeding_bytes!(reseeding_chacha20_64k, 64); -reseeding_bytes!(reseeding_chacha20_256k, 256); -reseeding_bytes!(reseeding_chacha20_1M, 1024); - - -macro_rules! threadrng_uint { - ($fnn:ident, $ty:ty) => { - #[bench] - fn $fnn(b: &mut Bencher) { - let mut rng = thread_rng(); - b.iter(|| { - let mut accum: $ty = 0; - for _ in 0..RAND_BENCH_N { - accum = accum.wrapping_add(rng.gen::<$ty>()); - } - accum - }); - b.bytes = size_of::<$ty>() as u64 * RAND_BENCH_N; - } - } -} - -threadrng_uint!(thread_rng_u32, u32); -threadrng_uint!(thread_rng_u64, u64); diff --git a/rand/benches/misc.rs b/rand/benches/misc.rs deleted file mode 100644 index 4098686..0000000 --- a/rand/benches/misc.rs +++ /dev/null @@ -1,140 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#![feature(test)] - -extern crate test; - -const RAND_BENCH_N: u64 = 1000; - -use test::Bencher; - -use rand::prelude::*; -use rand::distributions::{Distribution, Standard, Bernoulli}; -use rand_pcg::{Pcg32, Pcg64Mcg}; - -#[bench] -fn misc_gen_bool_const(b: &mut Bencher) { - let mut rng = Pcg32::from_rng(&mut thread_rng()).unwrap(); - b.iter(|| { - let mut accum = true; - for _ in 0..crate::RAND_BENCH_N { - accum ^= rng.gen_bool(0.18); - } - accum - }) -} - -#[bench] -fn misc_gen_bool_var(b: &mut Bencher) { - let mut rng = Pcg32::from_rng(&mut thread_rng()).unwrap(); - b.iter(|| { - let mut accum = true; - let mut p = 0.18; - for _ in 0..crate::RAND_BENCH_N { - accum ^= rng.gen_bool(p); - p += 0.0001; - } - accum - }) -} - -#[bench] -fn misc_gen_ratio_const(b: &mut Bencher) { - let mut rng = Pcg32::from_rng(&mut thread_rng()).unwrap(); - b.iter(|| { - let mut accum = true; - for _ in 0..crate::RAND_BENCH_N { - accum ^= rng.gen_ratio(2, 3); - } - accum - }) -} - -#[bench] -fn misc_gen_ratio_var(b: &mut Bencher) { - let mut rng = Pcg32::from_rng(&mut thread_rng()).unwrap(); - b.iter(|| { - let mut accum = true; - for i in 2..(crate::RAND_BENCH_N as u32 + 2) { - accum ^= rng.gen_ratio(i, i + 1); - } - accum - }) -} - -#[bench] -fn misc_bernoulli_const(b: &mut Bencher) { - let mut rng = Pcg32::from_rng(&mut thread_rng()).unwrap(); - b.iter(|| { - let d = rand::distributions::Bernoulli::new(0.18).unwrap(); - let mut accum = true; - for _ in 0..crate::RAND_BENCH_N { - accum ^= rng.sample(d); - } - accum - }) -} - -#[bench] -fn misc_bernoulli_var(b: &mut Bencher) { - let mut rng = Pcg32::from_rng(&mut thread_rng()).unwrap(); - b.iter(|| { - let mut accum = true; - let mut p = 0.18; - for _ in 0..crate::RAND_BENCH_N { - let d = Bernoulli::new(p).unwrap(); - accum ^= rng.sample(d); - p += 0.0001; - } - accum - }) -} - -#[bench] -fn gen_1k_iter_repeat(b: &mut Bencher) { - use std::iter; - let mut rng = Pcg64Mcg::from_rng(&mut thread_rng()).unwrap(); - b.iter(|| { - let v: Vec = iter::repeat(()).map(|()| rng.gen()).take(128).collect(); - v - }); - b.bytes = 1024; -} - -#[bench] -fn gen_1k_sample_iter(b: &mut Bencher) { - let mut rng = Pcg64Mcg::from_rng(&mut thread_rng()).unwrap(); - b.iter(|| { - let v: Vec = Standard.sample_iter(&mut rng).take(128).collect(); - v - }); - b.bytes = 1024; -} - -#[bench] -fn gen_1k_gen_array(b: &mut Bencher) { - let mut rng = Pcg64Mcg::from_rng(&mut thread_rng()).unwrap(); - b.iter(|| { - // max supported array length is 32! - let v: [[u64; 32]; 4] = rng.gen(); - v - }); - b.bytes = 1024; -} - -#[bench] -fn gen_1k_fill(b: &mut Bencher) { - let mut rng = Pcg64Mcg::from_rng(&mut thread_rng()).unwrap(); - let mut buf = [0u64; 128]; - b.iter(|| { - rng.fill(&mut buf[..]); - buf - }); - b.bytes = 1024; -} diff --git a/rand/benches/seq.rs b/rand/benches/seq.rs deleted file mode 100644 index 4c671b8..0000000 --- a/rand/benches/seq.rs +++ /dev/null @@ -1,177 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#![feature(test)] -#![allow(non_snake_case)] - -extern crate test; - -use test::Bencher; - -use rand::prelude::*; -use rand::seq::*; -use std::mem::size_of; - -// We force use of 32-bit RNG since seq code is optimised for use with 32-bit -// generators on all platforms. -use rand_pcg::Pcg32 as SmallRng; - -const RAND_BENCH_N: u64 = 1000; - -#[bench] -fn seq_shuffle_100(b: &mut Bencher) { - let mut rng = SmallRng::from_rng(thread_rng()).unwrap(); - let x : &mut [usize] = &mut [1; 100]; - b.iter(|| { - x.shuffle(&mut rng); - x[0] - }) -} - -#[bench] -fn seq_slice_choose_1_of_1000(b: &mut Bencher) { - let mut rng = SmallRng::from_rng(thread_rng()).unwrap(); - let x : &mut [usize] = &mut [1; 1000]; - for i in 0..1000 { - x[i] = i; - } - b.iter(|| { - let mut s = 0; - for _ in 0..RAND_BENCH_N { - s += x.choose(&mut rng).unwrap(); - } - s - }); - b.bytes = size_of::() as u64 * crate::RAND_BENCH_N; -} - -macro_rules! seq_slice_choose_multiple { - ($name:ident, $amount:expr, $length:expr) => { - #[bench] - fn $name(b: &mut Bencher) { - let mut rng = SmallRng::from_rng(thread_rng()).unwrap(); - let x : &[i32] = &[$amount; $length]; - let mut result = [0i32; $amount]; - b.iter(|| { - // Collect full result to prevent unwanted shortcuts getting - // first element (in case sample_indices returns an iterator). - for (slot, sample) in result.iter_mut().zip( - x.choose_multiple(&mut rng, $amount)) { - *slot = *sample; - } - result[$amount-1] - }) - } - } -} - -seq_slice_choose_multiple!(seq_slice_choose_multiple_1_of_1000, 1, 1000); -seq_slice_choose_multiple!(seq_slice_choose_multiple_950_of_1000, 950, 1000); -seq_slice_choose_multiple!(seq_slice_choose_multiple_10_of_100, 10, 100); -seq_slice_choose_multiple!(seq_slice_choose_multiple_90_of_100, 90, 100); - -#[bench] -fn seq_iter_choose_from_1000(b: &mut Bencher) { - let mut rng = SmallRng::from_rng(thread_rng()).unwrap(); - let x : &mut [usize] = &mut [1; 1000]; - for i in 0..1000 { - x[i] = i; - } - b.iter(|| { - let mut s = 0; - for _ in 0..RAND_BENCH_N { - s += x.iter().choose(&mut rng).unwrap(); - } - s - }); - b.bytes = size_of::() as u64 * crate::RAND_BENCH_N; -} - -#[derive(Clone)] -struct UnhintedIterator { - iter: I, -} -impl Iterator for UnhintedIterator { - type Item = I::Item; - fn next(&mut self) -> Option { - self.iter.next() - } -} - -#[derive(Clone)] -struct WindowHintedIterator { - iter: I, - window_size: usize, -} -impl Iterator for WindowHintedIterator { - type Item = I::Item; - fn next(&mut self) -> Option { - self.iter.next() - } - fn size_hint(&self) -> (usize, Option) { - (std::cmp::min(self.iter.len(), self.window_size), None) - } -} - -#[bench] -fn seq_iter_unhinted_choose_from_1000(b: &mut Bencher) { - let mut rng = SmallRng::from_rng(thread_rng()).unwrap(); - let x : &[usize] = &[1; 1000]; - b.iter(|| { - UnhintedIterator { iter: x.iter() }.choose(&mut rng).unwrap() - }) -} - -#[bench] -fn seq_iter_window_hinted_choose_from_1000(b: &mut Bencher) { - let mut rng = SmallRng::from_rng(thread_rng()).unwrap(); - let x : &[usize] = &[1; 1000]; - b.iter(|| { - WindowHintedIterator { iter: x.iter(), window_size: 7 }.choose(&mut rng) - }) -} - -#[bench] -fn seq_iter_choose_multiple_10_of_100(b: &mut Bencher) { - let mut rng = SmallRng::from_rng(thread_rng()).unwrap(); - let x : &[usize] = &[1; 100]; - b.iter(|| { - x.iter().cloned().choose_multiple(&mut rng, 10) - }) -} - -#[bench] -fn seq_iter_choose_multiple_fill_10_of_100(b: &mut Bencher) { - let mut rng = SmallRng::from_rng(thread_rng()).unwrap(); - let x : &[usize] = &[1; 100]; - let mut buf = [0; 10]; - b.iter(|| { - x.iter().cloned().choose_multiple_fill(&mut rng, &mut buf) - }) -} - -macro_rules! sample_indices { - ($name:ident, $fn:ident, $amount:expr, $length:expr) => { - #[bench] - fn $name(b: &mut Bencher) { - let mut rng = SmallRng::from_rng(thread_rng()).unwrap(); - b.iter(|| { - index::$fn(&mut rng, $length, $amount) - }) - } - } -} - -sample_indices!(misc_sample_indices_1_of_1k, sample, 1, 1000); -sample_indices!(misc_sample_indices_10_of_1k, sample, 10, 1000); -sample_indices!(misc_sample_indices_100_of_1k, sample, 100, 1000); -sample_indices!(misc_sample_indices_100_of_1M, sample, 100, 1000_000); -sample_indices!(misc_sample_indices_100_of_1G, sample, 100, 1000_000_000); -sample_indices!(misc_sample_indices_200_of_1G, sample, 200, 1000_000_000); -sample_indices!(misc_sample_indices_400_of_1G, sample, 400, 1000_000_000); -sample_indices!(misc_sample_indices_600_of_1G, sample, 600, 1000_000_000); diff --git a/rand/benches/weighted.rs b/rand/benches/weighted.rs deleted file mode 100644 index 5ddca3f..0000000 --- a/rand/benches/weighted.rs +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2019 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#![feature(test)] - -extern crate test; - -use test::Bencher; -use rand::Rng; -use rand::distributions::WeightedIndex; - -#[bench] -fn weighted_index_creation(b: &mut Bencher) { - let mut rng = rand::thread_rng(); - let weights = [1u32, 2, 4, 0, 5, 1, 7, 1, 2, 3, 4, 5, 6, 7]; - b.iter(|| { - let distr = WeightedIndex::new(weights.to_vec()).unwrap(); - rng.sample(distr) - }) -} - -#[bench] -fn weighted_index_modification(b: &mut Bencher) { - let mut rng = rand::thread_rng(); - let weights = [1u32, 2, 3, 0, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7]; - let mut distr = WeightedIndex::new(weights.to_vec()).unwrap(); - b.iter(|| { - distr.update_weights(&[(2, &4), (5, &1)]).unwrap(); - rng.sample(&distr) - }) -} diff --git a/rand/examples/monte-carlo.rs b/rand/examples/monte-carlo.rs deleted file mode 100644 index 39c779f..0000000 --- a/rand/examples/monte-carlo.rs +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// Copyright 2013-2018 The Rust Project Developers. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! # Monte Carlo estimation of Ο€ -//! -//! Imagine that we have a square with sides of length 2 and a unit circle -//! (radius = 1), both centered at the origin. The areas are: -//! -//! ```text -//! area of circle = Ο€rΒ² = Ο€ * r * r = Ο€ -//! area of square = 2Β² = 4 -//! ``` -//! -//! The circle is entirely within the square, so if we sample many points -//! randomly from the square, roughly Ο€ / 4 of them should be inside the circle. -//! -//! We can use the above fact to estimate the value of Ο€: pick many points in -//! the square at random, calculate the fraction that fall within the circle, -//! and multiply this fraction by 4. - -#![cfg(feature = "std")] - -use rand::distributions::{Distribution, Uniform}; - -fn main() { - let range = Uniform::new(-1.0f64, 1.0); - let mut rng = rand::thread_rng(); - - let total = 1_000_000; - let mut in_circle = 0; - - for _ in 0..total { - let a = range.sample(&mut rng); - let b = range.sample(&mut rng); - if a*a + b*b <= 1.0 { - in_circle += 1; - } - } - - // prints something close to 3.14159... - println!("Ο€ is approximately {}", 4. * (in_circle as f64) / (total as f64)); -} diff --git a/rand/examples/monty-hall.rs b/rand/examples/monty-hall.rs deleted file mode 100644 index 9fe5839..0000000 --- a/rand/examples/monty-hall.rs +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// Copyright 2013-2018 The Rust Project Developers. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! ## Monty Hall Problem -//! -//! This is a simulation of the [Monty Hall Problem][]: -//! -//! > Suppose you're on a game show, and you're given the choice of three doors: -//! > Behind one door is a car; behind the others, goats. You pick a door, say -//! > No. 1, and the host, who knows what's behind the doors, opens another -//! > door, say No. 3, which has a goat. He then says to you, "Do you want to -//! > pick door No. 2?" Is it to your advantage to switch your choice? -//! -//! The rather unintuitive answer is that you will have a 2/3 chance of winning -//! if you switch and a 1/3 chance of winning if you don't, so it's better to -//! switch. -//! -//! This program will simulate the game show and with large enough simulation -//! steps it will indeed confirm that it is better to switch. -//! -//! [Monty Hall Problem]: https://en.wikipedia.org/wiki/Monty_Hall_problem - -#![cfg(feature = "std")] - -use rand::distributions::{Distribution, Uniform}; -use rand::Rng; - -struct SimulationResult { - win: bool, - switch: bool, -} - -// Run a single simulation of the Monty Hall problem. -fn simulate(random_door: &Uniform, rng: &mut R) -> SimulationResult { - let car = random_door.sample(rng); - - // This is our initial choice - let mut choice = random_door.sample(rng); - - // The game host opens a door - let open = game_host_open(car, choice, rng); - - // Shall we switch? - let switch = rng.gen(); - if switch { - choice = switch_door(choice, open); - } - - SimulationResult { win: choice == car, switch } -} - -// Returns the door the game host opens given our choice and knowledge of -// where the car is. The game host will never open the door with the car. -fn game_host_open(car: u32, choice: u32, rng: &mut R) -> u32 { - use rand::seq::SliceRandom; - *free_doors(&[car, choice]).choose(rng).unwrap() -} - -// Returns the door we switch to, given our current choice and -// the open door. There will only be one valid door. -fn switch_door(choice: u32, open: u32) -> u32 { - free_doors(&[choice, open])[0] -} - -fn free_doors(blocked: &[u32]) -> Vec { - (0..3).filter(|x| !blocked.contains(x)).collect() -} - -fn main() { - // The estimation will be more accurate with more simulations - let num_simulations = 10000; - - let mut rng = rand::thread_rng(); - let random_door = Uniform::new(0u32, 3); - - let (mut switch_wins, mut switch_losses) = (0, 0); - let (mut keep_wins, mut keep_losses) = (0, 0); - - println!("Running {} simulations...", num_simulations); - for _ in 0..num_simulations { - let result = simulate(&random_door, &mut rng); - - match (result.win, result.switch) { - (true, true) => switch_wins += 1, - (true, false) => keep_wins += 1, - (false, true) => switch_losses += 1, - (false, false) => keep_losses += 1, - } - } - - let total_switches = switch_wins + switch_losses; - let total_keeps = keep_wins + keep_losses; - - println!("Switched door {} times with {} wins and {} losses", - total_switches, switch_wins, switch_losses); - - println!("Kept our choice {} times with {} wins and {} losses", - total_keeps, keep_wins, keep_losses); - - // With a large number of simulations, the values should converge to - // 0.667 and 0.333 respectively. - println!("Estimated chance to win if we switch: {}", - switch_wins as f32 / total_switches as f32); - println!("Estimated chance to win if we don't: {}", - keep_wins as f32 / total_keeps as f32); -} diff --git a/rand/rand_chacha/CHANGELOG.md b/rand/rand_chacha/CHANGELOG.md deleted file mode 100644 index d242f97..0000000 --- a/rand/rand_chacha/CHANGELOG.md +++ /dev/null @@ -1,18 +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.2.1] - 2019-07-22 -- Force enable the `simd` feature of `c2-chacha` (#845) - -## [0.2.0] - 2019-06-06 -- Rewrite based on the much faster `c2-chacha` crate (#789) - -## [0.1.1] - 2019-01-04 -- Disable `i128` and `u128` if the `target_os` is `emscripten` (#671: work-around Emscripten limitation) -- Update readme and doc links - -## [0.1.0] - 2018-10-17 -- Pulled out of the Rand crate diff --git a/rand/rand_chacha/COPYRIGHT b/rand/rand_chacha/COPYRIGHT deleted file mode 100644 index 468d907..0000000 --- a/rand/rand_chacha/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 or - or the MIT license - or , at your option. - -The Rand project includes code from the Rust project -published under these same licenses. diff --git a/rand/rand_chacha/Cargo.toml b/rand/rand_chacha/Cargo.toml deleted file mode 100644 index 6a47b86..0000000 --- a/rand/rand_chacha/Cargo.toml +++ /dev/null @@ -1,28 +0,0 @@ -[package] -name = "rand_chacha" -version = "0.2.1" -authors = ["The Rand Project Developers", "The Rust Project Developers", "The CryptoCorrosion Contributors"] -license = "MIT OR Apache-2.0" -readme = "README.md" -repository = "https://github.com/rust-random/rand" -documentation = "https://rust-random.github.io/rand/rand_chacha/" -homepage = "https://crates.io/crates/rand_chacha" -description = """ -ChaCha random number generator -""" -keywords = ["random", "rng", "chacha"] -categories = ["algorithms", "no-std"] -edition = "2018" - -[badges] -travis-ci = { repository = "rust-random/rand" } -appveyor = { repository = "rust-random/rand" } - -[dependencies] -rand_core = { path = "../rand_core", version = "0.5" } -c2-chacha = { version = "0.2.2", default-features = false, features = ["simd"] } - -[features] -default = ["std", "simd"] -std = ["c2-chacha/std"] -simd = [] # deprecated diff --git a/rand/rand_chacha/LICENSE-APACHE b/rand/rand_chacha/LICENSE-APACHE deleted file mode 100644 index 17d7468..0000000 --- a/rand/rand_chacha/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_chacha/LICENSE-MIT b/rand/rand_chacha/LICENSE-MIT deleted file mode 100644 index d93b5ba..0000000 --- a/rand/rand_chacha/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_chacha/README.md b/rand/rand_chacha/README.md deleted file mode 100644 index 69a0ce7..0000000 --- a/rand/rand_chacha/README.md +++ /dev/null @@ -1,49 +0,0 @@ -# rand_chacha - -[![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_chacha.svg)](https://crates.io/crates/rand_chacha) -[![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_chacha) -[![API](https://docs.rs/rand_chacha/badge.svg)](https://docs.rs/rand_chacha) -[![Minimum rustc version](https://img.shields.io/badge/rustc-1.32+-lightgray.svg)](https://github.com/rust-random/rand#rust-version-requirements) - -A cryptographically secure random number generator that uses the ChaCha -algorithm. - -ChaCha is a stream cipher designed by Daniel J. Bernstein[^1], that we use -as an RNG. It is an improved variant of the Salsa20 cipher family, which was -selected as one of the "stream ciphers suitable for widespread adoption" by -eSTREAM[^2]. - -The RNGs provided by this crate are implemented via the fast stream ciphers of -the [`c2-chacha`](https://crates.io/crates/c2-chacha) crate. - -Links: - -- [API documentation (master)](https://rust-random.github.io/rand/rand_chacha) -- [API documentation (docs.rs)](https://docs.rs/rand_chacha) -- [Changelog](https://github.com/rust-random/rand/blob/master/rand_chacha/CHANGELOG.md) - -[rand]: https://crates.io/crates/rand -[^1]: D. J. Bernstein, [*ChaCha, a variant of Salsa20*]( - https://cr.yp.to/chacha.html) - -[^2]: [eSTREAM: the ECRYPT Stream Cipher Project]( - http://www.ecrypt.eu.org/stream/) - - -## Crate Features - -`rand_chacha` is `no_std` compatible when disabling default features; the `std` -feature can be explicitly required to re-enable `std` support. Using `std` -allows detection of CPU features and thus better optimisation. - - -# License - -`rand_chacha` 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_chacha/src/chacha.rs b/rand/rand_chacha/src/chacha.rs deleted file mode 100644 index b1b89e0..0000000 --- a/rand/rand_chacha/src/chacha.rs +++ /dev/null @@ -1,452 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The ChaCha random number generator. - -#[cfg(feature = "std")] -use std as core; -#[cfg(not(feature = "std"))] -use core; - -use c2_chacha::guts::ChaCha; -use self::core::fmt; -use rand_core::block::{BlockRng, BlockRngCore}; -use rand_core::{CryptoRng, Error, RngCore, SeedableRng}; - -const STREAM_PARAM_NONCE: u32 = 1; -const STREAM_PARAM_BLOCK: u32 = 0; - -pub struct Array64([T; 64]); -impl Default for Array64 where T: Default { - fn default() -> Self { - Self([T::default(), T::default(), T::default(), T::default(), T::default(), T::default(), T::default(), T::default(), - T::default(), T::default(), T::default(), T::default(), T::default(), T::default(), T::default(), T::default(), - T::default(), T::default(), T::default(), T::default(), T::default(), T::default(), T::default(), T::default(), - T::default(), T::default(), T::default(), T::default(), T::default(), T::default(), T::default(), T::default(), - T::default(), T::default(), T::default(), T::default(), T::default(), T::default(), T::default(), T::default(), - T::default(), T::default(), T::default(), T::default(), T::default(), T::default(), T::default(), T::default(), - T::default(), T::default(), T::default(), T::default(), T::default(), T::default(), T::default(), T::default(), - T::default(), T::default(), T::default(), T::default(), T::default(), T::default(), T::default(), T::default()]) - } -} -impl AsRef<[T]> for Array64 { - fn as_ref(&self) -> &[T] { - &self.0 - } -} -impl AsMut<[T]> for Array64 { - fn as_mut(&mut self) -> &mut [T] { - &mut self.0 - } -} -impl Clone for Array64 where T: Copy + Default { - fn clone(&self) -> Self { - let mut new = Self::default(); - new.0.copy_from_slice(&self.0); - new - } -} -impl fmt::Debug for Array64 { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "Array64 {{}}") - } -} - -macro_rules! chacha_impl { - ($ChaChaXCore:ident, $ChaChaXRng:ident, $rounds:expr, $doc:expr) => { - #[doc=$doc] - #[derive(Clone)] - pub struct $ChaChaXCore { - state: ChaCha, - } - - // Custom Debug implementation that does not expose the internal state - impl fmt::Debug for $ChaChaXCore { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "ChaChaXCore {{}}") - } - } - - impl BlockRngCore for $ChaChaXCore { - type Item = u32; - type Results = Array64; - #[inline] - fn generate(&mut self, r: &mut Self::Results) { - // Fill slice of words by writing to equivalent slice of bytes, then fixing endianness. - self.state.refill4($rounds, unsafe { - &mut *(&mut *r as *mut Array64 as *mut [u8; 256]) - }); - for x in r.as_mut() { - *x = x.to_le(); - } - } - } - - impl SeedableRng for $ChaChaXCore { - type Seed = [u8; 32]; - #[inline] - fn from_seed(seed: Self::Seed) -> Self { - $ChaChaXCore { state: ChaCha::new(&seed, &[0u8; 8]) } - } - } - - /// A cryptographically secure random number generator that uses the ChaCha algorithm. - /// - /// ChaCha is a stream cipher designed by Daniel J. Bernstein[^1], that we use as an RNG. It is - /// an improved variant of the Salsa20 cipher family, which was selected as one of the "stream - /// ciphers suitable for widespread adoption" by eSTREAM[^2]. - /// - /// ChaCha uses add-rotate-xor (ARX) operations as its basis. These are safe against timing - /// attacks, although that is mostly a concern for ciphers and not for RNGs. We provide a SIMD - /// implementation to support high throughput on a variety of common hardware platforms. - /// - /// With the ChaCha algorithm it is possible to choose the number of rounds the core algorithm - /// should run. The number of rounds is a tradeoff between performance and security, where 8 - /// rounds is the minimum potentially secure configuration, and 20 rounds is widely used as a - /// conservative choice. - /// - /// We use a 64-bit counter and 64-bit stream identifier as in Bernstein's implementation[^1] - /// except that we use a stream identifier in place of a nonce. A 64-bit counter over 64-byte - /// (16 word) blocks allows 1 ZiB of output before cycling, and the stream identifier allows - /// 264 unique streams of output per seed. Both counter and stream are initialized - /// to zero but may be set via the `set_word_pos` and `set_stream` methods. - /// - /// The word layout is: - /// - /// ```text - /// constant constant constant constant - /// seed seed seed seed - /// seed seed seed seed - /// counter counter stream_id stream_id - /// ``` - /// - /// This implementation uses an output buffer of sixteen `u32` words, and uses - /// [`BlockRng`] to implement the [`RngCore`] methods. - /// - /// [^1]: D. J. Bernstein, [*ChaCha, a variant of Salsa20*]( - /// https://cr.yp.to/chacha.html) - /// - /// [^2]: [eSTREAM: the ECRYPT Stream Cipher Project]( - /// http://www.ecrypt.eu.org/stream/) - #[derive(Clone, Debug)] - pub struct $ChaChaXRng { - rng: BlockRng<$ChaChaXCore>, - } - - impl SeedableRng for $ChaChaXRng { - type Seed = [u8; 32]; - #[inline] - fn from_seed(seed: Self::Seed) -> Self { - let core = $ChaChaXCore::from_seed(seed); - Self { - rng: BlockRng::new(core), - } - } - } - - impl RngCore for $ChaChaXRng { - #[inline] - fn next_u32(&mut self) -> u32 { - self.rng.next_u32() - } - #[inline] - fn next_u64(&mut self) -> u64 { - self.rng.next_u64() - } - #[inline] - fn fill_bytes(&mut self, bytes: &mut [u8]) { - self.rng.fill_bytes(bytes) - } - #[inline] - fn try_fill_bytes(&mut self, bytes: &mut [u8]) -> Result<(), Error> { - self.rng.try_fill_bytes(bytes) - } - } - - impl $ChaChaXRng { - // The buffer is a 4-block window, i.e. it is always at a block-aligned position in the - // stream but if the stream has been seeked it may not be self-aligned. - - /// Get the offset from the start of the stream, in 32-bit words. - /// - /// Since the generated blocks are 16 words (24) long and the - /// counter is 64-bits, the offset is a 68-bit number. Sub-word offsets are - /// not supported, hence the result can simply be multiplied by 4 to get a - /// byte-offset. - #[inline] - pub fn get_word_pos(&self) -> u128 { - let mut block = u128::from(self.rng.core.state.get_stream_param(STREAM_PARAM_BLOCK)); - // counter is incremented *after* filling buffer - block -= 4; - (block << 4) + self.rng.index() as u128 - } - - /// Set the offset from the start of the stream, in 32-bit words. - /// - /// As with `get_word_pos`, we use a 68-bit number. Since the generator - /// simply cycles at the end of its period (1 ZiB), we ignore the upper - /// 60 bits. - #[inline] - pub fn set_word_pos(&mut self, word_offset: u128) { - let block = (word_offset >> 4) as u64; - self.rng - .core - .state - .set_stream_param(STREAM_PARAM_BLOCK, block); - self.rng.generate_and_set((word_offset & 15) as usize); - } - - /// Set the stream number. - /// - /// This is initialized to zero; 264 unique streams of output - /// are available per seed/key. - /// - /// Note that in order to reproduce ChaCha output with a specific 64-bit - /// nonce, one can convert that nonce to a `u64` in little-endian fashion - /// and pass to this function. In theory a 96-bit nonce can be used by - /// passing the last 64-bits to this function and using the first 32-bits as - /// the most significant half of the 64-bit counter (which may be set - /// indirectly via `set_word_pos`), but this is not directly supported. - #[inline] - pub fn set_stream(&mut self, stream: u64) { - self.rng - .core - .state - .set_stream_param(STREAM_PARAM_NONCE, stream); - if self.rng.index() != 64 { - let wp = self.get_word_pos(); - self.set_word_pos(wp); - } - } - } - - impl CryptoRng for $ChaChaXRng {} - - impl From<$ChaChaXCore> for $ChaChaXRng { - fn from(core: $ChaChaXCore) -> Self { - $ChaChaXRng { - rng: BlockRng::new(core), - } - } - } - } -} - -chacha_impl!(ChaCha20Core, ChaCha20Rng, 10, "ChaCha with 20 rounds"); -chacha_impl!(ChaCha12Core, ChaCha12Rng, 6, "ChaCha with 12 rounds"); -chacha_impl!(ChaCha8Core, ChaCha8Rng, 4, "ChaCha with 8 rounds"); - -#[cfg(test)] -mod test { - use rand_core::{RngCore, SeedableRng}; - - type ChaChaRng = super::ChaCha20Rng; - - #[test] - fn test_chacha_construction() { - let seed = [ - 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, - 0, 0, 0, - ]; - let mut rng1 = ChaChaRng::from_seed(seed); - assert_eq!(rng1.next_u32(), 137206642); - - let mut rng2 = ChaChaRng::from_rng(rng1).unwrap(); - assert_eq!(rng2.next_u32(), 1325750369); - } - - #[test] - fn test_chacha_true_values_a() { - // Test vectors 1 and 2 from - // https://tools.ietf.org/html/draft-nir-cfrg-chacha20-poly1305-04 - let seed = [0u8; 32]; - let mut rng = ChaChaRng::from_seed(seed); - - let mut results = [0u32; 16]; - for i in results.iter_mut() { - *i = rng.next_u32(); - } - let expected = [ - 0xade0b876, 0x903df1a0, 0xe56a5d40, 0x28bd8653, 0xb819d2bd, 0x1aed8da0, 0xccef36a8, - 0xc70d778b, 0x7c5941da, 0x8d485751, 0x3fe02477, 0x374ad8b8, 0xf4b8436a, 0x1ca11815, - 0x69b687c3, 0x8665eeb2, - ]; - assert_eq!(results, expected); - - for i in results.iter_mut() { - *i = rng.next_u32(); - } - let expected = [ - 0xbee7079f, 0x7a385155, 0x7c97ba98, 0x0d082d73, 0xa0290fcb, 0x6965e348, 0x3e53c612, - 0xed7aee32, 0x7621b729, 0x434ee69c, 0xb03371d5, 0xd539d874, 0x281fed31, 0x45fb0a51, - 0x1f0ae1ac, 0x6f4d794b, - ]; - assert_eq!(results, expected); - } - - #[test] - fn test_chacha_true_values_b() { - // Test vector 3 from - // https://tools.ietf.org/html/draft-nir-cfrg-chacha20-poly1305-04 - let seed = [ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 1, - ]; - let mut rng = ChaChaRng::from_seed(seed); - - // Skip block 0 - for _ in 0..16 { - rng.next_u32(); - } - - let mut results = [0u32; 16]; - for i in results.iter_mut() { - *i = rng.next_u32(); - } - let expected = [ - 0x2452eb3a, 0x9249f8ec, 0x8d829d9b, 0xddd4ceb1, 0xe8252083, 0x60818b01, 0xf38422b8, - 0x5aaa49c9, 0xbb00ca8e, 0xda3ba7b4, 0xc4b592d1, 0xfdf2732f, 0x4436274e, 0x2561b3c8, - 0xebdd4aa6, 0xa0136c00, - ]; - assert_eq!(results, expected); - } - - #[test] - fn test_chacha_true_values_c() { - // Test vector 4 from - // https://tools.ietf.org/html/draft-nir-cfrg-chacha20-poly1305-04 - let seed = [ - 0, 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, - ]; - let expected = [ - 0xfb4dd572, 0x4bc42ef1, 0xdf922636, 0x327f1394, 0xa78dea8f, 0x5e269039, 0xa1bebbc1, - 0xcaf09aae, 0xa25ab213, 0x48a6b46c, 0x1b9d9bcb, 0x092c5be6, 0x546ca624, 0x1bec45d5, - 0x87f47473, 0x96f0992e, - ]; - let expected_end = 3 * 16; - let mut results = [0u32; 16]; - - // Test block 2 by skipping block 0 and 1 - let mut rng1 = ChaChaRng::from_seed(seed); - for _ in 0..32 { - rng1.next_u32(); - } - for i in results.iter_mut() { - *i = rng1.next_u32(); - } - assert_eq!(results, expected); - assert_eq!(rng1.get_word_pos(), expected_end); - - // Test block 2 by using `set_word_pos` - let mut rng2 = ChaChaRng::from_seed(seed); - rng2.set_word_pos(2 * 16); - for i in results.iter_mut() { - *i = rng2.next_u32(); - } - assert_eq!(results, expected); - assert_eq!(rng2.get_word_pos(), expected_end); - - // Test skipping behaviour with other types - let mut buf = [0u8; 32]; - rng2.fill_bytes(&mut buf[..]); - assert_eq!(rng2.get_word_pos(), expected_end + 8); - rng2.fill_bytes(&mut buf[0..25]); - assert_eq!(rng2.get_word_pos(), expected_end + 15); - rng2.next_u64(); - assert_eq!(rng2.get_word_pos(), expected_end + 17); - rng2.next_u32(); - rng2.next_u64(); - assert_eq!(rng2.get_word_pos(), expected_end + 20); - rng2.fill_bytes(&mut buf[0..1]); - assert_eq!(rng2.get_word_pos(), expected_end + 21); - } - - #[test] - fn test_chacha_multiple_blocks() { - let seed = [ - 0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0, 5, 0, 0, 0, 6, 0, 0, 0, 7, - 0, 0, 0, - ]; - let mut rng = ChaChaRng::from_seed(seed); - - // Store the 17*i-th 32-bit word, - // i.e., the i-th word of the i-th 16-word block - let mut results = [0u32; 16]; - for i in results.iter_mut() { - *i = rng.next_u32(); - for _ in 0..16 { - rng.next_u32(); - } - } - let expected = [ - 0xf225c81a, 0x6ab1be57, 0x04d42951, 0x70858036, 0x49884684, 0x64efec72, 0x4be2d186, - 0x3615b384, 0x11cfa18e, 0xd3c50049, 0x75c775f6, 0x434c6530, 0x2c5bad8f, 0x898881dc, - 0x5f1c86d9, 0xc1f8e7f4, - ]; - assert_eq!(results, expected); - } - - #[test] - fn test_chacha_true_bytes() { - let seed = [0u8; 32]; - let mut rng = ChaChaRng::from_seed(seed); - let mut results = [0u8; 32]; - rng.fill_bytes(&mut results); - let expected = [ - 118, 184, 224, 173, 160, 241, 61, 144, 64, 93, 106, 229, 83, 134, 189, 40, 189, 210, - 25, 184, 160, 141, 237, 26, 168, 54, 239, 204, 139, 119, 13, 199, - ]; - assert_eq!(results, expected); - } - - #[test] - fn test_chacha_nonce() { - // Test vector 5 from - // https://tools.ietf.org/html/draft-nir-cfrg-chacha20-poly1305-04 - // Although we do not support setting a nonce, we try it here anyway so - // we can use this test vector. - let seed = [0u8; 32]; - let mut rng = ChaChaRng::from_seed(seed); - // 96-bit nonce in LE order is: 0,0,0,0, 0,0,0,0, 0,0,0,2 - rng.set_stream(2u64 << (24 + 32)); - - let mut results = [0u32; 16]; - for i in results.iter_mut() { - *i = rng.next_u32(); - } - let expected = [ - 0x374dc6c2, 0x3736d58c, 0xb904e24a, 0xcd3f93ef, 0x88228b1a, 0x96a4dfb3, 0x5b76ab72, - 0xc727ee54, 0x0e0e978a, 0xf3145c95, 0x1b748ea8, 0xf786c297, 0x99c28f5f, 0x628314e8, - 0x398a19fa, 0x6ded1b53, - ]; - assert_eq!(results, expected); - } - - #[test] - fn test_chacha_clone_streams() { - let seed = [ - 0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0, 5, 0, 0, 0, 6, 0, 0, 0, 7, - 0, 0, 0, - ]; - let mut rng = ChaChaRng::from_seed(seed); - let mut clone = rng.clone(); - for _ in 0..16 { - assert_eq!(rng.next_u64(), clone.next_u64()); - } - - rng.set_stream(51); - for _ in 0..7 { - assert!(rng.next_u32() != clone.next_u32()); - } - clone.set_stream(51); // switch part way through block - for _ in 7..16 { - assert_eq!(rng.next_u32(), clone.next_u32()); - } - } -} diff --git a/rand/rand_chacha/src/lib.rs b/rand/rand_chacha/src/lib.rs deleted file mode 100644 index e374bdd..0000000 --- a/rand/rand_chacha/src/lib.rs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The ChaCha random number generator. - -#![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(not(feature = "std"), no_std)] - -pub use rand_core; - -mod chacha; - -pub use crate::chacha::{ChaCha12Core, ChaCha12Rng, ChaCha20Core, ChaCha20Rng, ChaCha8Core, ChaCha8Rng}; - -/// ChaCha with 20 rounds -pub type ChaChaRng = ChaCha20Rng; -/// ChaCha with 20 rounds, low-level interface -pub type ChaChaCore = ChaCha20Core; 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 or - or the MIT license - or , 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` 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 or the MIT license -// , 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; -//! ``` -//! -//! [`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;`) but might prefer to use a -/// wrapper type (`pub struct MyRng(BlockRng);`); 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 { - 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 fmt::Debug for BlockRng { - 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 BlockRng { - /// Create a new `BlockRng` from an existing RNG implementing - /// `BlockRngCore`. Results will be generated on first use. - #[inline] - pub fn new(core: R) -> BlockRng{ - 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> RngCore for BlockRng -where ::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 SeedableRng for BlockRng { - 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(rng: S) -> Result { - 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 { - 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 fmt::Debug for BlockRng64 { - 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 BlockRng64 { - /// Create a new `BlockRng` from an existing RNG implementing - /// `BlockRngCore`. Results will be generated on first use. - #[inline] - pub fn new(core: R) -> BlockRng64{ - 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> RngCore for BlockRng64 -where ::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 SeedableRng for BlockRng64 { - 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(rng: S) -> Result { - Ok(Self::new(R::from_rng(rng)?)) - } -} - -impl CryptoRng for BlockRng {} 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 or the MIT license -// , 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, - #[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`, which is available with and without `std`. - #[cfg(feature="std")] - #[inline] - pub fn new(err: E) -> Self - where E: Into> - { - 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 { - 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 { - #[cfg(feature="std")] { - if let Some(e) = self.inner.downcast_ref::() { - 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`, 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 { - #[cfg(feature="std")] { - self.inner.downcast_ref::().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 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 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 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 or the MIT license -// , 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(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(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(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(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 or the MIT license -// , 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 or the MIT license -// , 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` 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(mut rng: R) -> Result { - 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 RngCore for Box { - #[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 { - 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 CryptoRng for Box {} - -#[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 or the MIT license -// , 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); -} diff --git a/rand/rand_distr/CHANGELOG.md b/rand/rand_distr/CHANGELOG.md deleted file mode 100644 index 376bb95..0000000 --- a/rand/rand_distr/CHANGELOG.md +++ /dev/null @@ -1,21 +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.2.1] - 2019-06-29 -- Update dependency to support Rand 0.7 -- Doc link fixes - -## [0.2.0] - 2019-06-06 -- Remove `new` constructors for zero-sized types -- Add Pert distribution -- Fix undefined behavior in `Poisson` -- Make all distributions return `Result`s instead of panicking -- Implement `f32` support for most distributions -- Rename `UnitSphereSurface` to `UnitSphere` -- Implement `UnitBall` and `UnitDisc` - -## [0.1.0] - 2019-06-06 -Initial release. This is equivalent to the code in `rand` 0.6.5. diff --git a/rand/rand_distr/COPYRIGHT b/rand/rand_distr/COPYRIGHT deleted file mode 100644 index 468d907..0000000 --- a/rand/rand_distr/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 or - or the MIT license - or , at your option. - -The Rand project includes code from the Rust project -published under these same licenses. diff --git a/rand/rand_distr/Cargo.toml b/rand/rand_distr/Cargo.toml deleted file mode 100644 index 315a5b0..0000000 --- a/rand/rand_distr/Cargo.toml +++ /dev/null @@ -1,27 +0,0 @@ -[package] -name = "rand_distr" -version = "0.2.1" -authors = ["The Rand 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_distr/" -homepage = "https://crates.io/crates/rand_distr" -description = """ -Sampling from random number distributions -""" -keywords = ["random", "rng", "distribution", "probability"] -categories = ["algorithms"] -edition = "2018" - -[badges] -travis-ci = { repository = "rust-random/rand" } -appveyor = { repository = "rust-random/rand" } - -[dependencies] -rand = { path = "..", version = "0.7" } - -[dev-dependencies] -rand_pcg = { version = "0.2", path = "../rand_pcg" } -# Histogram implementation for testing uniformity -average = "0.9.2" diff --git a/rand/rand_distr/LICENSE-APACHE b/rand/rand_distr/LICENSE-APACHE deleted file mode 100644 index 17d7468..0000000 --- a/rand/rand_distr/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_distr/LICENSE-MIT b/rand/rand_distr/LICENSE-MIT deleted file mode 100644 index cf65607..0000000 --- a/rand/rand_distr/LICENSE-MIT +++ /dev/null @@ -1,25 +0,0 @@ -Copyright 2018 Developers of the Rand project - -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_distr/README.md b/rand/rand_distr/README.md deleted file mode 100644 index 68acd2f..0000000 --- a/rand/rand_distr/README.md +++ /dev/null @@ -1,42 +0,0 @@ -# rand_distr - -[![Build Status](https://travis-ci.org/rust-random/rand.svg?branch=master)](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_distr.svg)](https://crates.io/crates/rand_distr) -[[![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_distr) -[![API](https://docs.rs/rand_distr/badge.svg)](https://docs.rs/rand_distr) -[![Minimum rustc version](https://img.shields.io/badge/rustc-1.32+-lightgray.svg)](https://github.com/rust-random/rand#rust-version-requirements) - -Implements a full suite of random number distributions sampling routines. - -This crate is a super-set of the [rand::distributions] module, including support -for sampling from Beta, Binomial, Cauchy, ChiSquared, Dirichlet, exponential, -Fisher F, Gamma, Log-normal, Normal, Pareto, Poisson, StudentT, Triangular and -Weibull distributions, as well as sampling points from the unit circle and unit -sphere surface. - -It is worth mentioning the [statrs] crate which provides similar functionality -along with various support functions, including PDF and CDF computation. In -contrast, this `rand_distr` crate focusses on sampling from distributions. - -Unlike most Rand crates, `rand_distr` does not currently support `no_std`. - -Links: - -- [API documentation (master)](https://rust-random.github.io/rand/rand_distr) -- [API documentation (docs.rs)](https://docs.rs/rand_distr) -- [Changelog](CHANGELOG.md) -- [The Rand project](https://github.com/rust-random/rand) - - -[statrs]: https://github.com/boxtown/statrs -[rand::distributions]: https://rust-random.github.io/rand/rand/distributions/index.html - -## License - -`rand_distr` 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_distr/benches/distributions.rs b/rand/rand_distr/benches/distributions.rs deleted file mode 100644 index 63bde36..0000000 --- a/rand/rand_distr/benches/distributions.rs +++ /dev/null @@ -1,316 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#![feature(test)] - -const RAND_BENCH_N: u64 = 1000; - -use std::mem::size_of; -use std::num::{NonZeroU8, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU128}; -use test::Bencher; -use std::time::Duration; - -use rand::prelude::*; -use rand_distr::{*, weighted::WeightedIndex}; - -// At this time, distributions are optimised for 64-bit platforms. -use rand_pcg::Pcg64Mcg; - -macro_rules! distr_int { - ($fnn:ident, $ty:ty, $distr:expr) => { - #[bench] - fn $fnn(b: &mut Bencher) { - let mut rng = Pcg64Mcg::from_entropy(); - let distr = $distr; - - b.iter(|| { - let mut accum = 0 as $ty; - for _ in 0..RAND_BENCH_N { - let x: $ty = distr.sample(&mut rng); - accum = accum.wrapping_add(x); - } - accum - }); - b.bytes = size_of::<$ty>() as u64 * RAND_BENCH_N; - } - } -} - -macro_rules! distr_nz_int { - ($fnn:ident, $tynz:ty, $ty:ty, $distr:expr) => { - #[bench] - fn $fnn(b: &mut Bencher) { - let mut rng = Pcg64Mcg::from_entropy(); - let distr = $distr; - - b.iter(|| { - let mut accum = 0 as $ty; - for _ in 0..RAND_BENCH_N { - let x: $tynz = distr.sample(&mut rng); - accum = accum.wrapping_add(x.get()); - } - accum - }); - b.bytes = size_of::<$ty>() as u64 * RAND_BENCH_N; - } - } -} - -macro_rules! distr_float { - ($fnn:ident, $ty:ty, $distr:expr) => { - #[bench] - fn $fnn(b: &mut Bencher) { - let mut rng = Pcg64Mcg::from_entropy(); - let distr = $distr; - - b.iter(|| { - let mut accum = 0.0; - for _ in 0..RAND_BENCH_N { - let x: $ty = distr.sample(&mut rng); - accum += x; - } - accum - }); - b.bytes = size_of::<$ty>() as u64 * RAND_BENCH_N; - } - } -} - -macro_rules! distr_duration { - ($fnn:ident, $distr:expr) => { - #[bench] - fn $fnn(b: &mut Bencher) { - let mut rng = Pcg64Mcg::from_entropy(); - let distr = $distr; - - b.iter(|| { - let mut accum = Duration::new(0, 0); - for _ in 0..RAND_BENCH_N { - let x: Duration = distr.sample(&mut rng); - accum = accum.checked_add(x).unwrap_or(Duration::new(u64::max_value(), 999_999_999)); - } - accum - }); - b.bytes = size_of::() as u64 * RAND_BENCH_N; - } - } -} - -macro_rules! distr { - ($fnn:ident, $ty:ty, $distr:expr) => { - #[bench] - fn $fnn(b: &mut Bencher) { - let mut rng = Pcg64Mcg::from_entropy(); - let distr = $distr; - - b.iter(|| { - let mut accum = 0u32; - for _ in 0..RAND_BENCH_N { - let x: $ty = distr.sample(&mut rng); - accum = accum.wrapping_add(x as u32); - } - accum - }); - b.bytes = size_of::<$ty>() as u64 * RAND_BENCH_N; - } - } -} - -macro_rules! distr_arr { - ($fnn:ident, $ty:ty, $distr:expr) => { - #[bench] - fn $fnn(b: &mut Bencher) { - let mut rng = Pcg64Mcg::from_entropy(); - let distr = $distr; - - b.iter(|| { - let mut accum = 0u32; - for _ in 0..RAND_BENCH_N { - let x: $ty = distr.sample(&mut rng); - accum = accum.wrapping_add(x[0] as u32); - } - accum - }); - b.bytes = size_of::<$ty>() as u64 * RAND_BENCH_N; - } - } -} - -// uniform -distr_int!(distr_uniform_i8, i8, Uniform::new(20i8, 100)); -distr_int!(distr_uniform_i16, i16, Uniform::new(-500i16, 2000)); -distr_int!(distr_uniform_i32, i32, Uniform::new(-200_000_000i32, 800_000_000)); -distr_int!(distr_uniform_i64, i64, Uniform::new(3i64, 123_456_789_123)); -distr_int!(distr_uniform_i128, i128, Uniform::new(-123_456_789_123i128, 123_456_789_123_456_789)); -distr_int!(distr_uniform_usize16, usize, Uniform::new(0usize, 0xb9d7)); -distr_int!(distr_uniform_usize32, usize, Uniform::new(0usize, 0x548c0f43)); -#[cfg(target_pointer_width = "64")] -distr_int!(distr_uniform_usize64, usize, Uniform::new(0usize, 0x3a42714f2bf927a8)); -distr_int!(distr_uniform_isize, isize, Uniform::new(-1060478432isize, 1858574057)); - -distr_float!(distr_uniform_f32, f32, Uniform::new(2.26f32, 2.319)); -distr_float!(distr_uniform_f64, f64, Uniform::new(2.26f64, 2.319)); - -const LARGE_SEC: u64 = u64::max_value() / 1000; - -distr_duration!(distr_uniform_duration_largest, - Uniform::new_inclusive(Duration::new(0, 0), Duration::new(u64::max_value(), 999_999_999)) -); -distr_duration!(distr_uniform_duration_large, - Uniform::new(Duration::new(0, 0), Duration::new(LARGE_SEC, 1_000_000_000 / 2)) -); -distr_duration!(distr_uniform_duration_one, - Uniform::new(Duration::new(0, 0), Duration::new(1, 0)) -); -distr_duration!(distr_uniform_duration_variety, - Uniform::new(Duration::new(10000, 423423), Duration::new(200000, 6969954)) -); -distr_duration!(distr_uniform_duration_edge, - Uniform::new_inclusive(Duration::new(LARGE_SEC, 999_999_999), Duration::new(LARGE_SEC + 1, 1)) -); - - -// standard -distr_int!(distr_standard_i8, i8, Standard); -distr_int!(distr_standard_i16, i16, Standard); -distr_int!(distr_standard_i32, i32, Standard); -distr_int!(distr_standard_i64, i64, Standard); -distr_int!(distr_standard_i128, i128, Standard); -distr_nz_int!(distr_standard_nz8, NonZeroU8, u8, Standard); -distr_nz_int!(distr_standard_nz16, NonZeroU16, u16, Standard); -distr_nz_int!(distr_standard_nz32, NonZeroU32, u32, Standard); -distr_nz_int!(distr_standard_nz64, NonZeroU64, u64, Standard); -distr_nz_int!(distr_standard_nz128, NonZeroU128, u128, Standard); - -distr!(distr_standard_bool, bool, Standard); -distr!(distr_standard_alphanumeric, char, Alphanumeric); -distr!(distr_standard_codepoint, char, Standard); - -distr_float!(distr_standard_f32, f32, Standard); -distr_float!(distr_standard_f64, f64, Standard); -distr_float!(distr_open01_f32, f32, Open01); -distr_float!(distr_open01_f64, f64, Open01); -distr_float!(distr_openclosed01_f32, f32, OpenClosed01); -distr_float!(distr_openclosed01_f64, f64, OpenClosed01); - -// distributions -distr_float!(distr_exp, f64, Exp::new(1.23 * 4.56).unwrap()); -distr_float!(distr_normal, f64, Normal::new(-1.23, 4.56).unwrap()); -distr_float!(distr_log_normal, f64, LogNormal::new(-1.23, 4.56).unwrap()); -distr_float!(distr_gamma_large_shape, f64, Gamma::new(10., 1.0).unwrap()); -distr_float!(distr_gamma_small_shape, f64, Gamma::new(0.1, 1.0).unwrap()); -distr_float!(distr_cauchy, f64, Cauchy::new(4.2, 6.9).unwrap()); -distr_float!(distr_triangular, f64, Triangular::new(0., 1., 0.9).unwrap()); -distr_int!(distr_binomial, u64, Binomial::new(20, 0.7).unwrap()); -distr_int!(distr_binomial_small, u64, Binomial::new(1000000, 1e-30).unwrap()); -distr_int!(distr_poisson, u64, Poisson::new(4.0).unwrap()); -distr!(distr_bernoulli, bool, Bernoulli::new(0.18).unwrap()); -distr_arr!(distr_circle, [f64; 2], UnitCircle); -distr_arr!(distr_sphere, [f64; 3], UnitSphere); - -// Weighted -distr_int!(distr_weighted_i8, usize, WeightedIndex::new(&[1i8, 2, 3, 4, 12, 0, 2, 1]).unwrap()); -distr_int!(distr_weighted_u32, usize, WeightedIndex::new(&[1u32, 2, 3, 4, 12, 0, 2, 1]).unwrap()); -distr_int!(distr_weighted_f64, usize, WeightedIndex::new(&[1.0f64, 0.001, 1.0/3.0, 4.01, 0.0, 3.3, 22.0, 0.001]).unwrap()); -distr_int!(distr_weighted_large_set, usize, WeightedIndex::new((0..10000).rev().chain(1..10001)).unwrap()); - -distr_int!(distr_weighted_alias_method_i8, usize, weighted::alias_method::WeightedIndex::new(vec![1i8, 2, 3, 4, 12, 0, 2, 1]).unwrap()); -distr_int!(distr_weighted_alias_method_u32, usize, weighted::alias_method::WeightedIndex::new(vec![1u32, 2, 3, 4, 12, 0, 2, 1]).unwrap()); -distr_int!(distr_weighted_alias_method_f64, usize, weighted::alias_method::WeightedIndex::new(vec![1.0f64, 0.001, 1.0/3.0, 4.01, 0.0, 3.3, 22.0, 0.001]).unwrap()); -distr_int!(distr_weighted_alias_method_large_set, usize, weighted::alias_method::WeightedIndex::new((0..10000).rev().chain(1..10001).collect()).unwrap()); - -// construct and sample from a range -macro_rules! gen_range_int { - ($fnn:ident, $ty:ident, $low:expr, $high:expr) => { - #[bench] - fn $fnn(b: &mut Bencher) { - let mut rng = Pcg64Mcg::from_entropy(); - - b.iter(|| { - let mut high = $high; - let mut accum: $ty = 0; - for _ in 0..RAND_BENCH_N { - accum = accum.wrapping_add(rng.gen_range($low, high)); - // force recalculation of range each time - high = high.wrapping_add(1) & std::$ty::MAX; - } - accum - }); - b.bytes = size_of::<$ty>() as u64 * RAND_BENCH_N; - } - } -} - -gen_range_int!(gen_range_i8, i8, -20i8, 100); -gen_range_int!(gen_range_i16, i16, -500i16, 2000); -gen_range_int!(gen_range_i32, i32, -200_000_000i32, 800_000_000); -gen_range_int!(gen_range_i64, i64, 3i64, 123_456_789_123); -gen_range_int!(gen_range_i128, i128, -12345678901234i128, 123_456_789_123_456_789); - -// construct and sample from a floating-point range -macro_rules! gen_range_float { - ($fnn:ident, $ty:ident, $low:expr, $high:expr) => { - #[bench] - fn $fnn(b: &mut Bencher) { - let mut rng = Pcg64Mcg::from_entropy(); - - b.iter(|| { - let mut high = $high; - let mut low = $low; - let mut accum: $ty = 0.0; - for _ in 0..RAND_BENCH_N { - accum += rng.gen_range(low, high); - // force recalculation of range each time - low += 0.9; - high += 1.1; - } - accum - }); - b.bytes = size_of::<$ty>() as u64 * RAND_BENCH_N; - } - } -} - -gen_range_float!(gen_range_f32, f32, -20000.0f32, 100000.0); -gen_range_float!(gen_range_f64, f64, 123.456f64, 7890.12); - -#[bench] -fn dist_iter(b: &mut Bencher) { - let mut rng = Pcg64Mcg::from_entropy(); - let distr = Normal::new(-2.71828, 3.14159).unwrap(); - let mut iter = distr.sample_iter(&mut rng); - - b.iter(|| { - let mut accum = 0.0; - for _ in 0..RAND_BENCH_N { - accum += iter.next().unwrap(); - } - accum - }); - b.bytes = size_of::() as u64 * RAND_BENCH_N; -} - -macro_rules! sample_binomial { - ($name:ident, $n:expr, $p:expr) => { - #[bench] - fn $name(b: &mut Bencher) { - let mut rng = Pcg64Mcg::from_rng(&mut thread_rng()).unwrap(); - let (n, p) = ($n, $p); - b.iter(|| { - let d = Binomial::new(n, p).unwrap(); - rng.sample(d) - }) - } - } -} - -sample_binomial!(misc_binomial_1, 1, 0.9); -sample_binomial!(misc_binomial_10, 10, 0.9); -sample_binomial!(misc_binomial_100, 100, 0.99); -sample_binomial!(misc_binomial_1000, 1000, 0.01); -sample_binomial!(misc_binomial_1e12, 1000_000_000_000, 0.2); diff --git a/rand/rand_distr/src/binomial.rs b/rand/rand_distr/src/binomial.rs deleted file mode 100644 index 0e6bf9a..0000000 --- a/rand/rand_distr/src/binomial.rs +++ /dev/null @@ -1,329 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// Copyright 2016-2017 The Rust Project Developers. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The binomial distribution. - -use rand::Rng; -use crate::{Distribution, Uniform}; - -/// The binomial distribution `Binomial(n, p)`. -/// -/// This distribution has density function: -/// `f(k) = n!/(k! (n-k)!) p^k (1-p)^(n-k)` for `k >= 0`. -/// -/// # Example -/// -/// ``` -/// use rand_distr::{Binomial, Distribution}; -/// -/// let bin = Binomial::new(20, 0.3).unwrap(); -/// let v = bin.sample(&mut rand::thread_rng()); -/// println!("{} is from a binomial distribution", v); -/// ``` -#[derive(Clone, Copy, Debug)] -pub struct Binomial { - /// Number of trials. - n: u64, - /// Probability of success. - p: f64, -} - -/// Error type returned from `Binomial::new`. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Error { - /// `p < 0` or `nan`. - ProbabilityTooSmall, - /// `p > 1`. - ProbabilityTooLarge, -} - -impl Binomial { - /// Construct a new `Binomial` with the given shape parameters `n` (number - /// of trials) and `p` (probability of success). - pub fn new(n: u64, p: f64) -> Result { - if !(p >= 0.0) { - return Err(Error::ProbabilityTooSmall); - } - if !(p <= 1.0) { - return Err(Error::ProbabilityTooLarge); - } - Ok(Binomial { n, p }) - } -} - -/// Convert a `f64` to an `i64`, panicing on overflow. -// In the future (Rust 1.34), this might be replaced with `TryFrom`. -fn f64_to_i64(x: f64) -> i64 { - assert!(x < (::std::i64::MAX as f64)); - x as i64 -} - -impl Distribution for Binomial { - #[allow(clippy::many_single_char_names)] // Same names as in the reference. - fn sample(&self, rng: &mut R) -> u64 { - // Handle these values directly. - if self.p == 0.0 { - return 0; - } else if self.p == 1.0 { - return self.n; - } - - // The binomial distribution is symmetrical with respect to p -> 1-p, - // k -> n-k switch p so that it is less than 0.5 - this allows for lower - // expected values we will just invert the result at the end - let p = if self.p <= 0.5 { - self.p - } else { - 1.0 - self.p - }; - - let result; - let q = 1. - p; - - // For small n * min(p, 1 - p), the BINV algorithm based on the inverse - // transformation of the binomial distribution is efficient. Otherwise, - // the BTPE algorithm is used. - // - // Voratas Kachitvichyanukul and Bruce W. Schmeiser. 1988. Binomial - // random variate generation. Commun. ACM 31, 2 (February 1988), - // 216-222. http://dx.doi.org/10.1145/42372.42381 - - // Threshold for prefering the BINV algorithm. The paper suggests 10, - // Ranlib uses 30, and GSL uses 14. - const BINV_THRESHOLD: f64 = 10.; - - if (self.n as f64) * p < BINV_THRESHOLD && - self.n <= (::std::i32::MAX as u64) { - // Use the BINV algorithm. - let s = p / q; - let a = ((self.n + 1) as f64) * s; - let mut r = q.powi(self.n as i32); - let mut u: f64 = rng.gen(); - let mut x = 0; - while u > r as f64 { - u -= r; - x += 1; - r *= a / (x as f64) - s; - } - result = x; - } else { - // Use the BTPE algorithm. - - // Threshold for using the squeeze algorithm. This can be freely - // chosen based on performance. Ranlib and GSL use 20. - const SQUEEZE_THRESHOLD: i64 = 20; - - // Step 0: Calculate constants as functions of `n` and `p`. - let n = self.n as f64; - let np = n * p; - let npq = np * q; - let f_m = np + p; - let m = f64_to_i64(f_m); - // radius of triangle region, since height=1 also area of region - let p1 = (2.195 * npq.sqrt() - 4.6 * q).floor() + 0.5; - // tip of triangle - let x_m = (m as f64) + 0.5; - // left edge of triangle - let x_l = x_m - p1; - // right edge of triangle - let x_r = x_m + p1; - let c = 0.134 + 20.5 / (15.3 + (m as f64)); - // p1 + area of parallelogram region - let p2 = p1 * (1. + 2. * c); - - fn lambda(a: f64) -> f64 { - a * (1. + 0.5 * a) - } - - let lambda_l = lambda((f_m - x_l) / (f_m - x_l * p)); - let lambda_r = lambda((x_r - f_m) / (x_r * q)); - // p1 + area of left tail - let p3 = p2 + c / lambda_l; - // p1 + area of right tail - let p4 = p3 + c / lambda_r; - - // return value - let mut y: i64; - - let gen_u = Uniform::new(0., p4); - let gen_v = Uniform::new(0., 1.); - - loop { - // Step 1: Generate `u` for selecting the region. If region 1 is - // selected, generate a triangularly distributed variate. - let u = gen_u.sample(rng); - let mut v = gen_v.sample(rng); - if !(u > p1) { - y = f64_to_i64(x_m - p1 * v + u); - break; - } - - if !(u > p2) { - // Step 2: Region 2, parallelograms. Check if region 2 is - // used. If so, generate `y`. - let x = x_l + (u - p1) / c; - v = v * c + 1.0 - (x - x_m).abs() / p1; - if v > 1. { - continue; - } else { - y = f64_to_i64(x); - } - } else if !(u > p3) { - // Step 3: Region 3, left exponential tail. - y = f64_to_i64(x_l + v.ln() / lambda_l); - if y < 0 { - continue; - } else { - v *= (u - p2) * lambda_l; - } - } else { - // Step 4: Region 4, right exponential tail. - y = f64_to_i64(x_r - v.ln() / lambda_r); - if y > 0 && (y as u64) > self.n { - continue; - } else { - v *= (u - p3) * lambda_r; - } - } - - // Step 5: Acceptance/rejection comparison. - - // Step 5.0: Test for appropriate method of evaluating f(y). - let k = (y - m).abs(); - if !(k > SQUEEZE_THRESHOLD && (k as f64) < 0.5 * npq - 1.) { - // Step 5.1: Evaluate f(y) via the recursive relationship. Start the - // search from the mode. - let s = p / q; - let a = s * (n + 1.); - let mut f = 1.0; - if m < y { - let mut i = m; - loop { - i += 1; - f *= a / (i as f64) - s; - if i == y { - break; - } - } - } else if m > y { - let mut i = y; - loop { - i += 1; - f /= a / (i as f64) - s; - if i == m { - break; - } - } - } - if v > f { - continue; - } else { - break; - } - } - - // Step 5.2: Squeezing. Check the value of ln(v) againts upper and - // lower bound of ln(f(y)). - let k = k as f64; - let rho = (k / npq) * ((k * (k / 3. + 0.625) + 1./6.) / npq + 0.5); - let t = -0.5 * k*k / npq; - let alpha = v.ln(); - if alpha < t - rho { - break; - } - if alpha > t + rho { - continue; - } - - // Step 5.3: Final acceptance/rejection test. - let x1 = (y + 1) as f64; - let f1 = (m + 1) as f64; - let z = (f64_to_i64(n) + 1 - m) as f64; - let w = (f64_to_i64(n) - y + 1) as f64; - - fn stirling(a: f64) -> f64 { - let a2 = a * a; - (13860. - (462. - (132. - (99. - 140. / a2) / a2) / a2) / a2) / a / 166320. - } - - if alpha > x_m * (f1 / x1).ln() - + (n - (m as f64) + 0.5) * (z / w).ln() - + ((y - m) as f64) * (w * p / (x1 * q)).ln() - // We use the signs from the GSL implementation, which are - // different than the ones in the reference. According to - // the GSL authors, the new signs were verified to be - // correct by one of the original designers of the - // algorithm. - + stirling(f1) + stirling(z) - stirling(x1) - stirling(w) - { - continue; - } - - break; - } - assert!(y >= 0); - result = y as u64; - } - - // Invert the result for p < 0.5. - if p != self.p { - self.n - result - } else { - result - } - } -} - -#[cfg(test)] -mod test { - use rand::Rng; - use crate::Distribution; - use super::Binomial; - - fn test_binomial_mean_and_variance(n: u64, p: f64, rng: &mut R) { - let binomial = Binomial::new(n, p).unwrap(); - - let expected_mean = n as f64 * p; - let expected_variance = n as f64 * p * (1.0 - p); - - let mut results = [0.0; 1000]; - for i in results.iter_mut() { *i = binomial.sample(rng) as f64; } - - let mean = results.iter().sum::() / results.len() as f64; - assert!((mean as f64 - expected_mean).abs() < expected_mean / 50.0); - - let variance = - results.iter().map(|x| (x - mean) * (x - mean)).sum::() - / results.len() as f64; - assert!((variance - expected_variance).abs() < expected_variance / 10.0); - } - - #[test] - fn test_binomial() { - let mut rng = crate::test::rng(351); - test_binomial_mean_and_variance(150, 0.1, &mut rng); - test_binomial_mean_and_variance(70, 0.6, &mut rng); - test_binomial_mean_and_variance(40, 0.5, &mut rng); - test_binomial_mean_and_variance(20, 0.7, &mut rng); - test_binomial_mean_and_variance(20, 0.5, &mut rng); - } - - #[test] - fn test_binomial_end_points() { - let mut rng = crate::test::rng(352); - assert_eq!(rng.sample(Binomial::new(20, 0.0).unwrap()), 0); - assert_eq!(rng.sample(Binomial::new(20, 1.0).unwrap()), 20); - } - - #[test] - #[should_panic] - fn test_binomial_invalid_lambda_neg() { - Binomial::new(20, -10.0).unwrap(); - } -} diff --git a/rand/rand_distr/src/cauchy.rs b/rand/rand_distr/src/cauchy.rs deleted file mode 100644 index 6b0e7c6..0000000 --- a/rand/rand_distr/src/cauchy.rs +++ /dev/null @@ -1,120 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// Copyright 2016-2017 The Rust Project Developers. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The Cauchy distribution. - -use rand::Rng; -use crate::{Distribution, Standard}; -use crate::utils::Float; - -/// The Cauchy distribution `Cauchy(median, scale)`. -/// -/// This distribution has a density function: -/// `f(x) = 1 / (pi * scale * (1 + ((x - median) / scale)^2))` -/// -/// # Example -/// -/// ``` -/// use rand_distr::{Cauchy, Distribution}; -/// -/// let cau = Cauchy::new(2.0, 5.0).unwrap(); -/// let v = cau.sample(&mut rand::thread_rng()); -/// println!("{} is from a Cauchy(2, 5) distribution", v); -/// ``` -#[derive(Clone, Copy, Debug)] -pub struct Cauchy { - median: N, - scale: N, -} - -/// Error type returned from `Cauchy::new`. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Error { - /// `scale <= 0` or `nan`. - ScaleTooSmall, -} - -impl Cauchy -where Standard: Distribution -{ - /// Construct a new `Cauchy` with the given shape parameters - /// `median` the peak location and `scale` the scale factor. - pub fn new(median: N, scale: N) -> Result, Error> { - if !(scale > N::from(0.0)) { - return Err(Error::ScaleTooSmall); - } - Ok(Cauchy { - median, - scale - }) - } -} - -impl Distribution for Cauchy -where Standard: Distribution -{ - fn sample(&self, rng: &mut R) -> N { - // sample from [0, 1) - let x = Standard.sample(rng); - // get standard cauchy random number - // note that Ο€/2 is not exactly representable, even if x=0.5 the result is finite - let comp_dev = (N::pi() * x).tan(); - // shift and scale according to parameters - self.median + self.scale * comp_dev - } -} - -#[cfg(test)] -mod test { - use crate::Distribution; - use super::Cauchy; - - fn median(mut numbers: &mut [f64]) -> f64 { - sort(&mut numbers); - let mid = numbers.len() / 2; - numbers[mid] - } - - fn sort(numbers: &mut [f64]) { - numbers.sort_by(|a, b| a.partial_cmp(b).unwrap()); - } - - #[test] - fn test_cauchy_averages() { - // NOTE: given that the variance and mean are undefined, - // this test does not have any rigorous statistical meaning. - let cauchy = Cauchy::new(10.0, 5.0).unwrap(); - let mut rng = crate::test::rng(123); - let mut numbers: [f64; 1000] = [0.0; 1000]; - let mut sum = 0.0; - for i in 0..1000 { - numbers[i] = cauchy.sample(&mut rng); - sum += numbers[i]; - } - let median = median(&mut numbers); - println!("Cauchy median: {}", median); - assert!((median - 10.0).abs() < 0.4); // not 100% certain, but probable enough - let mean = sum / 1000.0; - println!("Cauchy mean: {}", mean); - // for a Cauchy distribution the mean should not converge - assert!((mean - 10.0).abs() > 0.4); // not 100% certain, but probable enough - } - - #[test] - #[should_panic] - fn test_cauchy_invalid_scale_zero() { - Cauchy::new(0.0, 0.0).unwrap(); - } - - #[test] - #[should_panic] - fn test_cauchy_invalid_scale_neg() { - Cauchy::new(0.0, -10.0).unwrap(); - } -} diff --git a/rand/rand_distr/src/dirichlet.rs b/rand/rand_distr/src/dirichlet.rs deleted file mode 100644 index 71cf73c..0000000 --- a/rand/rand_distr/src/dirichlet.rs +++ /dev/null @@ -1,154 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// Copyright 2013 The Rust Project Developers. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The dirichlet distribution. - -use rand::Rng; -use crate::{Distribution, Gamma, StandardNormal, Exp1, Open01}; -use crate::utils::Float; - -/// The dirichelet distribution `Dirichlet(alpha)`. -/// -/// The Dirichlet distribution is a family of continuous multivariate -/// probability distributions parameterized by a vector alpha of positive reals. -/// It is a multivariate generalization of the beta distribution. -/// -/// # Example -/// -/// ``` -/// use rand::prelude::*; -/// use rand_distr::Dirichlet; -/// -/// let dirichlet = Dirichlet::new(vec![1.0, 2.0, 3.0]).unwrap(); -/// let samples = dirichlet.sample(&mut rand::thread_rng()); -/// println!("{:?} is from a Dirichlet([1.0, 2.0, 3.0]) distribution", samples); -/// ``` -#[derive(Clone, Debug)] -pub struct Dirichlet { - /// Concentration parameters (alpha) - alpha: Vec, -} - -/// Error type returned from `Dirchlet::new`. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Error { - /// `alpha.len() < 2`. - AlphaTooShort, - /// `alpha <= 0.0` or `nan`. - AlphaTooSmall, - /// `size < 2`. - SizeTooSmall, -} - -impl Dirichlet -where StandardNormal: Distribution, Exp1: Distribution, Open01: Distribution -{ - /// Construct a new `Dirichlet` with the given alpha parameter `alpha`. - /// - /// Requires `alpha.len() >= 2`. - #[inline] - pub fn new>>(alpha: V) -> Result, Error> { - let a = alpha.into(); - if a.len() < 2 { - return Err(Error::AlphaTooShort); - } - for &ai in &a { - if !(ai > N::from(0.0)) { - return Err(Error::AlphaTooSmall); - } - } - - Ok(Dirichlet { alpha: a }) - } - - /// Construct a new `Dirichlet` with the given shape parameter `alpha` and `size`. - /// - /// Requires `size >= 2`. - #[inline] - pub fn new_with_size(alpha: N, size: usize) -> Result, Error> { - if !(alpha > N::from(0.0)) { - return Err(Error::AlphaTooSmall); - } - if size < 2 { - return Err(Error::SizeTooSmall); - } - Ok(Dirichlet { - alpha: vec![alpha; size], - }) - } -} - -impl Distribution> for Dirichlet -where StandardNormal: Distribution, Exp1: Distribution, Open01: Distribution -{ - fn sample(&self, rng: &mut R) -> Vec { - let n = self.alpha.len(); - let mut samples = vec![N::from(0.0); n]; - let mut sum = N::from(0.0); - - for (s, &a) in samples.iter_mut().zip(self.alpha.iter()) { - let g = Gamma::new(a, N::from(1.0)).unwrap(); - *s = g.sample(rng); - sum += *s; - } - let invacc = N::from(1.0) / sum; - for s in samples.iter_mut() { - *s *= invacc; - } - samples - } -} - -#[cfg(test)] -mod test { - use super::Dirichlet; - use crate::Distribution; - - #[test] - fn test_dirichlet() { - let d = Dirichlet::new(vec![1.0, 2.0, 3.0]).unwrap(); - let mut rng = crate::test::rng(221); - let samples = d.sample(&mut rng); - let _: Vec = samples - .into_iter() - .map(|x| { - assert!(x > 0.0); - x - }) - .collect(); - } - - #[test] - fn test_dirichlet_with_param() { - let alpha = 0.5f64; - let size = 2; - let d = Dirichlet::new_with_size(alpha, size).unwrap(); - let mut rng = crate::test::rng(221); - let samples = d.sample(&mut rng); - let _: Vec = samples - .into_iter() - .map(|x| { - assert!(x > 0.0); - x - }) - .collect(); - } - - #[test] - #[should_panic] - fn test_dirichlet_invalid_length() { - Dirichlet::new_with_size(0.5f64, 1).unwrap(); - } - - #[test] - #[should_panic] - fn test_dirichlet_invalid_alpha() { - Dirichlet::new_with_size(0.0f64, 2).unwrap(); - } -} diff --git a/rand/rand_distr/src/exponential.rs b/rand/rand_distr/src/exponential.rs deleted file mode 100644 index 8322489..0000000 --- a/rand/rand_distr/src/exponential.rs +++ /dev/null @@ -1,145 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// Copyright 2013 The Rust Project Developers. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The exponential distribution. - -use rand::Rng; -use crate::{ziggurat_tables, Distribution}; -use crate::utils::{ziggurat, Float}; - -/// Samples floating-point numbers according to the exponential distribution, -/// with rate parameter `Ξ» = 1`. This is equivalent to `Exp::new(1.0)` or -/// sampling with `-rng.gen::().ln()`, but faster. -/// -/// See `Exp` for the general exponential distribution. -/// -/// Implemented via the ZIGNOR variant[^1] of the Ziggurat method. The exact -/// description in the paper was adjusted to use tables for the exponential -/// distribution rather than normal. -/// -/// [^1]: Jurgen A. Doornik (2005). [*An Improved Ziggurat Method to -/// Generate Normal Random Samples*]( -/// https://www.doornik.com/research/ziggurat.pdf). -/// Nuffield College, Oxford -/// -/// # Example -/// ``` -/// use rand::prelude::*; -/// use rand_distr::Exp1; -/// -/// let val: f64 = thread_rng().sample(Exp1); -/// println!("{}", val); -/// ``` -#[derive(Clone, Copy, Debug)] -pub struct Exp1; - -impl Distribution for Exp1 { - #[inline] - fn sample(&self, rng: &mut R) -> f32 { - // TODO: use optimal 32-bit implementation - let x: f64 = self.sample(rng); - x as f32 - } -} - -// This could be done via `-rng.gen::().ln()` but that is slower. -impl Distribution for Exp1 { - #[inline] - fn sample(&self, rng: &mut R) -> f64 { - #[inline] - fn pdf(x: f64) -> f64 { - (-x).exp() - } - #[inline] - fn zero_case(rng: &mut R, _u: f64) -> f64 { - ziggurat_tables::ZIG_EXP_R - rng.gen::().ln() - } - - ziggurat(rng, false, - &ziggurat_tables::ZIG_EXP_X, - &ziggurat_tables::ZIG_EXP_F, - pdf, zero_case) - } -} - -/// The exponential distribution `Exp(lambda)`. -/// -/// This distribution has density function: `f(x) = lambda * exp(-lambda * x)` -/// for `x > 0`. -/// -/// Note that [`Exp1`](crate::Exp1) is an optimised implementation for `lambda = 1`. -/// -/// # Example -/// -/// ``` -/// use rand_distr::{Exp, Distribution}; -/// -/// let exp = Exp::new(2.0).unwrap(); -/// let v = exp.sample(&mut rand::thread_rng()); -/// println!("{} is from a Exp(2) distribution", v); -/// ``` -#[derive(Clone, Copy, Debug)] -pub struct Exp { - /// `lambda` stored as `1/lambda`, since this is what we scale by. - lambda_inverse: N -} - -/// Error type returned from `Exp::new`. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Error { - /// `lambda <= 0` or `nan`. - LambdaTooSmall, -} - -impl Exp -where Exp1: Distribution -{ - /// Construct a new `Exp` with the given shape parameter - /// `lambda`. - #[inline] - pub fn new(lambda: N) -> Result, Error> { - if !(lambda > N::from(0.0)) { - return Err(Error::LambdaTooSmall); - } - Ok(Exp { lambda_inverse: N::from(1.0) / lambda }) - } -} - -impl Distribution for Exp -where Exp1: Distribution -{ - fn sample(&self, rng: &mut R) -> N { - rng.sample(Exp1) * self.lambda_inverse - } -} - -#[cfg(test)] -mod test { - use crate::Distribution; - use super::Exp; - - #[test] - fn test_exp() { - let exp = Exp::new(10.0).unwrap(); - let mut rng = crate::test::rng(221); - for _ in 0..1000 { - assert!(exp.sample(&mut rng) >= 0.0); - } - } - #[test] - #[should_panic] - fn test_exp_invalid_lambda_zero() { - Exp::new(0.0).unwrap(); - } - #[test] - #[should_panic] - fn test_exp_invalid_lambda_neg() { - Exp::new(-10.0).unwrap(); - } -} diff --git a/rand/rand_distr/src/gamma.rs b/rand/rand_distr/src/gamma.rs deleted file mode 100644 index 4018361..0000000 --- a/rand/rand_distr/src/gamma.rs +++ /dev/null @@ -1,485 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// Copyright 2013 The Rust Project Developers. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The Gamma and derived distributions. - -use self::GammaRepr::*; -use self::ChiSquaredRepr::*; - -use rand::Rng; -use crate::normal::StandardNormal; -use crate::{Distribution, Exp1, Exp, Open01}; -use crate::utils::Float; - -/// The Gamma distribution `Gamma(shape, scale)` distribution. -/// -/// The density function of this distribution is -/// -/// ```text -/// f(x) = x^(k - 1) * exp(-x / ΞΈ) / (Ξ“(k) * ΞΈ^k) -/// ``` -/// -/// where `Ξ“` is the Gamma function, `k` is the shape and `ΞΈ` is the -/// scale and both `k` and `ΞΈ` are strictly positive. -/// -/// The algorithm used is that described by Marsaglia & Tsang 2000[^1], -/// falling back to directly sampling from an Exponential for `shape -/// == 1`, and using the boosting technique described in that paper for -/// `shape < 1`. -/// -/// # Example -/// -/// ``` -/// use rand_distr::{Distribution, Gamma}; -/// -/// let gamma = Gamma::new(2.0, 5.0).unwrap(); -/// let v = gamma.sample(&mut rand::thread_rng()); -/// println!("{} is from a Gamma(2, 5) distribution", v); -/// ``` -/// -/// [^1]: George Marsaglia and Wai Wan Tsang. 2000. "A Simple Method for -/// Generating Gamma Variables" *ACM Trans. Math. Softw.* 26, 3 -/// (September 2000), 363-372. -/// DOI:[10.1145/358407.358414](https://doi.acm.org/10.1145/358407.358414) -#[derive(Clone, Copy, Debug)] -pub struct Gamma { - repr: GammaRepr, -} - -/// Error type returned from `Gamma::new`. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Error { - /// `shape <= 0` or `nan`. - ShapeTooSmall, - /// `scale <= 0` or `nan`. - ScaleTooSmall, - /// `1 / scale == 0`. - ScaleTooLarge, -} - -#[derive(Clone, Copy, Debug)] -enum GammaRepr { - Large(GammaLargeShape), - One(Exp), - Small(GammaSmallShape) -} - -// These two helpers could be made public, but saving the -// match-on-Gamma-enum branch from using them directly (e.g. if one -// knows that the shape is always > 1) doesn't appear to be much -// faster. - -/// Gamma distribution where the shape parameter is less than 1. -/// -/// Note, samples from this require a compulsory floating-point `pow` -/// call, which makes it significantly slower than sampling from a -/// gamma distribution where the shape parameter is greater than or -/// equal to 1. -/// -/// See `Gamma` for sampling from a Gamma distribution with general -/// shape parameters. -#[derive(Clone, Copy, Debug)] -struct GammaSmallShape { - inv_shape: N, - large_shape: GammaLargeShape -} - -/// Gamma distribution where the shape parameter is larger than 1. -/// -/// See `Gamma` for sampling from a Gamma distribution with general -/// shape parameters. -#[derive(Clone, Copy, Debug)] -struct GammaLargeShape { - scale: N, - c: N, - d: N -} - -impl Gamma -where StandardNormal: Distribution, Exp1: Distribution, Open01: Distribution -{ - /// Construct an object representing the `Gamma(shape, scale)` - /// distribution. - #[inline] - pub fn new(shape: N, scale: N) -> Result, Error> { - if !(shape > N::from(0.0)) { - return Err(Error::ShapeTooSmall); - } - if !(scale > N::from(0.0)) { - return Err(Error::ScaleTooSmall); - } - - let repr = if shape == N::from(1.0) { - One(Exp::new(N::from(1.0) / scale).map_err(|_| Error::ScaleTooLarge)?) - } else if shape < N::from(1.0) { - Small(GammaSmallShape::new_raw(shape, scale)) - } else { - Large(GammaLargeShape::new_raw(shape, scale)) - }; - Ok(Gamma { repr }) - } -} - -impl GammaSmallShape -where StandardNormal: Distribution, Open01: Distribution -{ - fn new_raw(shape: N, scale: N) -> GammaSmallShape { - GammaSmallShape { - inv_shape: N::from(1.0) / shape, - large_shape: GammaLargeShape::new_raw(shape + N::from(1.0), scale) - } - } -} - -impl GammaLargeShape -where StandardNormal: Distribution, Open01: Distribution -{ - fn new_raw(shape: N, scale: N) -> GammaLargeShape { - let d = shape - N::from(1. / 3.); - GammaLargeShape { - scale, - c: N::from(1.0) / (N::from(9.) * d).sqrt(), - d - } - } -} - -impl Distribution for Gamma -where StandardNormal: Distribution, Exp1: Distribution, Open01: Distribution -{ - fn sample(&self, rng: &mut R) -> N { - match self.repr { - Small(ref g) => g.sample(rng), - One(ref g) => g.sample(rng), - Large(ref g) => g.sample(rng), - } - } -} -impl Distribution for GammaSmallShape -where StandardNormal: Distribution, Open01: Distribution -{ - fn sample(&self, rng: &mut R) -> N { - let u: N = rng.sample(Open01); - - self.large_shape.sample(rng) * u.powf(self.inv_shape) - } -} -impl Distribution for GammaLargeShape -where StandardNormal: Distribution, Open01: Distribution -{ - fn sample(&self, rng: &mut R) -> N { - // Marsaglia & Tsang method, 2000 - loop { - let x: N = rng.sample(StandardNormal); - let v_cbrt = N::from(1.0) + self.c * x; - if v_cbrt <= N::from(0.0) { // a^3 <= 0 iff a <= 0 - continue - } - - let v = v_cbrt * v_cbrt * v_cbrt; - let u: N = rng.sample(Open01); - - let x_sqr = x * x; - if u < N::from(1.0) - N::from(0.0331) * x_sqr * x_sqr || - u.ln() < N::from(0.5) * x_sqr + self.d * (N::from(1.0) - v + v.ln()) - { - return self.d * v * self.scale - } - } - } -} - -/// The chi-squared distribution `χ²(k)`, where `k` is the degrees of -/// freedom. -/// -/// For `k > 0` integral, this distribution is the sum of the squares -/// of `k` independent standard normal random variables. For other -/// `k`, this uses the equivalent characterisation -/// `χ²(k) = Gamma(k/2, 2)`. -/// -/// # Example -/// -/// ``` -/// use rand_distr::{ChiSquared, Distribution}; -/// -/// let chi = ChiSquared::new(11.0).unwrap(); -/// let v = chi.sample(&mut rand::thread_rng()); -/// println!("{} is from a χ²(11) distribution", v) -/// ``` -#[derive(Clone, Copy, Debug)] -pub struct ChiSquared { - repr: ChiSquaredRepr, -} - -/// Error type returned from `ChiSquared::new` and `StudentT::new`. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum ChiSquaredError { - /// `0.5 * k <= 0` or `nan`. - DoFTooSmall, -} - -#[derive(Clone, Copy, Debug)] -enum ChiSquaredRepr { - // k == 1, Gamma(alpha, ..) is particularly slow for alpha < 1, - // e.g. when alpha = 1/2 as it would be for this case, so special- - // casing and using the definition of N(0,1)^2 is faster. - DoFExactlyOne, - DoFAnythingElse(Gamma), -} - -impl ChiSquared -where StandardNormal: Distribution, Exp1: Distribution, Open01: Distribution -{ - /// Create a new chi-squared distribution with degrees-of-freedom - /// `k`. - pub fn new(k: N) -> Result, ChiSquaredError> { - let repr = if k == N::from(1.0) { - DoFExactlyOne - } else { - if !(N::from(0.5) * k > N::from(0.0)) { - return Err(ChiSquaredError::DoFTooSmall); - } - DoFAnythingElse(Gamma::new(N::from(0.5) * k, N::from(2.0)).unwrap()) - }; - Ok(ChiSquared { repr }) - } -} -impl Distribution for ChiSquared -where StandardNormal: Distribution, Exp1: Distribution, Open01: Distribution -{ - fn sample(&self, rng: &mut R) -> N { - match self.repr { - DoFExactlyOne => { - // k == 1 => N(0,1)^2 - let norm: N = rng.sample(StandardNormal); - norm * norm - } - DoFAnythingElse(ref g) => g.sample(rng) - } - } -} - -/// The Fisher F distribution `F(m, n)`. -/// -/// This distribution is equivalent to the ratio of two normalised -/// chi-squared distributions, that is, `F(m,n) = (χ²(m)/m) / -/// (χ²(n)/n)`. -/// -/// # Example -/// -/// ``` -/// use rand_distr::{FisherF, Distribution}; -/// -/// let f = FisherF::new(2.0, 32.0).unwrap(); -/// let v = f.sample(&mut rand::thread_rng()); -/// println!("{} is from an F(2, 32) distribution", v) -/// ``` -#[derive(Clone, Copy, Debug)] -pub struct FisherF { - numer: ChiSquared, - denom: ChiSquared, - // denom_dof / numer_dof so that this can just be a straight - // multiplication, rather than a division. - dof_ratio: N, -} - -/// Error type returned from `FisherF::new`. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum FisherFError { - /// `m <= 0` or `nan`. - MTooSmall, - /// `n <= 0` or `nan`. - NTooSmall, -} - -impl FisherF -where StandardNormal: Distribution, Exp1: Distribution, Open01: Distribution -{ - /// Create a new `FisherF` distribution, with the given parameter. - pub fn new(m: N, n: N) -> Result, FisherFError> { - if !(m > N::from(0.0)) { - return Err(FisherFError::MTooSmall); - } - if !(n > N::from(0.0)) { - return Err(FisherFError::NTooSmall); - } - - Ok(FisherF { - numer: ChiSquared::new(m).unwrap(), - denom: ChiSquared::new(n).unwrap(), - dof_ratio: n / m - }) - } -} -impl Distribution for FisherF -where StandardNormal: Distribution, Exp1: Distribution, Open01: Distribution -{ - fn sample(&self, rng: &mut R) -> N { - self.numer.sample(rng) / self.denom.sample(rng) * self.dof_ratio - } -} - -/// The Student t distribution, `t(nu)`, where `nu` is the degrees of -/// freedom. -/// -/// # Example -/// -/// ``` -/// use rand_distr::{StudentT, Distribution}; -/// -/// let t = StudentT::new(11.0).unwrap(); -/// let v = t.sample(&mut rand::thread_rng()); -/// println!("{} is from a t(11) distribution", v) -/// ``` -#[derive(Clone, Copy, Debug)] -pub struct StudentT { - chi: ChiSquared, - dof: N -} - -impl StudentT -where StandardNormal: Distribution, Exp1: Distribution, Open01: Distribution -{ - /// Create a new Student t distribution with `n` degrees of - /// freedom. - pub fn new(n: N) -> Result, ChiSquaredError> { - Ok(StudentT { - chi: ChiSquared::new(n)?, - dof: n - }) - } -} -impl Distribution for StudentT -where StandardNormal: Distribution, Exp1: Distribution, Open01: Distribution -{ - fn sample(&self, rng: &mut R) -> N { - let norm: N = rng.sample(StandardNormal); - norm * (self.dof / self.chi.sample(rng)).sqrt() - } -} - -/// The Beta distribution with shape parameters `alpha` and `beta`. -/// -/// # Example -/// -/// ``` -/// use rand_distr::{Distribution, Beta}; -/// -/// let beta = Beta::new(2.0, 5.0).unwrap(); -/// let v = beta.sample(&mut rand::thread_rng()); -/// println!("{} is from a Beta(2, 5) distribution", v); -/// ``` -#[derive(Clone, Copy, Debug)] -pub struct Beta { - gamma_a: Gamma, - gamma_b: Gamma, -} - -/// Error type returned from `Beta::new`. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum BetaError { - /// `alpha <= 0` or `nan`. - AlphaTooSmall, - /// `beta <= 0` or `nan`. - BetaTooSmall, -} - -impl Beta -where StandardNormal: Distribution, Exp1: Distribution, Open01: Distribution -{ - /// Construct an object representing the `Beta(alpha, beta)` - /// distribution. - pub fn new(alpha: N, beta: N) -> Result, BetaError> { - Ok(Beta { - gamma_a: Gamma::new(alpha, N::from(1.)) - .map_err(|_| BetaError::AlphaTooSmall)?, - gamma_b: Gamma::new(beta, N::from(1.)) - .map_err(|_| BetaError::BetaTooSmall)?, - }) - } -} - -impl Distribution for Beta -where StandardNormal: Distribution, Exp1: Distribution, Open01: Distribution -{ - fn sample(&self, rng: &mut R) -> N { - let x = self.gamma_a.sample(rng); - let y = self.gamma_b.sample(rng); - x / (x + y) - } -} - -#[cfg(test)] -mod test { - use crate::Distribution; - use super::{Beta, ChiSquared, StudentT, FisherF}; - - #[test] - fn test_chi_squared_one() { - let chi = ChiSquared::new(1.0).unwrap(); - let mut rng = crate::test::rng(201); - for _ in 0..1000 { - chi.sample(&mut rng); - } - } - #[test] - fn test_chi_squared_small() { - let chi = ChiSquared::new(0.5).unwrap(); - let mut rng = crate::test::rng(202); - for _ in 0..1000 { - chi.sample(&mut rng); - } - } - #[test] - fn test_chi_squared_large() { - let chi = ChiSquared::new(30.0).unwrap(); - let mut rng = crate::test::rng(203); - for _ in 0..1000 { - chi.sample(&mut rng); - } - } - #[test] - #[should_panic] - fn test_chi_squared_invalid_dof() { - ChiSquared::new(-1.0).unwrap(); - } - - #[test] - fn test_f() { - let f = FisherF::new(2.0, 32.0).unwrap(); - let mut rng = crate::test::rng(204); - for _ in 0..1000 { - f.sample(&mut rng); - } - } - - #[test] - fn test_t() { - let t = StudentT::new(11.0).unwrap(); - let mut rng = crate::test::rng(205); - for _ in 0..1000 { - t.sample(&mut rng); - } - } - - #[test] - fn test_beta() { - let beta = Beta::new(1.0, 2.0).unwrap(); - let mut rng = crate::test::rng(201); - for _ in 0..1000 { - beta.sample(&mut rng); - } - } - - #[test] - #[should_panic] - fn test_beta_invalid_dof() { - Beta::new(0., 0.).unwrap(); - } -} diff --git a/rand/rand_distr/src/lib.rs b/rand/rand_distr/src/lib.rs deleted file mode 100644 index baf65ed..0000000 --- a/rand/rand_distr/src/lib.rs +++ /dev/null @@ -1,134 +0,0 @@ -// Copyright 2019 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#![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)] - -#![allow(clippy::excessive_precision, clippy::float_cmp, clippy::unreadable_literal)] -#![allow(clippy::neg_cmp_op_on_partial_ord)] // suggested fix too verbose - -//! Generating random samples from probability distributions. -//! -//! ## Re-exports -//! -//! This crate is a super-set of the [`rand::distributions`] module. See the -//! [`rand::distributions`] module documentation for an overview of the core -//! [`Distribution`] trait and implementations. -//! -//! The following are re-exported: -//! -//! - The [`Distribution`] trait and [`DistIter`] helper type -//! - The [`Standard`], [`Alphanumeric`], [`Uniform`], [`OpenClosed01`], [`Open01`] and [`Bernoulli`] distributions -//! - The [`weighted`] sub-module -//! -//! ## Distributions -//! -//! This crate provides the following probability distributions: -//! -//! - Related to real-valued quantities that grow linearly -//! (e.g. errors, offsets): -//! - [`Normal`] distribution, and [`StandardNormal`] as a primitive -//! - [`Cauchy`] distribution -//! - Related to Bernoulli trials (yes/no events, with a given probability): -//! - [`Binomial`] distribution -//! - Related to positive real-valued quantities that grow exponentially -//! (e.g. prices, incomes, populations): -//! - [`LogNormal`] distribution -//! - Related to the occurrence of independent events at a given rate: -//! - [`Pareto`] distribution -//! - [`Poisson`] distribution -//! - [`Exp`]onential distribution, and [`Exp1`] as a primitive -//! - [`Weibull`] distribution -//! - Gamma and derived distributions: -//! - [`Gamma`] distribution -//! - [`ChiSquared`] distribution -//! - [`StudentT`] distribution -//! - [`FisherF`] distribution -//! - Triangular distribution: -//! - [`Beta`] distribution -//! - [`Triangular`] distribution -//! - Multivariate probability distributions -//! - [`Dirichlet`] distribution -//! - [`UnitSphere`] distribution -//! - [`UnitBall`] distribution -//! - [`UnitCircle`] distribution -//! - [`UnitDisc`] distribution - -pub use rand::distributions::{Distribution, DistIter, Standard, - Alphanumeric, Uniform, OpenClosed01, Open01, Bernoulli, uniform, weighted}; - -pub use self::unit_sphere::UnitSphere; -pub use self::unit_ball::UnitBall; -pub use self::unit_circle::UnitCircle; -pub use self::unit_disc::UnitDisc; -pub use self::gamma::{Gamma, Error as GammaError, ChiSquared, ChiSquaredError, - FisherF, FisherFError, StudentT, Beta, BetaError}; -pub use self::normal::{Normal, Error as NormalError, LogNormal, StandardNormal}; -pub use self::exponential::{Exp, Error as ExpError, Exp1}; -pub use self::pareto::{Pareto, Error as ParetoError}; -pub use self::pert::{Pert, PertError}; -pub use self::poisson::{Poisson, Error as PoissonError}; -pub use self::binomial::{Binomial, Error as BinomialError}; -pub use self::cauchy::{Cauchy, Error as CauchyError}; -pub use self::dirichlet::{Dirichlet, Error as DirichletError}; -pub use self::triangular::{Triangular, TriangularError}; -pub use self::weibull::{Weibull, Error as WeibullError}; -pub use self::utils::Float; - -mod unit_sphere; -mod unit_ball; -mod unit_circle; -mod unit_disc; -mod gamma; -mod normal; -mod exponential; -mod pareto; -mod pert; -mod poisson; -mod binomial; -mod cauchy; -mod dirichlet; -mod triangular; -mod weibull; -mod utils; -mod ziggurat_tables; - -#[cfg(test)] -mod test { - // Notes on testing - // - // Testing random number distributions correctly is hard. The following - // testing is desired: - // - // - Construction: test initialisation with a few valid parameter sets. - // - Erroneous usage: test that incorrect usage generates an error. - // - Vector: test that usage with fixed inputs (including RNG) generates a - // fixed output sequence on all platforms. - // - Correctness at fixed points (optional): using a specific mock RNG, - // check that specific values are sampled (e.g. end-points and median of - // distribution). - // - Correctness of PDF (extra): generate a histogram of samples within a - // certain range, and check this approximates the PDF. These tests are - // expected to be expensive, and should be behind a feature-gate. - // - // TODO: Vector and correctness tests are largely absent so far. - // NOTE: Some distributions have tests checking only that samples can be - // generated. This is redundant with vector and correctness tests. - - /// Construct a deterministic RNG with the given seed - pub fn rng(seed: u64) -> impl rand::RngCore { - // For tests, we want a statistically good, fast, reproducible RNG. - // PCG32 will do fine, and will be easy to embed if we ever need to. - const INC: u64 = 11634580027462260723; - rand_pcg::Pcg32::new(seed, INC) - } -} diff --git a/rand/rand_distr/src/normal.rs b/rand/rand_distr/src/normal.rs deleted file mode 100644 index 882754f..0000000 --- a/rand/rand_distr/src/normal.rs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// Copyright 2013 The Rust Project Developers. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The normal and derived distributions. - -use rand::Rng; -use crate::{ziggurat_tables, Distribution, Open01}; -use crate::utils::{ziggurat, Float}; - -/// Samples floating-point numbers according to the normal distribution -/// `N(0, 1)` (a.k.a. a standard normal, or Gaussian). This is equivalent to -/// `Normal::new(0.0, 1.0)` but faster. -/// -/// See `Normal` for the general normal distribution. -/// -/// Implemented via the ZIGNOR variant[^1] of the Ziggurat method. -/// -/// [^1]: Jurgen A. Doornik (2005). [*An Improved Ziggurat Method to -/// Generate Normal Random Samples*]( -/// https://www.doornik.com/research/ziggurat.pdf). -/// Nuffield College, Oxford -/// -/// # Example -/// ``` -/// use rand::prelude::*; -/// use rand_distr::StandardNormal; -/// -/// let val: f64 = thread_rng().sample(StandardNormal); -/// println!("{}", val); -/// ``` -#[derive(Clone, Copy, Debug)] -pub struct StandardNormal; - -impl Distribution for StandardNormal { - #[inline] - fn sample(&self, rng: &mut R) -> f32 { - // TODO: use optimal 32-bit implementation - let x: f64 = self.sample(rng); - x as f32 - } -} - -impl Distribution for StandardNormal { - fn sample(&self, rng: &mut R) -> f64 { - #[inline] - fn pdf(x: f64) -> f64 { - (-x*x/2.0).exp() - } - #[inline] - fn zero_case(rng: &mut R, u: f64) -> f64 { - // compute a random number in the tail by hand - - // strange initial conditions, because the loop is not - // do-while, so the condition should be true on the first - // run, they get overwritten anyway (0 < 1, so these are - // good). - let mut x = 1.0f64; - let mut y = 0.0f64; - - while -2.0 * y < x * x { - let x_: f64 = rng.sample(Open01); - let y_: f64 = rng.sample(Open01); - - x = x_.ln() / ziggurat_tables::ZIG_NORM_R; - y = y_.ln(); - } - - if u < 0.0 { x - ziggurat_tables::ZIG_NORM_R } else { ziggurat_tables::ZIG_NORM_R - x } - } - - ziggurat(rng, true, // this is symmetric - &ziggurat_tables::ZIG_NORM_X, - &ziggurat_tables::ZIG_NORM_F, - pdf, zero_case) - } -} - -/// The normal distribution `N(mean, std_dev**2)`. -/// -/// This uses the ZIGNOR variant of the Ziggurat method, see [`StandardNormal`] -/// for more details. -/// -/// Note that [`StandardNormal`] is an optimised implementation for mean 0, and -/// standard deviation 1. -/// -/// # Example -/// -/// ``` -/// use rand_distr::{Normal, Distribution}; -/// -/// // mean 2, standard deviation 3 -/// let normal = Normal::new(2.0, 3.0).unwrap(); -/// let v = normal.sample(&mut rand::thread_rng()); -/// println!("{} is from a N(2, 9) distribution", v) -/// ``` -/// -/// [`StandardNormal`]: crate::StandardNormal -#[derive(Clone, Copy, Debug)] -pub struct Normal { - mean: N, - std_dev: N, -} - -/// Error type returned from `Normal::new` and `LogNormal::new`. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Error { - /// `std_dev < 0` or `nan`. - StdDevTooSmall, -} - -impl Normal -where StandardNormal: Distribution -{ - /// Construct a new `Normal` distribution with the given mean and - /// standard deviation. - #[inline] - pub fn new(mean: N, std_dev: N) -> Result, Error> { - if !(std_dev >= N::from(0.0)) { - return Err(Error::StdDevTooSmall); - } - Ok(Normal { - mean, - std_dev - }) - } -} - -impl Distribution for Normal -where StandardNormal: Distribution -{ - fn sample(&self, rng: &mut R) -> N { - let n: N = rng.sample(StandardNormal); - self.mean + self.std_dev * n - } -} - - -/// The log-normal distribution `ln N(mean, std_dev**2)`. -/// -/// If `X` is log-normal distributed, then `ln(X)` is `N(mean, std_dev**2)` -/// distributed. -/// -/// # Example -/// -/// ``` -/// use rand_distr::{LogNormal, Distribution}; -/// -/// // mean 2, standard deviation 3 -/// let log_normal = LogNormal::new(2.0, 3.0).unwrap(); -/// let v = log_normal.sample(&mut rand::thread_rng()); -/// println!("{} is from an ln N(2, 9) distribution", v) -/// ``` -#[derive(Clone, Copy, Debug)] -pub struct LogNormal { - norm: Normal -} - -impl LogNormal -where StandardNormal: Distribution -{ - /// Construct a new `LogNormal` distribution with the given mean - /// and standard deviation of the logarithm of the distribution. - #[inline] - pub fn new(mean: N, std_dev: N) -> Result, Error> { - if !(std_dev >= N::from(0.0)) { - return Err(Error::StdDevTooSmall); - } - Ok(LogNormal { norm: Normal::new(mean, std_dev).unwrap() }) - } -} - -impl Distribution for LogNormal -where StandardNormal: Distribution -{ - fn sample(&self, rng: &mut R) -> N { - self.norm.sample(rng).exp() - } -} - -#[cfg(test)] -mod tests { - use crate::Distribution; - use super::{Normal, LogNormal}; - - #[test] - fn test_normal() { - let norm = Normal::new(10.0, 10.0).unwrap(); - let mut rng = crate::test::rng(210); - for _ in 0..1000 { - norm.sample(&mut rng); - } - } - #[test] - #[should_panic] - fn test_normal_invalid_sd() { - Normal::new(10.0, -1.0).unwrap(); - } - - - #[test] - fn test_log_normal() { - let lnorm = LogNormal::new(10.0, 10.0).unwrap(); - let mut rng = crate::test::rng(211); - for _ in 0..1000 { - lnorm.sample(&mut rng); - } - } - #[test] - #[should_panic] - fn test_log_normal_invalid_sd() { - LogNormal::new(10.0, -1.0).unwrap(); - } -} diff --git a/rand/rand_distr/src/pareto.rs b/rand/rand_distr/src/pareto.rs deleted file mode 100644 index 33ea382..0000000 --- a/rand/rand_distr/src/pareto.rs +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The Pareto distribution. - -use rand::Rng; -use crate::{Distribution, OpenClosed01}; -use crate::utils::Float; - -/// Samples floating-point numbers according to the Pareto distribution -/// -/// # Example -/// ``` -/// use rand::prelude::*; -/// use rand_distr::Pareto; -/// -/// let val: f64 = thread_rng().sample(Pareto::new(1., 2.).unwrap()); -/// println!("{}", val); -/// ``` -#[derive(Clone, Copy, Debug)] -pub struct Pareto { - scale: N, - inv_neg_shape: N, -} - -/// Error type returned from `Pareto::new`. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Error { - /// `scale <= 0` or `nan`. - ScaleTooSmall, - /// `shape <= 0` or `nan`. - ShapeTooSmall, -} - -impl Pareto -where OpenClosed01: Distribution -{ - /// Construct a new Pareto distribution with given `scale` and `shape`. - /// - /// In the literature, `scale` is commonly written as xm or k and - /// `shape` is often written as Ξ±. - pub fn new(scale: N, shape: N) -> Result, Error> { - if !(scale > N::from(0.0)) { - return Err(Error::ScaleTooSmall); - } - if !(shape > N::from(0.0)) { - return Err(Error::ShapeTooSmall); - } - Ok(Pareto { scale, inv_neg_shape: N::from(-1.0) / shape }) - } -} - -impl Distribution for Pareto -where OpenClosed01: Distribution -{ - fn sample(&self, rng: &mut R) -> N { - let u: N = OpenClosed01.sample(rng); - self.scale * u.powf(self.inv_neg_shape) - } -} - -#[cfg(test)] -mod tests { - use crate::Distribution; - use super::Pareto; - - #[test] - #[should_panic] - fn invalid() { - Pareto::new(0., 0.).unwrap(); - } - - #[test] - fn sample() { - let scale = 1.0; - let shape = 2.0; - let d = Pareto::new(scale, shape).unwrap(); - let mut rng = crate::test::rng(1); - for _ in 0..1000 { - let r = d.sample(&mut rng); - assert!(r >= scale); - } - } -} diff --git a/rand/rand_distr/src/pert.rs b/rand/rand_distr/src/pert.rs deleted file mode 100644 index 040cd05..0000000 --- a/rand/rand_distr/src/pert.rs +++ /dev/null @@ -1,132 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. -//! The PERT distribution. - -use rand::Rng; -use crate::{Distribution, Beta, StandardNormal, Exp1, Open01}; -use crate::utils::Float; - -/// The PERT distribution. -/// -/// Similar to the [`Triangular`] distribution, the PERT distribution is -/// parameterised by a range and a mode within that range. Unlike the -/// [`Triangular`] distribution, the probability density function of the PERT -/// distribution is smooth, with a configurable weighting around the mode. -/// -/// # Example -/// -/// ```rust -/// use rand_distr::{Pert, Distribution}; -/// -/// let d = Pert::new(0., 5., 2.5).unwrap(); -/// let v = d.sample(&mut rand::thread_rng()); -/// println!("{} is from a PERT distribution", v); -/// ``` -/// -/// [`Triangular`]: crate::Triangular -#[derive(Clone, Copy, Debug)] -pub struct Pert { - min: N, - range: N, - beta: Beta, -} - -/// Error type returned from [`Pert`] constructors. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum PertError { - /// `max < min` or `min` or `max` is NaN. - RangeTooSmall, - /// `mode < min` or `mode > max` or `mode` is NaN. - ModeRange, - /// `shape < 0` or `shape` is NaN - ShapeTooSmall, -} - -impl Pert -where StandardNormal: Distribution, Exp1: Distribution, Open01: Distribution -{ - /// Set up the PERT distribution with defined `min`, `max` and `mode`. - /// - /// This is equivalent to calling `Pert::new_shape` with `shape == 4.0`. - #[inline] - pub fn new(min: N, max: N, mode: N) -> Result, PertError> { - Pert::new_with_shape(min, max, mode, N::from(4.)) - } - - /// Set up the PERT distribution with defined `min`, `max`, `mode` and - /// `shape`. - pub fn new_with_shape(min: N, max: N, mode: N, shape: N) -> Result, PertError> { - if !(max > min) { - return Err(PertError::RangeTooSmall); - } - if !(mode >= min && max >= mode) { - return Err(PertError::ModeRange); - } - if !(shape >= N::from(0.)) { - return Err(PertError::ShapeTooSmall); - } - - let range = max - min; - let mu = (min + max + shape * mode) / (shape + N::from(2.)); - let v = if mu == mode { - shape * N::from(0.5) + N::from(1.) - } else { - (mu - min) * (N::from(2.) * mode - min - max) - / ((mode - mu) * (max - min)) - }; - let w = v * (max - mu) / (mu - min); - let beta = Beta::new(v, w).map_err(|_| PertError::RangeTooSmall)?; - Ok(Pert{ min, range, beta }) - } -} - -impl Distribution for Pert -where StandardNormal: Distribution, Exp1: Distribution, Open01: Distribution -{ - #[inline] - fn sample(&self, rng: &mut R) -> N { - self.beta.sample(rng) * self.range + self.min - } -} - -#[cfg(test)] -mod test { - use std::f64; - use super::*; - - #[test] - fn test_pert() { - for &(min, max, mode) in &[ - (-1., 1., 0.), - (1., 2., 1.), - (5., 25., 25.), - ] { - let _distr = Pert::new(min, max, mode).unwrap(); - // TODO: test correctness - } - - for &(min, max, mode) in &[ - (-1., 1., 2.), - (-1., 1., -2.), - (2., 1., 1.), - ] { - assert!(Pert::new(min, max, mode).is_err()); - } - } - - #[test] - fn value_stability() { - let rng = crate::test::rng(860); - let distr = Pert::new(2., 10., 3.).unwrap(); // mean = 4, var = 12/7 - let seq = distr.sample_iter(rng).take(5).collect::>(); - println!("seq: {:?}", seq); - let expected = vec![4.631484136029422, 3.307201472321789, - 3.29995019556348, 3.66835483991721, 3.514246139933899]; - assert!(seq == expected); - } -} diff --git a/rand/rand_distr/src/poisson.rs b/rand/rand_distr/src/poisson.rs deleted file mode 100644 index 4f4a0b7..0000000 --- a/rand/rand_distr/src/poisson.rs +++ /dev/null @@ -1,233 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// Copyright 2016-2017 The Rust Project Developers. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The Poisson distribution. - -use rand::Rng; -use crate::{Distribution, Cauchy, Standard}; -use crate::utils::Float; - -/// The Poisson distribution `Poisson(lambda)`. -/// -/// This distribution has a density function: -/// `f(k) = lambda^k * exp(-lambda) / k!` for `k >= 0`. -/// -/// # Example -/// -/// ``` -/// use rand_distr::{Poisson, Distribution}; -/// -/// let poi = Poisson::new(2.0).unwrap(); -/// let v: u64 = poi.sample(&mut rand::thread_rng()); -/// println!("{} is from a Poisson(2) distribution", v); -/// ``` -#[derive(Clone, Copy, Debug)] -pub struct Poisson { - lambda: N, - // precalculated values - exp_lambda: N, - log_lambda: N, - sqrt_2lambda: N, - magic_val: N, -} - -/// Error type returned from `Poisson::new`. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Error { - /// `lambda <= 0` or `nan`. - ShapeTooSmall, -} - -impl Poisson -where Standard: Distribution -{ - /// Construct a new `Poisson` with the given shape parameter - /// `lambda`. - pub fn new(lambda: N) -> Result, Error> { - if !(lambda > N::from(0.0)) { - return Err(Error::ShapeTooSmall); - } - let log_lambda = lambda.ln(); - Ok(Poisson { - lambda, - exp_lambda: (-lambda).exp(), - log_lambda, - sqrt_2lambda: (N::from(2.0) * lambda).sqrt(), - magic_val: lambda * log_lambda - (N::from(1.0) + lambda).log_gamma(), - }) - } -} - -impl Distribution for Poisson -where Standard: Distribution -{ - #[inline] - fn sample(&self, rng: &mut R) -> N { - // using the algorithm from Numerical Recipes in C - - // for low expected values use the Knuth method - if self.lambda < N::from(12.0) { - let mut result = N::from(0.); - let mut p = N::from(1.0); - while p > self.exp_lambda { - p *= rng.gen::(); - result += N::from(1.); - } - result - N::from(1.) - } - // high expected values - rejection method - else { - // we use the Cauchy distribution as the comparison distribution - // f(x) ~ 1/(1+x^2) - let cauchy = Cauchy::new(N::from(0.0), N::from(1.0)).unwrap(); - let mut result; - - loop { - let mut comp_dev; - - loop { - // draw from the Cauchy distribution - comp_dev = rng.sample(cauchy); - // shift the peak of the comparison ditribution - result = self.sqrt_2lambda * comp_dev + self.lambda; - // repeat the drawing until we are in the range of possible values - if result >= N::from(0.0) { - break; - } - } - // now the result is a random variable greater than 0 with Cauchy distribution - // the result should be an integer value - result = result.floor(); - - // this is the ratio of the Poisson distribution to the comparison distribution - // the magic value scales the distribution function to a range of approximately 0-1 - // since it is not exact, we multiply the ratio by 0.9 to avoid ratios greater than 1 - // this doesn't change the resulting distribution, only increases the rate of failed drawings - let check = N::from(0.9) * (N::from(1.0) + comp_dev * comp_dev) - * (result * self.log_lambda - (N::from(1.0) + result).log_gamma() - self.magic_val).exp(); - - // check with uniform random value - if below the threshold, we are within the target distribution - if rng.gen::() <= check { - break; - } - } - result - } - } -} - -impl Distribution for Poisson -where Standard: Distribution -{ - #[inline] - fn sample(&self, rng: &mut R) -> u64 { - let result: N = self.sample(rng); - result.to_u64().unwrap() - } -} - -#[cfg(test)] -mod test { - use crate::Distribution; - use super::Poisson; - - #[test] - fn test_poisson_10() { - let poisson = Poisson::new(10.0).unwrap(); - let mut rng = crate::test::rng(123); - let mut sum_u64 = 0; - let mut sum_f64 = 0.; - for _ in 0..1000 { - let s_u64: u64 = poisson.sample(&mut rng); - let s_f64: f64 = poisson.sample(&mut rng); - sum_u64 += s_u64; - sum_f64 += s_f64; - } - let avg_u64 = (sum_u64 as f64) / 1000.0; - let avg_f64 = sum_f64 / 1000.0; - println!("Poisson averages: {} (u64) {} (f64)", avg_u64, avg_f64); - for &avg in &[avg_u64, avg_f64] { - assert!((avg - 10.0).abs() < 0.5); // not 100% certain, but probable enough - } - } - - #[test] - fn test_poisson_15() { - // Take the 'high expected values' path - let poisson = Poisson::new(15.0).unwrap(); - let mut rng = crate::test::rng(123); - let mut sum_u64 = 0; - let mut sum_f64 = 0.; - for _ in 0..1000 { - let s_u64: u64 = poisson.sample(&mut rng); - let s_f64: f64 = poisson.sample(&mut rng); - sum_u64 += s_u64; - sum_f64 += s_f64; - } - let avg_u64 = (sum_u64 as f64) / 1000.0; - let avg_f64 = sum_f64 / 1000.0; - println!("Poisson average: {} (u64) {} (f64)", avg_u64, avg_f64); - for &avg in &[avg_u64, avg_f64] { - assert!((avg - 15.0).abs() < 0.5); // not 100% certain, but probable enough - } - } - - #[test] - fn test_poisson_10_f32() { - let poisson = Poisson::new(10.0f32).unwrap(); - let mut rng = crate::test::rng(123); - let mut sum_u64 = 0; - let mut sum_f32 = 0.; - for _ in 0..1000 { - let s_u64: u64 = poisson.sample(&mut rng); - let s_f32: f32 = poisson.sample(&mut rng); - sum_u64 += s_u64; - sum_f32 += s_f32; - } - let avg_u64 = (sum_u64 as f32) / 1000.0; - let avg_f32 = sum_f32 / 1000.0; - println!("Poisson averages: {} (u64) {} (f32)", avg_u64, avg_f32); - for &avg in &[avg_u64, avg_f32] { - assert!((avg - 10.0).abs() < 0.5); // not 100% certain, but probable enough - } - } - - #[test] - fn test_poisson_15_f32() { - // Take the 'high expected values' path - let poisson = Poisson::new(15.0f32).unwrap(); - let mut rng = crate::test::rng(123); - let mut sum_u64 = 0; - let mut sum_f32 = 0.; - for _ in 0..1000 { - let s_u64: u64 = poisson.sample(&mut rng); - let s_f32: f32 = poisson.sample(&mut rng); - sum_u64 += s_u64; - sum_f32 += s_f32; - } - let avg_u64 = (sum_u64 as f32) / 1000.0; - let avg_f32 = sum_f32 / 1000.0; - println!("Poisson average: {} (u64) {} (f32)", avg_u64, avg_f32); - for &avg in &[avg_u64, avg_f32] { - assert!((avg - 15.0).abs() < 0.5); // not 100% certain, but probable enough - } - } - - #[test] - #[should_panic] - fn test_poisson_invalid_lambda_zero() { - Poisson::new(0.0).unwrap(); - } - - #[test] - #[should_panic] - fn test_poisson_invalid_lambda_neg() { - Poisson::new(-10.0).unwrap(); - } -} diff --git a/rand/rand_distr/src/triangular.rs b/rand/rand_distr/src/triangular.rs deleted file mode 100644 index dd0bbfb..0000000 --- a/rand/rand_distr/src/triangular.rs +++ /dev/null @@ -1,125 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. -//! The triangular distribution. - -use rand::Rng; -use crate::{Distribution, Standard}; -use crate::utils::Float; - -/// The triangular distribution. -/// -/// A continuous probability distribution parameterised by a range, and a mode -/// (most likely value) within that range. -/// -/// The probability density function is triangular. For a similar distribution -/// with a smooth PDF, see the [`Pert`] distribution. -/// -/// # Example -/// -/// ```rust -/// use rand_distr::{Triangular, Distribution}; -/// -/// let d = Triangular::new(0., 5., 2.5).unwrap(); -/// let v = d.sample(&mut rand::thread_rng()); -/// println!("{} is from a triangular distribution", v); -/// ``` -/// -/// [`Pert`]: crate::Pert -#[derive(Clone, Copy, Debug)] -pub struct Triangular { - min: N, - max: N, - mode: N, -} - -/// Error type returned from [`Triangular::new`]. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum TriangularError { - /// `max < min` or `min` or `max` is NaN. - RangeTooSmall, - /// `mode < min` or `mode > max` or `mode` is NaN. - ModeRange, -} - -impl Triangular -where Standard: Distribution -{ - /// Set up the Triangular distribution with defined `min`, `max` and `mode`. - #[inline] - pub fn new(min: N, max: N, mode: N) -> Result, TriangularError> { - if !(max >= min) { - return Err(TriangularError::RangeTooSmall); - } - if !(mode >= min && max >= mode) { - return Err(TriangularError::ModeRange); - } - Ok(Triangular { min, max, mode }) - } -} - -impl Distribution for Triangular -where Standard: Distribution -{ - #[inline] - fn sample(&self, rng: &mut R) -> N { - let f: N = rng.sample(Standard); - let diff_mode_min = self.mode - self.min; - let range = self.max - self.min; - let f_range = f * range; - if f_range < diff_mode_min { - self.min + (f_range * diff_mode_min).sqrt() - } else { - self.max - ((range - f_range) * (self.max - self.mode)).sqrt() - } - } -} - -#[cfg(test)] -mod test { - use std::f64; - use rand::{Rng, rngs::mock}; - use super::*; - - #[test] - fn test_triangular() { - let mut half_rng = mock::StepRng::new(0x8000_0000_0000_0000, 0); - assert_eq!(half_rng.gen::(), 0.5); - for &(min, max, mode, median) in &[ - (-1., 1., 0., 0.), - (1., 2., 1., 2. - 0.5f64.sqrt()), - (5., 25., 25., 5. + 200f64.sqrt()), - (1e-5, 1e5, 1e-3, 1e5 - 4999999949.5f64.sqrt()), - (0., 1., 0.9, 0.45f64.sqrt()), - (-4., -0.5, -2., -4.0 + 3.5f64.sqrt()), - ] { - println!("{} {} {} {}", min, max, mode, median); - let distr = Triangular::new(min, max, mode).unwrap(); - // Test correct value at median: - assert_eq!(distr.sample(&mut half_rng), median); - } - - for &(min, max, mode) in &[ - (-1., 1., 2.), - (-1., 1., -2.), - (2., 1., 1.), - ] { - assert!(Triangular::new(min, max, mode).is_err()); - } - } - - #[test] - fn value_stability() { - let rng = crate::test::rng(860); - let distr = Triangular::new(2., 10., 3.).unwrap(); - let seq = distr.sample_iter(rng).take(5).collect::>(); - println!("seq: {:?}", seq); - let expected = vec![5.74373257511361, 7.890059162791258, - 4.7256280652553455, 2.9474808121184077, 3.058301946314053]; - assert!(seq == expected); - } -} diff --git a/rand/rand_distr/src/unit_ball.rs b/rand/rand_distr/src/unit_ball.rs deleted file mode 100644 index 9d61627..0000000 --- a/rand/rand_distr/src/unit_ball.rs +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright 2019 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use rand::Rng; -use crate::{Distribution, Uniform, uniform::SampleUniform}; -use crate::utils::Float; - -/// Samples uniformly from the unit ball (surface and interior) in three -/// dimensions. -/// -/// Implemented via rejection sampling. -/// -/// -/// # Example -/// -/// ``` -/// use rand_distr::{UnitBall, Distribution}; -/// -/// let v: [f64; 3] = UnitBall.sample(&mut rand::thread_rng()); -/// println!("{:?} is from the unit ball.", v) -/// ``` -#[derive(Clone, Copy, Debug)] -pub struct UnitBall; - -impl Distribution<[N; 3]> for UnitBall { - #[inline] - fn sample(&self, rng: &mut R) -> [N; 3] { - let uniform = Uniform::new(N::from(-1.), N::from(1.)); - let mut x1; - let mut x2; - let mut x3; - loop { - x1 = uniform.sample(rng); - x2 = uniform.sample(rng); - x3 = uniform.sample(rng); - if x1*x1 + x2*x2 + x3*x3 <= N::from(1.) { - break; - } - } - [x1, x2, x3] - } -} - -#[cfg(test)] -mod tests { - use crate::Distribution; - use super::UnitBall; - - #[test] - fn value_stability() { - let mut rng = crate::test::rng(2); - let expected = [ - [0.018035709265959987, -0.4348771383120438, -0.07982762085055706], - [0.10588569388223945, -0.4734350111375454, -0.7392104908825501], - [0.11060237642041049, -0.16065642822852677, -0.8444043930440075] - ]; - let samples: [[f64; 3]; 3] = [ - UnitBall.sample(&mut rng), - UnitBall.sample(&mut rng), - UnitBall.sample(&mut rng), - ]; - assert_eq!(samples, expected); - } -} diff --git a/rand/rand_distr/src/unit_circle.rs b/rand/rand_distr/src/unit_circle.rs deleted file mode 100644 index 5863a1a..0000000 --- a/rand/rand_distr/src/unit_circle.rs +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use rand::Rng; -use crate::{Distribution, Uniform, uniform::SampleUniform}; -use crate::utils::Float; - -/// Samples uniformly from the edge of the unit circle in two dimensions. -/// -/// Implemented via a method by von Neumann[^1]. -/// -/// -/// # Example -/// -/// ``` -/// use rand_distr::{UnitCircle, Distribution}; -/// -/// let v: [f64; 2] = UnitCircle.sample(&mut rand::thread_rng()); -/// println!("{:?} is from the unit circle.", v) -/// ``` -/// -/// [^1]: von Neumann, J. (1951) [*Various Techniques Used in Connection with -/// Random Digits.*](https://mcnp.lanl.gov/pdf_files/nbs_vonneumann.pdf) -/// NBS Appl. Math. Ser., No. 12. Washington, DC: U.S. Government Printing -/// Office, pp. 36-38. -#[derive(Clone, Copy, Debug)] -pub struct UnitCircle; - -impl Distribution<[N; 2]> for UnitCircle { - #[inline] - fn sample(&self, rng: &mut R) -> [N; 2] { - let uniform = Uniform::new(N::from(-1.), N::from(1.)); - let mut x1; - let mut x2; - let mut sum; - loop { - x1 = uniform.sample(rng); - x2 = uniform.sample(rng); - sum = x1*x1 + x2*x2; - if sum < N::from(1.) { - break; - } - } - let diff = x1*x1 - x2*x2; - [diff / sum, N::from(2.)*x1*x2 / sum] - } -} - -#[cfg(test)] -mod tests { - use crate::Distribution; - use super::UnitCircle; - - /// Assert that two numbers are almost equal to each other. - /// - /// On panic, this macro will print the values of the expressions with their - /// debug representations. - macro_rules! assert_almost_eq { - ($a:expr, $b:expr, $prec:expr) => ( - let diff = ($a - $b).abs(); - if diff > $prec { - panic!(format!( - "assertion failed: `abs(left - right) = {:.1e} < {:e}`, \ - (left: `{}`, right: `{}`)", - diff, $prec, $a, $b)); - } - ); - } - - #[test] - fn norm() { - let mut rng = crate::test::rng(1); - for _ in 0..1000 { - let x: [f64; 2] = UnitCircle.sample(&mut rng); - assert_almost_eq!(x[0]*x[0] + x[1]*x[1], 1., 1e-15); - } - } - - #[test] - fn value_stability() { - let mut rng = crate::test::rng(2); - let expected = [ - [-0.9965658683520504, -0.08280380447614634], - [-0.9790853270389644, -0.20345004884984505], - [-0.8449189758898707, 0.5348943112253227], - ]; - let samples: [[f64; 2]; 3] = [ - UnitCircle.sample(&mut rng), - UnitCircle.sample(&mut rng), - UnitCircle.sample(&mut rng), - ]; - assert_eq!(samples, expected); - } -} diff --git a/rand/rand_distr/src/unit_disc.rs b/rand/rand_distr/src/unit_disc.rs deleted file mode 100644 index 97abc2f..0000000 --- a/rand/rand_distr/src/unit_disc.rs +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright 2019 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use rand::Rng; -use crate::{Distribution, Uniform, uniform::SampleUniform}; -use crate::utils::Float; - -/// Samples uniformly from the unit disc in two dimensions. -/// -/// Implemented via rejection sampling. -/// -/// -/// # Example -/// -/// ``` -/// use rand_distr::{UnitDisc, Distribution}; -/// -/// let v: [f64; 2] = UnitDisc.sample(&mut rand::thread_rng()); -/// println!("{:?} is from the unit Disc.", v) -/// ``` -#[derive(Clone, Copy, Debug)] -pub struct UnitDisc; - -impl Distribution<[N; 2]> for UnitDisc { - #[inline] - fn sample(&self, rng: &mut R) -> [N; 2] { - let uniform = Uniform::new(N::from(-1.), N::from(1.)); - let mut x1; - let mut x2; - loop { - x1 = uniform.sample(rng); - x2 = uniform.sample(rng); - if x1*x1 + x2*x2 <= N::from(1.) { - break; - } - } - [x1, x2] - } -} - -#[cfg(test)] -mod tests { - use crate::Distribution; - use super::UnitDisc; - - #[test] - fn value_stability() { - let mut rng = crate::test::rng(2); - let expected = [ - [0.018035709265959987, -0.4348771383120438], - [-0.07982762085055706, 0.7765329819820659], - [0.21450745997299503, 0.7398636984333291] - ]; - let samples: [[f64; 2]; 3] = [ - UnitDisc.sample(&mut rng), - UnitDisc.sample(&mut rng), - UnitDisc.sample(&mut rng), - ]; - assert_eq!(samples, expected); - } -} diff --git a/rand/rand_distr/src/unit_sphere.rs b/rand/rand_distr/src/unit_sphere.rs deleted file mode 100644 index 8e0c361..0000000 --- a/rand/rand_distr/src/unit_sphere.rs +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright 2018-2019 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use rand::Rng; -use crate::{Distribution, Uniform, uniform::SampleUniform}; -use crate::utils::Float; - -/// Samples uniformly from the surface of the unit sphere in three dimensions. -/// -/// Implemented via a method by Marsaglia[^1]. -/// -/// -/// # Example -/// -/// ``` -/// use rand_distr::{UnitSphere, Distribution}; -/// -/// let v: [f64; 3] = UnitSphere.sample(&mut rand::thread_rng()); -/// println!("{:?} is from the unit sphere surface.", v) -/// ``` -/// -/// [^1]: Marsaglia, George (1972). [*Choosing a Point from the Surface of a -/// Sphere.*](https://doi.org/10.1214/aoms/1177692644) -/// Ann. Math. Statist. 43, no. 2, 645--646. -#[derive(Clone, Copy, Debug)] -pub struct UnitSphere; - -impl Distribution<[N; 3]> for UnitSphere { - #[inline] - fn sample(&self, rng: &mut R) -> [N; 3] { - let uniform = Uniform::new(N::from(-1.), N::from(1.)); - loop { - let (x1, x2) = (uniform.sample(rng), uniform.sample(rng)); - let sum = x1*x1 + x2*x2; - if sum >= N::from(1.) { - continue; - } - let factor = N::from(2.) * (N::from(1.0) - sum).sqrt(); - return [x1 * factor, x2 * factor, N::from(1.) - N::from(2.)*sum]; - } - } -} - -#[cfg(test)] -mod tests { - use crate::Distribution; - use super::UnitSphere; - - /// Assert that two numbers are almost equal to each other. - /// - /// On panic, this macro will print the values of the expressions with their - /// debug representations. - macro_rules! assert_almost_eq { - ($a:expr, $b:expr, $prec:expr) => ( - let diff = ($a - $b).abs(); - if diff > $prec { - panic!(format!( - "assertion failed: `abs(left - right) = {:.1e} < {:e}`, \ - (left: `{}`, right: `{}`)", - diff, $prec, $a, $b)); - } - ); - } - - #[test] - fn norm() { - let mut rng = crate::test::rng(1); - for _ in 0..1000 { - let x: [f64; 3] = UnitSphere.sample(&mut rng); - assert_almost_eq!(x[0]*x[0] + x[1]*x[1] + x[2]*x[2], 1., 1e-15); - } - } - - #[test] - fn value_stability() { - let mut rng = crate::test::rng(2); - let expected = [ - [0.03247542860231647, -0.7830477442152738, 0.6211131755296027], - [-0.09978440840914075, 0.9706650829833128, -0.21875184231323952], - [0.2735582468624679, 0.9435374242279655, -0.1868234852870203], - ]; - let samples: [[f64; 3]; 3] = [ - UnitSphere.sample(&mut rng), - UnitSphere.sample(&mut rng), - UnitSphere.sample(&mut rng), - ]; - assert_eq!(samples, expected); - } -} diff --git a/rand/rand_distr/src/utils.rs b/rand/rand_distr/src/utils.rs deleted file mode 100644 index 75b3500..0000000 --- a/rand/rand_distr/src/utils.rs +++ /dev/null @@ -1,234 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Math helper functions - -use rand::Rng; -use crate::ziggurat_tables; -use rand::distributions::hidden_export::IntoFloat; -use core::{cmp, ops}; - -/// Trait for floating-point scalar types -/// -/// This allows many distributions to work with `f32` or `f64` parameters and is -/// potentially extensible. Note however that the `Exp1` and `StandardNormal` -/// distributions are implemented exclusively for `f32` and `f64`. -/// -/// The bounds and methods are based purely on internal -/// requirements, and will change as needed. -pub trait Float: Copy + Sized + cmp::PartialOrd - + ops::Neg - + ops::Add - + ops::Sub - + ops::Mul - + ops::Div - + ops::AddAssign + ops::SubAssign + ops::MulAssign + ops::DivAssign -{ - /// The constant Ο€ - fn pi() -> Self; - /// Support approximate representation of a f64 value - fn from(x: f64) -> Self; - /// Support converting to an unsigned integer. - fn to_u64(self) -> Option; - - /// Take the absolute value of self - fn abs(self) -> Self; - /// Take the largest integer less than or equal to self - fn floor(self) -> Self; - - /// Take the exponential of self - fn exp(self) -> Self; - /// Take the natural logarithm of self - fn ln(self) -> Self; - /// Take square root of self - fn sqrt(self) -> Self; - /// Take self to a floating-point power - fn powf(self, power: Self) -> Self; - - /// Take the tangent of self - fn tan(self) -> Self; - /// Take the logarithm of the gamma function of self - fn log_gamma(self) -> Self; -} - -impl Float for f32 { - #[inline] - fn pi() -> Self { core::f32::consts::PI } - #[inline] - fn from(x: f64) -> Self { x as f32 } - #[inline] - fn to_u64(self) -> Option { - if self >= 0. && self <= ::core::u64::MAX as f32 { - Some(self as u64) - } else { - None - } - } - - #[inline] - fn abs(self) -> Self { self.abs() } - #[inline] - fn floor(self) -> Self { self.floor() } - - #[inline] - fn exp(self) -> Self { self.exp() } - #[inline] - fn ln(self) -> Self { self.ln() } - #[inline] - fn sqrt(self) -> Self { self.sqrt() } - #[inline] - fn powf(self, power: Self) -> Self { self.powf(power) } - - #[inline] - fn tan(self) -> Self { self.tan() } - #[inline] - fn log_gamma(self) -> Self { - let result = log_gamma(self.into()); - assert!(result <= ::core::f32::MAX.into()); - assert!(result >= ::core::f32::MIN.into()); - result as f32 - } -} - -impl Float for f64 { - #[inline] - fn pi() -> Self { core::f64::consts::PI } - #[inline] - fn from(x: f64) -> Self { x } - #[inline] - fn to_u64(self) -> Option { - if self >= 0. && self <= ::core::u64::MAX as f64 { - Some(self as u64) - } else { - None - } - } - - #[inline] - fn abs(self) -> Self { self.abs() } - #[inline] - fn floor(self) -> Self { self.floor() } - - #[inline] - fn exp(self) -> Self { self.exp() } - #[inline] - fn ln(self) -> Self { self.ln() } - #[inline] - fn sqrt(self) -> Self { self.sqrt() } - #[inline] - fn powf(self, power: Self) -> Self { self.powf(power) } - - #[inline] - fn tan(self) -> Self { self.tan() } - #[inline] - fn log_gamma(self) -> Self { log_gamma(self) } -} - -/// Calculates ln(gamma(x)) (natural logarithm of the gamma -/// function) using the Lanczos approximation. -/// -/// The approximation expresses the gamma function as: -/// `gamma(z+1) = sqrt(2*pi)*(z+g+0.5)^(z+0.5)*exp(-z-g-0.5)*Ag(z)` -/// `g` is an arbitrary constant; we use the approximation with `g=5`. -/// -/// Noting that `gamma(z+1) = z*gamma(z)` and applying `ln` to both sides: -/// `ln(gamma(z)) = (z+0.5)*ln(z+g+0.5)-(z+g+0.5) + ln(sqrt(2*pi)*Ag(z)/z)` -/// -/// `Ag(z)` is an infinite series with coefficients that can be calculated -/// ahead of time - we use just the first 6 terms, which is good enough -/// for most purposes. -pub(crate) fn log_gamma(x: f64) -> f64 { - // precalculated 6 coefficients for the first 6 terms of the series - let coefficients: [f64; 6] = [ - 76.18009172947146, - -86.50532032941677, - 24.01409824083091, - -1.231739572450155, - 0.1208650973866179e-2, - -0.5395239384953e-5, - ]; - - // (x+0.5)*ln(x+g+0.5)-(x+g+0.5) - let tmp = x + 5.5; - let log = (x + 0.5) * tmp.ln() - tmp; - - // the first few terms of the series for Ag(x) - let mut a = 1.000000000190015; - let mut denom = x; - for &coeff in &coefficients { - denom += 1.0; - a += coeff / denom; - } - - // get everything together - // a is Ag(x) - // 2.5066... is sqrt(2pi) - log + (2.5066282746310005 * a / x).ln() -} - -/// Sample a random number using the Ziggurat method (specifically the -/// ZIGNOR variant from Doornik 2005). Most of the arguments are -/// directly from the paper: -/// -/// * `rng`: source of randomness -/// * `symmetric`: whether this is a symmetric distribution, or one-sided with P(x < 0) = 0. -/// * `X`: the $x_i$ abscissae. -/// * `F`: precomputed values of the PDF at the $x_i$, (i.e. $f(x_i)$) -/// * `F_DIFF`: precomputed values of $f(x_i) - f(x_{i+1})$ -/// * `pdf`: the probability density function -/// * `zero_case`: manual sampling from the tail when we chose the -/// bottom box (i.e. i == 0) - -// the perf improvement (25-50%) is definitely worth the extra code -// size from force-inlining. -#[inline(always)] -pub(crate) fn ziggurat( - rng: &mut R, - symmetric: bool, - x_tab: ziggurat_tables::ZigTable, - f_tab: ziggurat_tables::ZigTable, - mut pdf: P, - mut zero_case: Z) - -> f64 where P: FnMut(f64) -> f64, Z: FnMut(&mut R, f64) -> f64 { - loop { - // As an optimisation we re-implement the conversion to a f64. - // From the remaining 12 most significant bits we use 8 to construct `i`. - // This saves us generating a whole extra random number, while the added - // precision of using 64 bits for f64 does not buy us much. - let bits = rng.next_u64(); - let i = bits as usize & 0xff; - - let u = if symmetric { - // Convert to a value in the range [2,4) and substract to get [-1,1) - // We can't convert to an open range directly, that would require - // substracting `3.0 - EPSILON`, which is not representable. - // It is possible with an extra step, but an open range does not - // seem neccesary for the ziggurat algorithm anyway. - (bits >> 12).into_float_with_exponent(1) - 3.0 - } else { - // Convert to a value in the range [1,2) and substract to get (0,1) - (bits >> 12).into_float_with_exponent(0) - - (1.0 - std::f64::EPSILON / 2.0) - }; - let x = u * x_tab[i]; - - let test_x = if symmetric { x.abs() } else {x}; - - // algebraically equivalent to |u| < x_tab[i+1]/x_tab[i] (or u < x_tab[i+1]/x_tab[i]) - if test_x < x_tab[i + 1] { - return x; - } - if i == 0 { - return zero_case(rng, u); - } - // algebraically equivalent to f1 + DRanU()*(f0 - f1) < 1 - if f_tab[i + 1] + (f_tab[i] - f_tab[i + 1]) * rng.gen::() < pdf(x) { - return x; - } - } -} diff --git a/rand/rand_distr/src/weibull.rs b/rand/rand_distr/src/weibull.rs deleted file mode 100644 index ddde380..0000000 --- a/rand/rand_distr/src/weibull.rs +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The Weibull distribution. - -use rand::Rng; -use crate::{Distribution, OpenClosed01}; -use crate::utils::Float; - -/// Samples floating-point numbers according to the Weibull distribution -/// -/// # Example -/// ``` -/// use rand::prelude::*; -/// use rand_distr::Weibull; -/// -/// let val: f64 = thread_rng().sample(Weibull::new(1., 10.).unwrap()); -/// println!("{}", val); -/// ``` -#[derive(Clone, Copy, Debug)] -pub struct Weibull { - inv_shape: N, - scale: N, -} - -/// Error type returned from `Weibull::new`. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Error { - /// `scale <= 0` or `nan`. - ScaleTooSmall, - /// `shape <= 0` or `nan`. - ShapeTooSmall, -} - -impl Weibull -where OpenClosed01: Distribution -{ - /// Construct a new `Weibull` distribution with given `scale` and `shape`. - pub fn new(scale: N, shape: N) -> Result, Error> { - if !(scale > N::from(0.0)) { - return Err(Error::ScaleTooSmall); - } - if !(shape > N::from(0.0)) { - return Err(Error::ShapeTooSmall); - } - Ok(Weibull { inv_shape: N::from(1.)/shape, scale }) - } -} - -impl Distribution for Weibull -where OpenClosed01: Distribution -{ - fn sample(&self, rng: &mut R) -> N { - let x: N = rng.sample(OpenClosed01); - self.scale * (-x.ln()).powf(self.inv_shape) - } -} - -#[cfg(test)] -mod tests { - use crate::Distribution; - use super::Weibull; - - #[test] - #[should_panic] - fn invalid() { - Weibull::new(0., 0.).unwrap(); - } - - #[test] - fn sample() { - let scale = 1.0; - let shape = 2.0; - let d = Weibull::new(scale, shape).unwrap(); - let mut rng = crate::test::rng(1); - for _ in 0..1000 { - let r = d.sample(&mut rng); - assert!(r >= 0.); - } - } -} diff --git a/rand/rand_distr/src/ziggurat_tables.rs b/rand/rand_distr/src/ziggurat_tables.rs deleted file mode 100644 index ca1ce30..0000000 --- a/rand/rand_distr/src/ziggurat_tables.rs +++ /dev/null @@ -1,279 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// Copyright 2013 The Rust Project Developers. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -// Tables for distributions which are sampled using the ziggurat -// algorithm. Autogenerated by `ziggurat_tables.py`. - -pub type ZigTable = &'static [f64; 257]; -pub const ZIG_NORM_R: f64 = 3.654152885361008796; -pub static ZIG_NORM_X: [f64; 257] = - [3.910757959537090045, 3.654152885361008796, 3.449278298560964462, 3.320244733839166074, - 3.224575052047029100, 3.147889289517149969, 3.083526132001233044, 3.027837791768635434, - 2.978603279880844834, 2.934366867207854224, 2.894121053612348060, 2.857138730872132548, - 2.822877396825325125, 2.790921174000785765, 2.760944005278822555, 2.732685359042827056, - 2.705933656121858100, 2.680514643284522158, 2.656283037575502437, 2.633116393630324570, - 2.610910518487548515, 2.589575986706995181, 2.569035452680536569, 2.549221550323460761, - 2.530075232158516929, 2.511544441625342294, 2.493583041269680667, 2.476149939669143318, - 2.459208374333311298, 2.442725318198956774, 2.426670984935725972, 2.411018413899685520, - 2.395743119780480601, 2.380822795170626005, 2.366237056715818632, 2.351967227377659952, - 2.337996148795031370, 2.324308018869623016, 2.310888250599850036, 2.297723348901329565, - 2.284800802722946056, 2.272108990226823888, 2.259637095172217780, 2.247375032945807760, - 2.235313384928327984, 2.223443340090905718, 2.211756642882544366, 2.200245546609647995, - 2.188902771624720689, 2.177721467738641614, 2.166695180352645966, 2.155817819875063268, - 2.145083634046203613, 2.134487182844320152, 2.124023315687815661, 2.113687150684933957, - 2.103474055713146829, 2.093379631137050279, 2.083399693996551783, 2.073530263516978778, - 2.063767547809956415, 2.054107931648864849, 2.044547965215732788, 2.035084353727808715, - 2.025713947862032960, 2.016433734904371722, 2.007240830558684852, 1.998132471356564244, - 1.989106007615571325, 1.980158896898598364, 1.971288697931769640, 1.962493064942461896, - 1.953769742382734043, 1.945116560006753925, 1.936531428273758904, 1.928012334050718257, - 1.919557336591228847, 1.911164563769282232, 1.902832208548446369, 1.894558525668710081, - 1.886341828534776388, 1.878180486290977669, 1.870072921069236838, 1.862017605397632281, - 1.854013059758148119, 1.846057850283119750, 1.838150586580728607, 1.830289919680666566, - 1.822474540091783224, 1.814703175964167636, 1.806974591348693426, 1.799287584547580199, - 1.791640986550010028, 1.784033659547276329, 1.776464495522344977, 1.768932414909077933, - 1.761436365316706665, 1.753975320315455111, 1.746548278279492994, 1.739154261283669012, - 1.731792314050707216, 1.724461502945775715, 1.717160915015540690, 1.709889657069006086, - 1.702646854797613907, 1.695431651932238548, 1.688243209434858727, 1.681080704722823338, - 1.673943330923760353, 1.666830296159286684, 1.659740822855789499, 1.652674147080648526, - 1.645629517902360339, 1.638606196773111146, 1.631603456932422036, 1.624620582830568427, - 1.617656869570534228, 1.610711622367333673, 1.603784156023583041, 1.596873794420261339, - 1.589979870021648534, 1.583101723393471438, 1.576238702733332886, 1.569390163412534456, - 1.562555467528439657, 1.555733983466554893, 1.548925085471535512, 1.542128153226347553, - 1.535342571438843118, 1.528567729435024614, 1.521803020758293101, 1.515047842773992404, - 1.508301596278571965, 1.501563685112706548, 1.494833515777718391, 1.488110497054654369, - 1.481394039625375747, 1.474683555695025516, 1.467978458615230908, 1.461278162507407830, - 1.454582081885523293, 1.447889631277669675, 1.441200224845798017, 1.434513276002946425, - 1.427828197027290358, 1.421144398672323117, 1.414461289772464658, 1.407778276843371534, - 1.401094763676202559, 1.394410150925071257, 1.387723835686884621, 1.381035211072741964, - 1.374343665770030531, 1.367648583594317957, 1.360949343030101844, 1.354245316759430606, - 1.347535871177359290, 1.340820365893152122, 1.334098153216083604, 1.327368577624624679, - 1.320630975217730096, 1.313884673146868964, 1.307128989027353860, 1.300363230327433728, - 1.293586693733517645, 1.286798664489786415, 1.279998415710333237, 1.273185207661843732, - 1.266358287014688333, 1.259516886060144225, 1.252660221891297887, 1.245787495544997903, - 1.238897891102027415, 1.231990574742445110, 1.225064693752808020, 1.218119375481726552, - 1.211153726239911244, 1.204166830140560140, 1.197157747875585931, 1.190125515422801650, - 1.183069142678760732, 1.175987612011489825, 1.168879876726833800, 1.161744859441574240, - 1.154581450355851802, 1.147388505416733873, 1.140164844363995789, 1.132909248648336975, - 1.125620459211294389, 1.118297174115062909, 1.110938046009249502, 1.103541679420268151, - 1.096106627847603487, 1.088631390649514197, 1.081114409698889389, 1.073554065787871714, - 1.065948674757506653, 1.058296483326006454, 1.050595664586207123, 1.042844313139370538, - 1.035040439828605274, 1.027181966030751292, 1.019266717460529215, 1.011292417434978441, - 1.003256679539591412, 0.995156999629943084, 0.986990747093846266, 0.978755155288937750, - 0.970447311058864615, 0.962064143217605250, 0.953602409875572654, 0.945058684462571130, - 0.936429340280896860, 0.927710533396234771, 0.918898183643734989, 0.909987953490768997, - 0.900975224455174528, 0.891855070726792376, 0.882622229578910122, 0.873271068082494550, - 0.863795545546826915, 0.854189171001560554, 0.844444954902423661, 0.834555354079518752, - 0.824512208745288633, 0.814306670128064347, 0.803929116982664893, 0.793369058833152785, - 0.782615023299588763, 0.771654424216739354, 0.760473406422083165, 0.749056662009581653, - 0.737387211425838629, 0.725446140901303549, 0.713212285182022732, 0.700661841097584448, - 0.687767892786257717, 0.674499822827436479, 0.660822574234205984, 0.646695714884388928, - 0.632072236375024632, 0.616896989996235545, 0.601104617743940417, 0.584616766093722262, - 0.567338257040473026, 0.549151702313026790, 0.529909720646495108, 0.509423329585933393, - 0.487443966121754335, 0.463634336771763245, 0.437518402186662658, 0.408389134588000746, - 0.375121332850465727, 0.335737519180459465, 0.286174591747260509, 0.215241895913273806, - 0.000000000000000000]; -pub static ZIG_NORM_F: [f64; 257] = - [0.000477467764586655, 0.001260285930498598, 0.002609072746106363, 0.004037972593371872, - 0.005522403299264754, 0.007050875471392110, 0.008616582769422917, 0.010214971439731100, - 0.011842757857943104, 0.013497450601780807, 0.015177088307982072, 0.016880083152595839, - 0.018605121275783350, 0.020351096230109354, 0.022117062707379922, 0.023902203305873237, - 0.025705804008632656, 0.027527235669693315, 0.029365939758230111, 0.031221417192023690, - 0.033093219458688698, 0.034980941461833073, 0.036884215688691151, 0.038802707404656918, - 0.040736110656078753, 0.042684144916619378, 0.044646552251446536, 0.046623094902089664, - 0.048613553216035145, 0.050617723861121788, 0.052635418276973649, 0.054666461325077916, - 0.056710690106399467, 0.058767952921137984, 0.060838108349751806, 0.062921024437977854, - 0.065016577971470438, 0.067124653828023989, 0.069245144397250269, 0.071377949059141965, - 0.073522973714240991, 0.075680130359194964, 0.077849336702372207, 0.080030515814947509, - 0.082223595813495684, 0.084428509570654661, 0.086645194450867782, 0.088873592068594229, - 0.091113648066700734, 0.093365311913026619, 0.095628536713353335, 0.097903279039215627, - 0.100189498769172020, 0.102487158942306270, 0.104796225622867056, 0.107116667775072880, - 0.109448457147210021, 0.111791568164245583, 0.114145977828255210, 0.116511665626037014, - 0.118888613443345698, 0.121276805485235437, 0.123676228202051403, 0.126086870220650349, - 0.128508722280473636, 0.130941777174128166, 0.133386029692162844, 0.135841476571757352, - 0.138308116449064322, 0.140785949814968309, 0.143274978974047118, 0.145775208006537926, - 0.148286642733128721, 0.150809290682410169, 0.153343161060837674, 0.155888264725064563, - 0.158444614156520225, 0.161012223438117663, 0.163591108232982951, 0.166181285765110071, - 0.168782774801850333, 0.171395595638155623, 0.174019770082499359, 0.176655321444406654, - 0.179302274523530397, 0.181960655600216487, 0.184630492427504539, 0.187311814224516926, - 0.190004651671193070, 0.192709036904328807, 0.195425003514885592, 0.198152586546538112, - 0.200891822495431333, 0.203642749311121501, 0.206405406398679298, 0.209179834621935651, - 0.211966076307852941, 0.214764175252008499, 0.217574176725178370, 0.220396127481011589, - 0.223230075764789593, 0.226076071323264877, 0.228934165415577484, 0.231804410825248525, - 0.234686861873252689, 0.237581574432173676, 0.240488605941449107, 0.243408015423711988, - 0.246339863502238771, 0.249284212419516704, 0.252241126056943765, 0.255210669955677150, - 0.258192911338648023, 0.261187919133763713, 0.264195763998317568, 0.267216518344631837, - 0.270250256366959984, 0.273297054069675804, 0.276356989296781264, 0.279430141762765316, - 0.282516593084849388, 0.285616426816658109, 0.288729728483353931, 0.291856585618280984, - 0.294997087801162572, 0.298151326697901342, 0.301319396102034120, 0.304501391977896274, - 0.307697412505553769, 0.310907558127563710, 0.314131931597630143, 0.317370638031222396, - 0.320623784958230129, 0.323891482377732021, 0.327173842814958593, 0.330470981380537099, - 0.333783015832108509, 0.337110066638412809, 0.340452257045945450, 0.343809713148291340, - 0.347182563958251478, 0.350570941482881204, 0.353974980801569250, 0.357394820147290515, - 0.360830600991175754, 0.364282468130549597, 0.367750569780596226, 0.371235057669821344, - 0.374736087139491414, 0.378253817247238111, 0.381788410875031348, 0.385340034841733958, - 0.388908860020464597, 0.392495061461010764, 0.396098818517547080, 0.399720314981931668, - 0.403359739222868885, 0.407017284331247953, 0.410693148271983222, 0.414387534042706784, - 0.418100649839684591, 0.421832709231353298, 0.425583931339900579, 0.429354541031341519, - 0.433144769114574058, 0.436954852549929273, 0.440785034667769915, 0.444635565397727750, - 0.448506701509214067, 0.452398706863882505, 0.456311852680773566, 0.460246417814923481, - 0.464202689050278838, 0.468180961407822172, 0.472181538469883255, 0.476204732721683788, - 0.480250865911249714, 0.484320269428911598, 0.488413284707712059, 0.492530263646148658, - 0.496671569054796314, 0.500837575128482149, 0.505028667945828791, 0.509245245998136142, - 0.513487720749743026, 0.517756517232200619, 0.522052074674794864, 0.526374847174186700, - 0.530725304406193921, 0.535103932383019565, 0.539511234259544614, 0.543947731192649941, - 0.548413963257921133, 0.552910490428519918, 0.557437893621486324, 0.561996775817277916, - 0.566587763258951771, 0.571211506738074970, 0.575868682975210544, 0.580559996103683473, - 0.585286179266300333, 0.590047996335791969, 0.594846243770991268, 0.599681752622167719, - 0.604555390700549533, 0.609468064928895381, 0.614420723892076803, 0.619414360609039205, - 0.624450015550274240, 0.629528779928128279, 0.634651799290960050, 0.639820277456438991, - 0.645035480824251883, 0.650298743114294586, 0.655611470583224665, 0.660975147780241357, - 0.666391343912380640, 0.671861719900766374, 0.677388036222513090, 0.682972161648791376, - 0.688616083008527058, 0.694321916130032579, 0.700091918140490099, 0.705928501336797409, - 0.711834248882358467, 0.717811932634901395, 0.723864533472881599, 0.729995264565802437, - 0.736207598131266683, 0.742505296344636245, 0.748892447223726720, 0.755373506511754500, - 0.761953346841546475, 0.768637315803334831, 0.775431304986138326, 0.782341832659861902, - 0.789376143571198563, 0.796542330428254619, 0.803849483176389490, 0.811307874318219935, - 0.818929191609414797, 0.826726833952094231, 0.834716292992930375, 0.842915653118441077, - 0.851346258465123684, 0.860033621203008636, 0.869008688043793165, 0.878309655816146839, - 0.887984660763399880, 0.898095921906304051, 0.908726440060562912, 0.919991505048360247, - 0.932060075968990209, 0.945198953453078028, 0.959879091812415930, 0.977101701282731328, - 1.000000000000000000]; -pub const ZIG_EXP_R: f64 = 7.697117470131050077; -pub static ZIG_EXP_X: [f64; 257] = - [8.697117470131052741, 7.697117470131050077, 6.941033629377212577, 6.478378493832569696, - 6.144164665772472667, 5.882144315795399869, 5.666410167454033697, 5.482890627526062488, - 5.323090505754398016, 5.181487281301500047, 5.054288489981304089, 4.938777085901250530, - 4.832939741025112035, 4.735242996601741083, 4.644491885420085175, 4.559737061707351380, - 4.480211746528421912, 4.405287693473573185, 4.334443680317273007, 4.267242480277365857, - 4.203313713735184365, 4.142340865664051464, 4.084051310408297830, 4.028208544647936762, - 3.974606066673788796, 3.923062500135489739, 3.873417670399509127, 3.825529418522336744, - 3.779270992411667862, 3.734528894039797375, 3.691201090237418825, 3.649195515760853770, - 3.608428813128909507, 3.568825265648337020, 3.530315889129343354, 3.492837654774059608, - 3.456332821132760191, 3.420748357251119920, 3.386035442460300970, 3.352149030900109405, - 3.319047470970748037, 3.286692171599068679, 3.255047308570449882, 3.224079565286264160, - 3.193757903212240290, 3.164053358025972873, 3.134938858084440394, 3.106389062339824481, - 3.078380215254090224, 3.050890016615455114, 3.023897504455676621, 2.997382949516130601, - 2.971327759921089662, 2.945714394895045718, 2.920526286512740821, 2.895747768600141825, - 2.871364012015536371, 2.847360965635188812, 2.823725302450035279, 2.800444370250737780, - 2.777506146439756574, 2.754899196562344610, 2.732612636194700073, 2.710636095867928752, - 2.688959688741803689, 2.667573980773266573, 2.646469963151809157, 2.625639026797788489, - 2.605072938740835564, 2.584763820214140750, 2.564704126316905253, 2.544886627111869970, - 2.525304390037828028, 2.505950763528594027, 2.486819361740209455, 2.467904050297364815, - 2.449198932978249754, 2.430698339264419694, 2.412396812688870629, 2.394289099921457886, - 2.376370140536140596, 2.358635057409337321, 2.341079147703034380, 2.323697874390196372, - 2.306486858283579799, 2.289441870532269441, 2.272558825553154804, 2.255833774367219213, - 2.239262898312909034, 2.222842503111036816, 2.206569013257663858, 2.190438966723220027, - 2.174449009937774679, 2.158595893043885994, 2.142876465399842001, 2.127287671317368289, - 2.111826546019042183, 2.096490211801715020, 2.081275874393225145, 2.066180819490575526, - 2.051202409468584786, 2.036338080248769611, 2.021585338318926173, 2.006941757894518563, - 1.992404978213576650, 1.977972700957360441, 1.963642687789548313, 1.949412758007184943, - 1.935280786297051359, 1.921244700591528076, 1.907302480018387536, 1.893452152939308242, - 1.879691795072211180, 1.866019527692827973, 1.852433515911175554, 1.838931967018879954, - 1.825513128903519799, 1.812175288526390649, 1.798916770460290859, 1.785735935484126014, - 1.772631179231305643, 1.759600930889074766, 1.746643651946074405, 1.733757834985571566, - 1.720942002521935299, 1.708194705878057773, 1.695514524101537912, 1.682900062917553896, - 1.670349953716452118, 1.657862852574172763, 1.645437439303723659, 1.633072416535991334, - 1.620766508828257901, 1.608518461798858379, 1.596327041286483395, 1.584191032532688892, - 1.572109239386229707, 1.560080483527888084, 1.548103603714513499, 1.536177455041032092, - 1.524300908219226258, 1.512472848872117082, 1.500692176842816750, 1.488957805516746058, - 1.477268661156133867, 1.465623682245745352, 1.454021818848793446, 1.442462031972012504, - 1.430943292938879674, 1.419464582769983219, 1.408024891569535697, 1.396623217917042137, - 1.385258568263121992, 1.373929956328490576, 1.362636402505086775, 1.351376933258335189, - 1.340150580529504643, 1.328956381137116560, 1.317793376176324749, 1.306660610415174117, - 1.295557131686601027, 1.284481990275012642, 1.273434238296241139, 1.262412929069615330, - 1.251417116480852521, 1.240445854334406572, 1.229498195693849105, 1.218573192208790124, - 1.207669893426761121, 1.196787346088403092, 1.185924593404202199, 1.175080674310911677, - 1.164254622705678921, 1.153445466655774743, 1.142652227581672841, 1.131873919411078511, - 1.121109547701330200, 1.110358108727411031, 1.099618588532597308, 1.088889961938546813, - 1.078171191511372307, 1.067461226479967662, 1.056759001602551429, 1.046063435977044209, - 1.035373431790528542, 1.024687873002617211, 1.014005623957096480, 1.003325527915696735, - 0.992646405507275897, 0.981967053085062602, 0.971286240983903260, 0.960602711668666509, - 0.949915177764075969, 0.939222319955262286, 0.928522784747210395, 0.917815182070044311, - 0.907098082715690257, 0.896370015589889935, 0.885629464761751528, 0.874874866291025066, - 0.864104604811004484, 0.853317009842373353, 0.842510351810368485, 0.831682837734273206, - 0.820832606554411814, 0.809957724057418282, 0.799056177355487174, 0.788125868869492430, - 0.777164609759129710, 0.766170112735434672, 0.755139984181982249, 0.744071715500508102, - 0.732962673584365398, 0.721810090308756203, 0.710611050909655040, 0.699362481103231959, - 0.688061132773747808, 0.676703568029522584, 0.665286141392677943, 0.653804979847664947, - 0.642255960424536365, 0.630634684933490286, 0.618936451394876075, 0.607156221620300030, - 0.595288584291502887, 0.583327712748769489, 0.571267316532588332, 0.559100585511540626, - 0.546820125163310577, 0.534417881237165604, 0.521885051592135052, 0.509211982443654398, - 0.496388045518671162, 0.483401491653461857, 0.470239275082169006, 0.456886840931420235, - 0.443327866073552401, 0.429543940225410703, 0.415514169600356364, 0.401214678896277765, - 0.386617977941119573, 0.371692145329917234, 0.356399760258393816, 0.340696481064849122, - 0.324529117016909452, 0.307832954674932158, 0.290527955491230394, 0.272513185478464703, - 0.253658363385912022, 0.233790483059674731, 0.212671510630966620, 0.189958689622431842, - 0.165127622564187282, 0.137304980940012589, 0.104838507565818778, 0.063852163815001570, - 0.000000000000000000]; -pub static ZIG_EXP_F: [f64; 257] = - [0.000167066692307963, 0.000454134353841497, 0.000967269282327174, 0.001536299780301573, - 0.002145967743718907, 0.002788798793574076, 0.003460264777836904, 0.004157295120833797, - 0.004877655983542396, 0.005619642207205489, 0.006381905937319183, 0.007163353183634991, - 0.007963077438017043, 0.008780314985808977, 0.009614413642502212, 0.010464810181029981, - 0.011331013597834600, 0.012212592426255378, 0.013109164931254991, 0.014020391403181943, - 0.014945968011691148, 0.015885621839973156, 0.016839106826039941, 0.017806200410911355, - 0.018786700744696024, 0.019780424338009740, 0.020787204072578114, 0.021806887504283581, - 0.022839335406385240, 0.023884420511558174, 0.024942026419731787, 0.026012046645134221, - 0.027094383780955803, 0.028188948763978646, 0.029295660224637411, 0.030414443910466622, - 0.031545232172893622, 0.032687963508959555, 0.033842582150874358, 0.035009037697397431, - 0.036187284781931443, 0.037377282772959382, 0.038578995503074871, 0.039792391023374139, - 0.041017441380414840, 0.042254122413316254, 0.043502413568888197, 0.044762297732943289, - 0.046033761076175184, 0.047316792913181561, 0.048611385573379504, 0.049917534282706379, - 0.051235237055126281, 0.052564494593071685, 0.053905310196046080, 0.055257689676697030, - 0.056621641283742870, 0.057997175631200659, 0.059384305633420280, 0.060783046445479660, - 0.062193415408541036, 0.063615431999807376, 0.065049117786753805, 0.066494496385339816, - 0.067951593421936643, 0.069420436498728783, 0.070901055162371843, 0.072393480875708752, - 0.073897746992364746, 0.075413888734058410, 0.076941943170480517, 0.078481949201606435, - 0.080033947542319905, 0.081597980709237419, 0.083174093009632397, 0.084762330532368146, - 0.086362741140756927, 0.087975374467270231, 0.089600281910032886, 0.091237516631040197, - 0.092887133556043569, 0.094549189376055873, 0.096223742550432825, 0.097910853311492213, - 0.099610583670637132, 0.101322997425953631, 0.103048160171257702, 0.104786139306570145, - 0.106537004050001632, 0.108300825451033755, 0.110077676405185357, 0.111867631670056283, - 0.113670767882744286, 0.115487163578633506, 0.117316899211555525, 0.119160057175327641, - 0.121016721826674792, 0.122886979509545108, 0.124770918580830933, 0.126668629437510671, - 0.128580204545228199, 0.130505738468330773, 0.132445327901387494, 0.134399071702213602, - 0.136367070926428829, 0.138349428863580176, 0.140346251074862399, 0.142357645432472146, - 0.144383722160634720, 0.146424593878344889, 0.148480375643866735, 0.150551185001039839, - 0.152637142027442801, 0.154738369384468027, 0.156854992369365148, 0.158987138969314129, - 0.161134939917591952, 0.163298528751901734, 0.165478041874935922, 0.167673618617250081, - 0.169885401302527550, 0.172113535315319977, 0.174358169171353411, 0.176619454590494829, - 0.178897546572478278, 0.181192603475496261, 0.183504787097767436, 0.185834262762197083, - 0.188181199404254262, 0.190545769663195363, 0.192928149976771296, 0.195328520679563189, - 0.197747066105098818, 0.200183974691911210, 0.202639439093708962, 0.205113656293837654, - 0.207606827724221982, 0.210119159388988230, 0.212650861992978224, 0.215202151075378628, - 0.217773247148700472, 0.220364375843359439, 0.222975768058120111, 0.225607660116683956, - 0.228260293930716618, 0.230933917169627356, 0.233628783437433291, 0.236345152457059560, - 0.239083290262449094, 0.241843469398877131, 0.244625969131892024, 0.247431075665327543, - 0.250259082368862240, 0.253110290015629402, 0.255985007030415324, 0.258883549749016173, - 0.261806242689362922, 0.264753418835062149, 0.267725419932044739, 0.270722596799059967, - 0.273745309652802915, 0.276793928448517301, 0.279868833236972869, 0.282970414538780746, - 0.286099073737076826, 0.289255223489677693, 0.292439288161892630, 0.295651704281261252, - 0.298892921015581847, 0.302163400675693528, 0.305463619244590256, 0.308794066934560185, - 0.312155248774179606, 0.315547685227128949, 0.318971912844957239, 0.322428484956089223, - 0.325917972393556354, 0.329440964264136438, 0.332998068761809096, 0.336589914028677717, - 0.340217149066780189, 0.343880444704502575, 0.347580494621637148, 0.351318016437483449, - 0.355093752866787626, 0.358908472948750001, 0.362762973354817997, 0.366658079781514379, - 0.370594648435146223, 0.374573567615902381, 0.378595759409581067, 0.382662181496010056, - 0.386773829084137932, 0.390931736984797384, 0.395136981833290435, 0.399390684475231350, - 0.403694012530530555, 0.408048183152032673, 0.412454465997161457, 0.416914186433003209, - 0.421428728997616908, 0.425999541143034677, 0.430628137288459167, 0.435316103215636907, - 0.440065100842354173, 0.444876873414548846, 0.449753251162755330, 0.454696157474615836, - 0.459707615642138023, 0.464789756250426511, 0.469944825283960310, 0.475175193037377708, - 0.480483363930454543, 0.485871987341885248, 0.491343869594032867, 0.496901987241549881, - 0.502549501841348056, 0.508289776410643213, 0.514126393814748894, 0.520063177368233931, - 0.526104213983620062, 0.532253880263043655, 0.538516872002862246, 0.544898237672440056, - 0.551403416540641733, 0.558038282262587892, 0.564809192912400615, 0.571723048664826150, - 0.578787358602845359, 0.586010318477268366, 0.593400901691733762, 0.600968966365232560, - 0.608725382079622346, 0.616682180915207878, 0.624852738703666200, 0.633251994214366398, - 0.641896716427266423, 0.650805833414571433, 0.660000841079000145, 0.669506316731925177, - 0.679350572264765806, 0.689566496117078431, 0.700192655082788606, 0.711274760805076456, - 0.722867659593572465, 0.735038092431424039, 0.747868621985195658, 0.761463388849896838, - 0.775956852040116218, 0.791527636972496285, 0.808421651523009044, 0.826993296643051101, - 0.847785500623990496, 0.871704332381204705, 0.900469929925747703, 0.938143680862176477, - 1.000000000000000000]; diff --git a/rand/rand_distr/tests/uniformity.rs b/rand/rand_distr/tests/uniformity.rs deleted file mode 100644 index d0d9d97..0000000 --- a/rand/rand_distr/tests/uniformity.rs +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use average::Histogram; -use rand::prelude::*; - -const N_BINS: usize = 100; -const N_SAMPLES: u32 = 1_000_000; -const TOL: f64 = 1e-3; -average::define_histogram!(hist, 100); -use hist::Histogram as Histogram100; - -#[test] -fn unit_sphere() { - const N_DIM: usize = 3; - let h = Histogram100::with_const_width(-1., 1.); - let mut histograms = [h.clone(), h.clone(), h]; - let dist = rand_distr::UnitSphere; - let mut rng = rand_pcg::Pcg32::from_entropy(); - for _ in 0..N_SAMPLES { - let v: [f64; 3] = dist.sample(&mut rng); - for i in 0..N_DIM { - histograms[i].add(v[i]).map_err( - |e| { println!("v: {}", v[i]); e } - ).unwrap(); - } - } - for h in &histograms { - let sum: u64 = h.bins().iter().sum(); - println!("{:?}", h); - for &b in h.bins() { - let p = (b as f64) / (sum as f64); - assert!((p - 1.0 / (N_BINS as f64)).abs() < TOL, "{}", p); - } - } -} - -#[test] -fn unit_circle() { - use std::f64::consts::PI; - let mut h = Histogram100::with_const_width(-PI, PI); - let dist = rand_distr::UnitCircle; - let mut rng = rand_pcg::Pcg32::from_entropy(); - for _ in 0..N_SAMPLES { - let v: [f64; 2] = dist.sample(&mut rng); - h.add(v[0].atan2(v[1])).unwrap(); - } - let sum: u64 = h.bins().iter().sum(); - println!("{:?}", h); - for &b in h.bins() { - let p = (b as f64) / (sum as f64); - assert!((p - 1.0 / (N_BINS as f64)).abs() < TOL, "{}", p); - } -} diff --git a/rand/rand_hc/CHANGELOG.md b/rand/rand_hc/CHANGELOG.md deleted file mode 100644 index a629d7d..0000000 --- a/rand/rand_hc/CHANGELOG.md +++ /dev/null @@ -1,16 +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.2.0] - 2019-06-12 -- Bump minor crate version since rand_core bump is a breaking change -- Switch to Edition 2018 - -## [0.1.1] - 2019-06-06 - yanked -- Bump `rand_core` version -- Adjust usage of `#[inline]` - -## [0.1.0] - 2018-10-17 -- Pulled out of the Rand crate diff --git a/rand/rand_hc/COPYRIGHT b/rand/rand_hc/COPYRIGHT deleted file mode 100644 index 468d907..0000000 --- a/rand/rand_hc/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 or - or the MIT license - or , at your option. - -The Rand project includes code from the Rust project -published under these same licenses. diff --git a/rand/rand_hc/Cargo.toml b/rand/rand_hc/Cargo.toml deleted file mode 100644 index 40cea06..0000000 --- a/rand/rand_hc/Cargo.toml +++ /dev/null @@ -1,22 +0,0 @@ -[package] -name = "rand_hc" -version = "0.2.0" -authors = ["The Rand 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_hc/" -homepage = "https://crates.io/crates/rand_hc" -description = """ -HC128 random number generator -""" -keywords = ["random", "rng", "hc128"] -categories = ["algorithms", "no-std"] -edition = "2018" - -[badges] -travis-ci = { repository = "rust-random/rand" } -appveyor = { repository = "rust-random/rand" } - -[dependencies] -rand_core = { path = "../rand_core", version = "0.5" } diff --git a/rand/rand_hc/LICENSE-APACHE b/rand/rand_hc/LICENSE-APACHE deleted file mode 100644 index 17d7468..0000000 --- a/rand/rand_hc/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_hc/LICENSE-MIT b/rand/rand_hc/LICENSE-MIT deleted file mode 100644 index cf65607..0000000 --- a/rand/rand_hc/LICENSE-MIT +++ /dev/null @@ -1,25 +0,0 @@ -Copyright 2018 Developers of the Rand project - -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_hc/README.md b/rand/rand_hc/README.md deleted file mode 100644 index 36449c0..0000000 --- a/rand/rand_hc/README.md +++ /dev/null @@ -1,45 +0,0 @@ -# rand_hc - -[![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_hc.svg)](https://crates.io/crates/rand_hc) -[[![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_hc) -[![API](https://docs.rs/rand_hc/badge.svg)](https://docs.rs/rand_hc) -[![Minimum rustc version](https://img.shields.io/badge/rustc-1.32+-lightgray.svg)](https://github.com/rust-random/rand#rust-version-requirements) - -A cryptographically secure random number generator that uses the HC-128 -algorithm. - -HC-128 is a stream cipher designed by Hongjun Wu[^1], that we use as an -RNG. It is selected as one of the "stream ciphers suitable for widespread -adoption" by eSTREAM[^2]. - -Links: - -- [API documentation (master)](https://rust-random.github.io/rand/rand_hc) -- [API documentation (docs.rs)](https://docs.rs/rand_hc) -- [Changelog](https://github.com/rust-random/rand/blob/master/rand_hc/CHANGELOG.md) - -[rand]: https://crates.io/crates/rand -[^1]: Hongjun Wu (2008). ["The Stream Cipher HC-128"]( - http://www.ecrypt.eu.org/stream/p3ciphers/hc/hc128_p3.pdf). - *The eSTREAM Finalists*, LNCS 4986, pp. 39–47, Springer-Verlag. - -[^2]: [eSTREAM: the ECRYPT Stream Cipher Project]( - http://www.ecrypt.eu.org/stream/) - - -## Crate Features - -`rand_hc` is `no_std` compatible. It does not require any functionality -outside of the `core` lib, thus there are no features to configure. - - -# License - -`rand_hc` 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_hc/src/hc128.rs b/rand/rand_hc/src/hc128.rs deleted file mode 100644 index a320f48..0000000 --- a/rand/rand_hc/src/hc128.rs +++ /dev/null @@ -1,464 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The HC-128 random number generator. - -use core::fmt; -use rand_core::{CryptoRng, RngCore, SeedableRng, Error, le}; -use rand_core::block::{BlockRngCore, BlockRng}; - -const SEED_WORDS: usize = 8; // 128 bit key followed by 128 bit iv - -/// A cryptographically secure random number generator that uses the HC-128 -/// algorithm. -/// -/// HC-128 is a stream cipher designed by Hongjun Wu[^1], that we use as an -/// RNG. It is selected as one of the "stream ciphers suitable for widespread -/// adoption" by eSTREAM[^2]. -/// -/// HC-128 is an array based RNG. In this it is similar to RC-4 and ISAAC before -/// it, but those have never been proven cryptographically secure (or have even -/// been significantly compromised, as in the case of RC-4[^5]). -/// -/// Because HC-128 works with simple indexing into a large array and with a few -/// operations that parallelize well, it has very good performance. The size of -/// the array it needs, 4kb, can however be a disadvantage. -/// -/// This implementation is not based on the version of HC-128 submitted to the -/// eSTREAM contest, but on a later version by the author with a few small -/// improvements from December 15, 2009[^3]. -/// -/// HC-128 has no known weaknesses that are easier to exploit than doing a -/// brute-force search of 2128. A very comprehensive analysis of the -/// current state of known attacks / weaknesses of HC-128 is given in *Some -/// Results On Analysis And Implementation Of HC-128 Stream Cipher*[^4]. -/// -/// The average cycle length is expected to be -/// 21024*32+10-1 = 232777. -/// We support seeding with a 256-bit array, which matches the 128-bit key -/// concatenated with a 128-bit IV from the stream cipher. -/// -/// This implementation uses an output buffer of sixteen `u32` words, and uses -/// [`BlockRng`] to implement the [`RngCore`] methods. -/// -/// ## References -/// [^1]: Hongjun Wu (2008). ["The Stream Cipher HC-128"]( -/// http://www.ecrypt.eu.org/stream/p3ciphers/hc/hc128_p3.pdf). -/// *The eSTREAM Finalists*, LNCS 4986, pp. 39–47, Springer-Verlag. -/// -/// [^2]: [eSTREAM: the ECRYPT Stream Cipher Project]( -/// http://www.ecrypt.eu.org/stream/) -/// -/// [^3]: Hongjun Wu, [Stream Ciphers HC-128 and HC-256]( -/// https://www.ntu.edu.sg/home/wuhj/research/hc/index.html) -/// -/// [^4]: Shashwat Raizada (January 2015),["Some Results On Analysis And -/// Implementation Of HC-128 Stream Cipher"]( -/// http://library.isical.ac.in:8080/jspui/bitstream/123456789/6636/1/TH431.pdf). -/// -/// [^5]: Internet Engineering Task Force (February 2015), -/// ["Prohibiting RC4 Cipher Suites"](https://tools.ietf.org/html/rfc7465). -#[derive(Clone, Debug)] -pub struct Hc128Rng(BlockRng); - -impl RngCore for Hc128Rng { - #[inline] - fn next_u32(&mut self) -> u32 { - self.0.next_u32() - } - - #[inline] - fn next_u64(&mut self) -> u64 { - self.0.next_u64() - } - - #[inline] - fn fill_bytes(&mut self, dest: &mut [u8]) { - self.0.fill_bytes(dest) - } - - #[inline] - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - self.0.try_fill_bytes(dest) - } -} - -impl SeedableRng for Hc128Rng { - type Seed = ::Seed; - - #[inline] - fn from_seed(seed: Self::Seed) -> Self { - Hc128Rng(BlockRng::::from_seed(seed)) - } - - #[inline] - fn from_rng(rng: R) -> Result { - BlockRng::::from_rng(rng).map(Hc128Rng) - } -} - -impl CryptoRng for Hc128Rng {} - -/// The core of `Hc128Rng`, used with `BlockRng`. -#[derive(Clone)] -pub struct Hc128Core { - t: [u32; 1024], - counter1024: usize, -} - -// Custom Debug implementation that does not expose the internal state -impl fmt::Debug for Hc128Core { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "Hc128Core {{}}") - } -} - -impl BlockRngCore for Hc128Core { - type Item = u32; - type Results = [u32; 16]; - - fn generate(&mut self, results: &mut Self::Results) { - assert!(self.counter1024 % 16 == 0); - - let cc = self.counter1024 % 512; - let dd = (cc + 16) % 512; - let ee = cc.wrapping_sub(16) % 512; - - if self.counter1024 & 512 == 0 { - // P block - results[0] = self.step_p(cc+0, cc+1, ee+13, ee+6, ee+4); - results[1] = self.step_p(cc+1, cc+2, ee+14, ee+7, ee+5); - results[2] = self.step_p(cc+2, cc+3, ee+15, ee+8, ee+6); - results[3] = self.step_p(cc+3, cc+4, cc+0, ee+9, ee+7); - results[4] = self.step_p(cc+4, cc+5, cc+1, ee+10, ee+8); - results[5] = self.step_p(cc+5, cc+6, cc+2, ee+11, ee+9); - results[6] = self.step_p(cc+6, cc+7, cc+3, ee+12, ee+10); - results[7] = self.step_p(cc+7, cc+8, cc+4, ee+13, ee+11); - results[8] = self.step_p(cc+8, cc+9, cc+5, ee+14, ee+12); - results[9] = self.step_p(cc+9, cc+10, cc+6, ee+15, ee+13); - results[10] = self.step_p(cc+10, cc+11, cc+7, cc+0, ee+14); - results[11] = self.step_p(cc+11, cc+12, cc+8, cc+1, ee+15); - results[12] = self.step_p(cc+12, cc+13, cc+9, cc+2, cc+0); - results[13] = self.step_p(cc+13, cc+14, cc+10, cc+3, cc+1); - results[14] = self.step_p(cc+14, cc+15, cc+11, cc+4, cc+2); - results[15] = self.step_p(cc+15, dd+0, cc+12, cc+5, cc+3); - } else { - // Q block - results[0] = self.step_q(cc+0, cc+1, ee+13, ee+6, ee+4); - results[1] = self.step_q(cc+1, cc+2, ee+14, ee+7, ee+5); - results[2] = self.step_q(cc+2, cc+3, ee+15, ee+8, ee+6); - results[3] = self.step_q(cc+3, cc+4, cc+0, ee+9, ee+7); - results[4] = self.step_q(cc+4, cc+5, cc+1, ee+10, ee+8); - results[5] = self.step_q(cc+5, cc+6, cc+2, ee+11, ee+9); - results[6] = self.step_q(cc+6, cc+7, cc+3, ee+12, ee+10); - results[7] = self.step_q(cc+7, cc+8, cc+4, ee+13, ee+11); - results[8] = self.step_q(cc+8, cc+9, cc+5, ee+14, ee+12); - results[9] = self.step_q(cc+9, cc+10, cc+6, ee+15, ee+13); - results[10] = self.step_q(cc+10, cc+11, cc+7, cc+0, ee+14); - results[11] = self.step_q(cc+11, cc+12, cc+8, cc+1, ee+15); - results[12] = self.step_q(cc+12, cc+13, cc+9, cc+2, cc+0); - results[13] = self.step_q(cc+13, cc+14, cc+10, cc+3, cc+1); - results[14] = self.step_q(cc+14, cc+15, cc+11, cc+4, cc+2); - results[15] = self.step_q(cc+15, dd+0, cc+12, cc+5, cc+3); - } - self.counter1024 = self.counter1024.wrapping_add(16); - } -} - -impl Hc128Core { - // One step of HC-128, update P and generate 32 bits keystream - #[inline(always)] - fn step_p(&mut self, i: usize, i511: usize, i3: usize, i10: usize, i12: usize) - -> u32 - { - let (p, q) = self.t.split_at_mut(512); - // FIXME: it would be great if we the bounds checks here could be - // optimized out, and we would not need unsafe. - // This improves performance by about 7%. - unsafe { - let temp0 = p.get_unchecked(i511).rotate_right(23); - let temp1 = p.get_unchecked(i3).rotate_right(10); - let temp2 = p.get_unchecked(i10).rotate_right(8); - *p.get_unchecked_mut(i) = p.get_unchecked(i) - .wrapping_add(temp2) - .wrapping_add(temp0 ^ temp1); - let temp3 = { - // The h1 function in HC-128 - let a = *p.get_unchecked(i12) as u8; - let c = (p.get_unchecked(i12) >> 16) as u8; - q[a as usize].wrapping_add(q[256 + c as usize]) - }; - temp3 ^ p.get_unchecked(i) - } - } - - // One step of HC-128, update Q and generate 32 bits keystream - // Similar to `step_p`, but `p` and `q` are swapped, and the rotates are to - // the left instead of to the right. - #[inline(always)] - fn step_q(&mut self, i: usize, i511: usize, i3: usize, i10: usize, i12: usize) - -> u32 - { - let (p, q) = self.t.split_at_mut(512); - unsafe { - let temp0 = q.get_unchecked(i511).rotate_left(23); - let temp1 = q.get_unchecked(i3).rotate_left(10); - let temp2 = q.get_unchecked(i10).rotate_left(8); - *q.get_unchecked_mut(i) = q.get_unchecked(i) - .wrapping_add(temp2) - .wrapping_add(temp0 ^ temp1); - let temp3 = { - // The h2 function in HC-128 - let a = *q.get_unchecked(i12) as u8; - let c = (q.get_unchecked(i12) >> 16) as u8; - p[a as usize].wrapping_add(p[256 + c as usize]) - }; - temp3 ^ q.get_unchecked(i) - } - } - - fn sixteen_steps(&mut self) { - assert!(self.counter1024 % 16 == 0); - - let cc = self.counter1024 % 512; - let dd = (cc + 16) % 512; - let ee = cc.wrapping_sub(16) % 512; - - if self.counter1024 < 512 { - // P block - self.t[cc+0] = self.step_p(cc+0, cc+1, ee+13, ee+6, ee+4); - self.t[cc+1] = self.step_p(cc+1, cc+2, ee+14, ee+7, ee+5); - self.t[cc+2] = self.step_p(cc+2, cc+3, ee+15, ee+8, ee+6); - self.t[cc+3] = self.step_p(cc+3, cc+4, cc+0, ee+9, ee+7); - self.t[cc+4] = self.step_p(cc+4, cc+5, cc+1, ee+10, ee+8); - self.t[cc+5] = self.step_p(cc+5, cc+6, cc+2, ee+11, ee+9); - self.t[cc+6] = self.step_p(cc+6, cc+7, cc+3, ee+12, ee+10); - self.t[cc+7] = self.step_p(cc+7, cc+8, cc+4, ee+13, ee+11); - self.t[cc+8] = self.step_p(cc+8, cc+9, cc+5, ee+14, ee+12); - self.t[cc+9] = self.step_p(cc+9, cc+10, cc+6, ee+15, ee+13); - self.t[cc+10] = self.step_p(cc+10, cc+11, cc+7, cc+0, ee+14); - self.t[cc+11] = self.step_p(cc+11, cc+12, cc+8, cc+1, ee+15); - self.t[cc+12] = self.step_p(cc+12, cc+13, cc+9, cc+2, cc+0); - self.t[cc+13] = self.step_p(cc+13, cc+14, cc+10, cc+3, cc+1); - self.t[cc+14] = self.step_p(cc+14, cc+15, cc+11, cc+4, cc+2); - self.t[cc+15] = self.step_p(cc+15, dd+0, cc+12, cc+5, cc+3); - } else { - // Q block - self.t[cc+512+0] = self.step_q(cc+0, cc+1, ee+13, ee+6, ee+4); - self.t[cc+512+1] = self.step_q(cc+1, cc+2, ee+14, ee+7, ee+5); - self.t[cc+512+2] = self.step_q(cc+2, cc+3, ee+15, ee+8, ee+6); - self.t[cc+512+3] = self.step_q(cc+3, cc+4, cc+0, ee+9, ee+7); - self.t[cc+512+4] = self.step_q(cc+4, cc+5, cc+1, ee+10, ee+8); - self.t[cc+512+5] = self.step_q(cc+5, cc+6, cc+2, ee+11, ee+9); - self.t[cc+512+6] = self.step_q(cc+6, cc+7, cc+3, ee+12, ee+10); - self.t[cc+512+7] = self.step_q(cc+7, cc+8, cc+4, ee+13, ee+11); - self.t[cc+512+8] = self.step_q(cc+8, cc+9, cc+5, ee+14, ee+12); - self.t[cc+512+9] = self.step_q(cc+9, cc+10, cc+6, ee+15, ee+13); - self.t[cc+512+10] = self.step_q(cc+10, cc+11, cc+7, cc+0, ee+14); - self.t[cc+512+11] = self.step_q(cc+11, cc+12, cc+8, cc+1, ee+15); - self.t[cc+512+12] = self.step_q(cc+12, cc+13, cc+9, cc+2, cc+0); - self.t[cc+512+13] = self.step_q(cc+13, cc+14, cc+10, cc+3, cc+1); - self.t[cc+512+14] = self.step_q(cc+14, cc+15, cc+11, cc+4, cc+2); - self.t[cc+512+15] = self.step_q(cc+15, dd+0, cc+12, cc+5, cc+3); - } - self.counter1024 += 16; - } - - // Initialize an HC-128 random number generator. The seed has to be - // 256 bits in length (`[u32; 8]`), matching the 128 bit `key` followed by - // 128 bit `iv` when HC-128 where to be used as a stream cipher. - #[inline(always)] // single use: SeedableRng::from_seed - fn init(seed: [u32; SEED_WORDS]) -> Self { - #[inline] - fn f1(x: u32) -> u32 { - x.rotate_right(7) ^ x.rotate_right(18) ^ (x >> 3) - } - - #[inline] - fn f2(x: u32) -> u32 { - x.rotate_right(17) ^ x.rotate_right(19) ^ (x >> 10) - } - - let mut t = [0u32; 1024]; - - // Expand the key and iv into P and Q - let (key, iv) = seed.split_at(4); - t[..4].copy_from_slice(key); - t[4..8].copy_from_slice(key); - t[8..12].copy_from_slice(iv); - t[12..16].copy_from_slice(iv); - - // Generate the 256 intermediate values W[16] ... W[256+16-1], and - // copy the last 16 generated values to the start op P. - for i in 16..256+16 { - t[i] = f2(t[i-2]).wrapping_add(t[i-7]).wrapping_add(f1(t[i-15])) - .wrapping_add(t[i-16]).wrapping_add(i as u32); - } - { - let (p1, p2) = t.split_at_mut(256); - p1[0..16].copy_from_slice(&p2[0..16]); - } - - // Generate both the P and Q tables - for i in 16..1024 { - t[i] = f2(t[i-2]).wrapping_add(t[i-7]).wrapping_add(f1(t[i-15])) - .wrapping_add(t[i-16]).wrapping_add(256 + i as u32); - } - - let mut core = Self { t, counter1024: 0 }; - - // run the cipher 1024 steps - for _ in 0..64 { core.sixteen_steps() }; - core.counter1024 = 0; - core - } -} - -impl SeedableRng for Hc128Core { - type Seed = [u8; SEED_WORDS*4]; - - /// Create an HC-128 random number generator with a seed. The seed has to be - /// 256 bits in length, matching the 128 bit `key` followed by 128 bit `iv` - /// when HC-128 where to be used as a stream cipher. - fn from_seed(seed: Self::Seed) -> Self { - let mut seed_u32 = [0u32; SEED_WORDS]; - le::read_u32_into(&seed, &mut seed_u32); - Self::init(seed_u32) - } -} - -impl CryptoRng for Hc128Core {} - -#[cfg(test)] -mod test { - use ::rand_core::{RngCore, SeedableRng}; - use super::Hc128Rng; - - #[test] - // Test vector 1 from the paper "The Stream Cipher HC-128" - fn test_hc128_true_values_a() { - let seed = [0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, // key - 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; // iv - let mut rng = Hc128Rng::from_seed(seed); - - let mut results = [0u32; 16]; - for i in results.iter_mut() { *i = rng.next_u32(); } - let expected = [0x73150082, 0x3bfd03a0, 0xfb2fd77f, 0xaa63af0e, - 0xde122fc6, 0xa7dc29b6, 0x62a68527, 0x8b75ec68, - 0x9036db1e, 0x81896005, 0x00ade078, 0x491fbf9a, - 0x1cdc3013, 0x6c3d6e24, 0x90f664b2, 0x9cd57102]; - assert_eq!(results, expected); - } - - #[test] - // Test vector 2 from the paper "The Stream Cipher HC-128" - fn test_hc128_true_values_b() { - let seed = [0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, // key - 1,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; // iv - let mut rng = Hc128Rng::from_seed(seed); - - let mut results = [0u32; 16]; - for i in results.iter_mut() { *i = rng.next_u32(); } - let expected = [0xc01893d5, 0xb7dbe958, 0x8f65ec98, 0x64176604, - 0x36fc6724, 0xc82c6eec, 0x1b1c38a7, 0xc9b42a95, - 0x323ef123, 0x0a6a908b, 0xce757b68, 0x9f14f7bb, - 0xe4cde011, 0xaeb5173f, 0x89608c94, 0xb5cf46ca]; - assert_eq!(results, expected); - } - - #[test] - // Test vector 3 from the paper "The Stream Cipher HC-128" - fn test_hc128_true_values_c() { - let seed = [0x55,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, // key - 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; // iv - let mut rng = Hc128Rng::from_seed(seed); - - let mut results = [0u32; 16]; - for i in results.iter_mut() { *i = rng.next_u32(); } - let expected = [0x518251a4, 0x04b4930a, 0xb02af931, 0x0639f032, - 0xbcb4a47a, 0x5722480b, 0x2bf99f72, 0xcdc0e566, - 0x310f0c56, 0xd3cc83e8, 0x663db8ef, 0x62dfe07f, - 0x593e1790, 0xc5ceaa9c, 0xab03806f, 0xc9a6e5a0]; - assert_eq!(results, expected); - } - - #[test] - fn test_hc128_true_values_u64() { - let seed = [0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, // key - 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; // iv - let mut rng = Hc128Rng::from_seed(seed); - - let mut results = [0u64; 8]; - for i in results.iter_mut() { *i = rng.next_u64(); } - let expected = [0x3bfd03a073150082, 0xaa63af0efb2fd77f, - 0xa7dc29b6de122fc6, 0x8b75ec6862a68527, - 0x818960059036db1e, 0x491fbf9a00ade078, - 0x6c3d6e241cdc3013, 0x9cd5710290f664b2]; - assert_eq!(results, expected); - - // The RNG operates in a P block of 512 results and next a Q block. - // After skipping 2*800 u32 results we end up somewhere in the Q block - // of the second round - for _ in 0..800 { rng.next_u64(); } - - for i in results.iter_mut() { *i = rng.next_u64(); } - let expected = [0xd8c4d6ca84d0fc10, 0xf16a5d91dc66e8e7, - 0xd800de5bc37a8653, 0x7bae1f88c0dfbb4c, - 0x3bfe1f374e6d4d14, 0x424b55676be3fa06, - 0xe3a1e8758cbff579, 0x417f7198c5652bcd]; - assert_eq!(results, expected); - } - - #[test] - fn test_hc128_true_values_bytes() { - let seed = [0x55,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, // key - 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; // iv - let mut rng = Hc128Rng::from_seed(seed); - let expected = [0x31, 0xf9, 0x2a, 0xb0, 0x32, 0xf0, 0x39, 0x06, - 0x7a, 0xa4, 0xb4, 0xbc, 0x0b, 0x48, 0x22, 0x57, - 0x72, 0x9f, 0xf9, 0x2b, 0x66, 0xe5, 0xc0, 0xcd, - 0x56, 0x0c, 0x0f, 0x31, 0xe8, 0x83, 0xcc, 0xd3, - 0xef, 0xb8, 0x3d, 0x66, 0x7f, 0xe0, 0xdf, 0x62, - 0x90, 0x17, 0x3e, 0x59, 0x9c, 0xaa, 0xce, 0xc5, - 0x6f, 0x80, 0x03, 0xab, 0xa0, 0xe5, 0xa6, 0xc9, - 0x60, 0x95, 0x84, 0x7a, 0xa5, 0x68, 0x5a, 0x84, - 0xea, 0xd5, 0xf3, 0xea, 0x73, 0xa9, 0xad, 0x01, - 0x79, 0x7d, 0xbe, 0x9f, 0xea, 0xe3, 0xf9, 0x74, - 0x0e, 0xda, 0x2f, 0xa0, 0xe4, 0x7b, 0x4b, 0x1b, - 0xdd, 0x17, 0x69, 0x4a, 0xfe, 0x9f, 0x56, 0x95, - 0xad, 0x83, 0x6b, 0x9d, 0x60, 0xa1, 0x99, 0x96, - 0x90, 0x00, 0x66, 0x7f, 0xfa, 0x7e, 0x65, 0xe9, - 0xac, 0x8b, 0x92, 0x34, 0x77, 0xb4, 0x23, 0xd0, - 0xb9, 0xab, 0xb1, 0x47, 0x7d, 0x4a, 0x13, 0x0a]; - - // Pick a somewhat large buffer so we can test filling with the - // remainder from `state.results`, directly filling the buffer, and - // filling the remainder of the buffer. - let mut buffer = [0u8; 16*4*2]; - // Consume a value so that we have a remainder. - assert!(rng.next_u64() == 0x04b4930a518251a4); - rng.fill_bytes(&mut buffer); - - // [u8; 128] doesn't implement PartialEq - assert_eq!(buffer.len(), expected.len()); - for (b, e) in buffer.iter().zip(expected.iter()) { - assert_eq!(b, e); - } - } - - #[test] - fn test_hc128_clone() { - let seed = [0x55,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, // key - 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; // iv - let mut rng1 = Hc128Rng::from_seed(seed); - let mut rng2 = rng1.clone(); - for _ in 0..16 { - assert_eq!(rng1.next_u32(), rng2.next_u32()); - } - } -} diff --git a/rand/rand_hc/src/lib.rs b/rand/rand_hc/src/lib.rs deleted file mode 100644 index c1ae665..0000000 --- a/rand/rand_hc/src/lib.rs +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The HC128 random number generator. - -#![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))))] - -#![no_std] - -mod hc128; - -pub use hc128::{Hc128Rng, Hc128Core}; diff --git a/rand/rand_isaac/CHANGELOG.md b/rand/rand_isaac/CHANGELOG.md deleted file mode 100644 index 0a5591f..0000000 --- a/rand/rand_isaac/CHANGELOG.md +++ /dev/null @@ -1,21 +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.2.0] - 2019-06-12 -- Bump minor crate version since rand_core bump is a breaking change -- Switch to Edition 2018 - -## [0.1.2] - 2019-06-06 - yanked -- Bump `rand_core` version -- Remove deprecated code -- Adjust usage of `#[inline]` - -## [0.1.1] - 2018-11-26 -- Fix `rand_core` version requirement -- Fix doc links - -## [0.1.0] - 2018-10-17 -- Pulled out of the Rand crate diff --git a/rand/rand_isaac/COPYRIGHT b/rand/rand_isaac/COPYRIGHT deleted file mode 100644 index 468d907..0000000 --- a/rand/rand_isaac/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 or - or the MIT license - or , at your option. - -The Rand project includes code from the Rust project -published under these same licenses. diff --git a/rand/rand_isaac/Cargo.toml b/rand/rand_isaac/Cargo.toml deleted file mode 100644 index c11c305..0000000 --- a/rand/rand_isaac/Cargo.toml +++ /dev/null @@ -1,31 +0,0 @@ -[package] -name = "rand_isaac" -version = "0.2.0" -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_isaac/" -homepage = "https://crates.io/crates/rand_isaac" -description = """ -ISAAC random number generator -""" -keywords = ["random", "rng", "isaac"] -categories = ["algorithms", "no-std"] -edition = "2018" - -[badges] -travis-ci = { repository = "rust-random/rand" } -appveyor = { repository = "rust-random/rand" } - -[features] -serde1 = ["serde", "rand_core/serde1"] - -[dependencies] -rand_core = { path = "../rand_core", version = "0.5" } -serde = { version = "1", features = ["derive"], optional = true } - -[dev-dependencies] -# This is for testing serde, unfortunately we can't specify feature-gated dev -# deps yet, see: https://github.com/rust-lang/cargo/issues/1596 -bincode = "1" diff --git a/rand/rand_isaac/LICENSE-APACHE b/rand/rand_isaac/LICENSE-APACHE deleted file mode 100644 index 17d7468..0000000 --- a/rand/rand_isaac/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_isaac/LICENSE-MIT b/rand/rand_isaac/LICENSE-MIT deleted file mode 100644 index d93b5ba..0000000 --- a/rand/rand_isaac/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_isaac/README.md b/rand/rand_isaac/README.md deleted file mode 100644 index c16c63f..0000000 --- a/rand/rand_isaac/README.md +++ /dev/null @@ -1,47 +0,0 @@ -# rand_isaac - -[![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_isaac.svg)](https://crates.io/crates/rand_isaac) -[![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_isaac) -[![API](https://docs.rs/rand_isaac/badge.svg)](https://docs.rs/rand_isaac) -[![Minimum rustc version](https://img.shields.io/badge/rustc-1.32+-lightgray.svg)](https://github.com/rust-random/rand#rust-version-requirements) - -Implements the ISAAC and ISAAC-64 random number generators. - -ISAAC stands for "Indirection, Shift, Accumulate, Add, and Count" which are -the principal bitwise operations employed. It is the most advanced of a -series of array based random number generator designed by Robert Jenkins -in 1996[^1][^2]. - -ISAAC is notably fast and produces excellent quality random numbers for -non-cryptographic applications. - -Links: - -- [API documentation (master)](https://rust-random.github.io/rand/rand_isaac) -- [API documentation (docs.rs)](https://docs.rs/rand_isaac) -- [Changelog](https://github.com/rust-random/rand/blob/master/rand_isaac/CHANGELOG.md) - -[rand]: https://crates.io/crates/rand -[^1]: Bob Jenkins, [*ISAAC: A fast cryptographic random number generator*](http://burtleburtle.net/bob/rand/isaacafa.html) -[^2]: Bob Jenkins, [*ISAAC and RC4*](http://burtleburtle.net/bob/rand/isaac.html) - - -## Crate Features - -`rand_isaac` is `no_std` compatible. It does not require any functionality -outside of the `core` lib, thus there are no features to configure. - -The `serde1` feature includes implementations of `Serialize` and `Deserialize` -for the included RNGs. - - -# License - -`rand_isaac` 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_isaac/src/isaac.rs b/rand/rand_isaac/src/isaac.rs deleted file mode 100644 index 2caf61a..0000000 --- a/rand/rand_isaac/src/isaac.rs +++ /dev/null @@ -1,476 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// Copyright 2013-2018 The Rust Project Developers. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The ISAAC random number generator. - -use core::{fmt, slice}; -use core::num::Wrapping as w; -#[cfg(feature="serde1")] use serde::{Serialize, Deserialize}; -use rand_core::{RngCore, SeedableRng, Error, le}; -use rand_core::block::{BlockRngCore, BlockRng}; -use crate::isaac_array::IsaacArray; - -#[allow(non_camel_case_types)] -type w32 = w; - -const RAND_SIZE_LEN: usize = 8; -const RAND_SIZE: usize = 1 << RAND_SIZE_LEN; - -/// A random number generator that uses the ISAAC algorithm. -/// -/// ISAAC stands for "Indirection, Shift, Accumulate, Add, and Count" which are -/// the principal bitwise operations employed. It is the most advanced of a -/// series of array based random number generator designed by Robert Jenkins -/// in 1996[^1][^2]. -/// -/// ISAAC is notably fast and produces excellent quality random numbers for -/// non-cryptographic applications. -/// -/// In spite of being designed with cryptographic security in mind, ISAAC hasn't -/// been stringently cryptanalyzed and thus cryptographers do not not -/// consensually trust it to be secure. When looking for a secure RNG, prefer -/// `Hc128Rng` from the [`rand_hc`] crate instead, which, like ISAAC, is an -/// array-based RNG and one of the stream-ciphers selected the by eSTREAM -/// -/// In 2006 an improvement to ISAAC was suggested by Jean-Philippe Aumasson, -/// named ISAAC+[^3]. But because the specification is not complete, because -/// there is no good implementation, and because the suggested bias may not -/// exist, it is not implemented here. -/// -/// ## Overview of the ISAAC algorithm: -/// (in pseudo-code) -/// -/// ```text -/// Input: a, b, c, s[256] // state -/// Output: r[256] // results -/// -/// mix(a,i) = a ^ a << 13 if i = 0 mod 4 -/// a ^ a >> 6 if i = 1 mod 4 -/// a ^ a << 2 if i = 2 mod 4 -/// a ^ a >> 16 if i = 3 mod 4 -/// -/// c = c + 1 -/// b = b + c -/// -/// for i in 0..256 { -/// x = s_[i] -/// a = f(a,i) + s[i+128 mod 256] -/// y = a + b + s[x>>2 mod 256] -/// s[i] = y -/// b = x + s[y>>10 mod 256] -/// r[i] = b -/// } -/// ``` -/// -/// Numbers are generated in blocks of 256. This means the function above only -/// runs once every 256 times you ask for a next random number. In all other -/// circumstances the last element of the results array is returned. -/// -/// ISAAC therefore needs a lot of memory, relative to other non-crypto RNGs. -/// 2 * 256 * 4 = 2 kb to hold the state and results. -/// -/// This implementation uses [`BlockRng`] to implement the [`RngCore`] methods. -/// -/// ## References -/// [^1]: Bob Jenkins, [*ISAAC: A fast cryptographic random number generator*]( -/// http://burtleburtle.net/bob/rand/isaacafa.html) -/// -/// [^2]: Bob Jenkins, [*ISAAC and RC4*]( -/// http://burtleburtle.net/bob/rand/isaac.html) -/// -/// [^3]: Jean-Philippe Aumasson, [*On the pseudo-random generator ISAAC*]( -/// https://eprint.iacr.org/2006/438) -/// -/// [`rand_hc`]: https://docs.rs/rand_hc -#[derive(Clone, Debug)] -#[cfg_attr(feature="serde1", derive(Serialize, Deserialize))] -pub struct IsaacRng(BlockRng); - -impl RngCore for IsaacRng { - #[inline] - fn next_u32(&mut self) -> u32 { - self.0.next_u32() - } - - #[inline] - fn next_u64(&mut self) -> u64 { - self.0.next_u64() - } - - #[inline] - fn fill_bytes(&mut self, dest: &mut [u8]) { - self.0.fill_bytes(dest) - } - - #[inline] - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - self.0.try_fill_bytes(dest) - } -} - -impl SeedableRng for IsaacRng { - type Seed = ::Seed; - - #[inline] - fn from_seed(seed: Self::Seed) -> Self { - IsaacRng(BlockRng::::from_seed(seed)) - } - - /// Create an ISAAC random number generator using an `u64` as seed. - /// If `seed == 0` this will produce the same stream of random numbers as - /// the reference implementation when used unseeded. - #[inline] - fn seed_from_u64(seed: u64) -> Self { - IsaacRng(BlockRng::::seed_from_u64(seed)) - } - - #[inline] - fn from_rng(rng: S) -> Result { - BlockRng::::from_rng(rng).map(|rng| IsaacRng(rng)) - } -} - -/// The core of [`IsaacRng`], used with [`BlockRng`]. -#[derive(Clone)] -#[cfg_attr(feature="serde1", derive(Serialize, Deserialize))] -pub struct IsaacCore { - #[cfg_attr(feature="serde1",serde(with="super::isaac_array::isaac_array_serde"))] - mem: [w32; RAND_SIZE], - a: w32, - b: w32, - c: w32, -} - -// Custom Debug implementation that does not expose the internal state -impl fmt::Debug for IsaacCore { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "IsaacCore {{}}") - } -} - -impl BlockRngCore for IsaacCore { - type Item = u32; - type Results = IsaacArray; - - /// Refills the output buffer, `results`. See also the pseudocode desciption - /// of the algorithm in the `IsaacRng` documentation. - /// - /// Optimisations used (similar to the reference implementation): - /// - /// - The loop is unrolled 4 times, once for every constant of mix(). - /// - The contents of the main loop are moved to a function `rngstep`, to - /// reduce code duplication. - /// - We use local variables for a and b, which helps with optimisations. - /// - We split the main loop in two, one that operates over 0..128 and one - /// over 128..256. This way we can optimise out the addition and modulus - /// from `s[i+128 mod 256]`. - /// - We maintain one index `i` and add `m` or `m2` as base (m2 for the - /// `s[i+128 mod 256]`), relying on the optimizer to turn it into pointer - /// arithmetic. - /// - We fill `results` backwards. The reference implementation reads values - /// from `results` in reverse. We read them in the normal direction, to - /// make `fill_bytes` a memcopy. To maintain compatibility we fill in - /// reverse. - fn generate(&mut self, results: &mut IsaacArray) { - self.c += w(1); - // abbreviations - let mut a = self.a; - let mut b = self.b + self.c; - const MIDPOINT: usize = RAND_SIZE / 2; - - #[inline] - fn ind(mem:&[w32; RAND_SIZE], v: w32, amount: usize) -> w32 { - let index = (v >> amount).0 as usize % RAND_SIZE; - mem[index] - } - - #[inline] - fn rngstep(mem: &mut [w32; RAND_SIZE], - results: &mut [u32; RAND_SIZE], - mix: w32, - a: &mut w32, - b: &mut w32, - base: usize, - m: usize, - m2: usize) { - let x = mem[base + m]; - *a = mix + mem[base + m2]; - let y = *a + *b + ind(&mem, x, 2); - mem[base + m] = y; - *b = x + ind(&mem, y, 2 + RAND_SIZE_LEN); - results[RAND_SIZE - 1 - base - m] = (*b).0; - } - - let mut m = 0; - let mut m2 = MIDPOINT; - for i in (0..MIDPOINT/4).map(|i| i * 4) { - rngstep(&mut self.mem, results, a ^ (a << 13), &mut a, &mut b, i + 0, m, m2); - rngstep(&mut self.mem, results, a ^ (a >> 6 ), &mut a, &mut b, i + 1, m, m2); - rngstep(&mut self.mem, results, a ^ (a << 2 ), &mut a, &mut b, i + 2, m, m2); - rngstep(&mut self.mem, results, a ^ (a >> 16), &mut a, &mut b, i + 3, m, m2); - } - - m = MIDPOINT; - m2 = 0; - for i in (0..MIDPOINT/4).map(|i| i * 4) { - rngstep(&mut self.mem, results, a ^ (a << 13), &mut a, &mut b, i + 0, m, m2); - rngstep(&mut self.mem, results, a ^ (a >> 6 ), &mut a, &mut b, i + 1, m, m2); - rngstep(&mut self.mem, results, a ^ (a << 2 ), &mut a, &mut b, i + 2, m, m2); - rngstep(&mut self.mem, results, a ^ (a >> 16), &mut a, &mut b, i + 3, m, m2); - } - - self.a = a; - self.b = b; - } -} - -impl IsaacCore { - /// Create a new ISAAC random number generator. - /// - /// The author Bob Jenkins describes how to best initialize ISAAC here: - /// - /// The answer is included here just in case: - /// - /// "No, you don't need a full 8192 bits of seed data. Normal key sizes will - /// do fine, and they should have their expected strength (eg a 40-bit key - /// will take as much time to brute force as 40-bit keysΒ usually will). You - /// could fill the remainder with 0, but set the last array element to the - /// length of the key provided (to distinguish keys that differ only by - /// different amounts of 0 padding). You do still need to call `randinit()` - /// to make sure the initial state isn't uniform-looking." - /// "After publishing ISAAC, I wanted to limit the key to half the size of - /// `r[]`, and repeat it twice. That would have made it hard to provide a - /// key that sets the whole internal state to anything convenient. But I'd - /// already published it." - /// - /// And his answer to the question "For my code, would repeating the key - /// over and over to fill 256 integers be a better solution than - /// zero-filling, or would they essentially be the same?": - /// "If the seed is under 32 bytes, they're essentially the same, otherwise - /// repeating the seed would be stronger. randinit() takes a chunk of 32 - /// bytes, mixes it, and combines that with the next 32 bytes, et cetera. - /// Then loops over all the elements the same way a second time." - #[inline] - fn init(mut mem: [w32; RAND_SIZE], rounds: u32) -> Self { - fn mix(a: &mut w32, b: &mut w32, c: &mut w32, d: &mut w32, - e: &mut w32, f: &mut w32, g: &mut w32, h: &mut w32) { - *a ^= *b << 11; *d += *a; *b += *c; - *b ^= *c >> 2; *e += *b; *c += *d; - *c ^= *d << 8; *f += *c; *d += *e; - *d ^= *e >> 16; *g += *d; *e += *f; - *e ^= *f << 10; *h += *e; *f += *g; - *f ^= *g >> 4; *a += *f; *g += *h; - *g ^= *h << 8; *b += *g; *h += *a; - *h ^= *a >> 9; *c += *h; *a += *b; - } - - // These numbers are the result of initializing a...h with the - // fractional part of the golden ratio in binary (0x9e3779b9) - // and applying mix() 4 times. - let mut a = w(0x1367df5a); - let mut b = w(0x95d90059); - let mut c = w(0xc3163e4b); - let mut d = w(0x0f421ad8); - let mut e = w(0xd92a4a78); - let mut f = w(0xa51a3c49); - let mut g = w(0xc4efea1b); - let mut h = w(0x30609119); - - // Normally this should do two passes, to make all of the seed effect - // all of `mem` - for _ in 0..rounds { - for i in (0..RAND_SIZE/8).map(|i| i * 8) { - a += mem[i ]; b += mem[i+1]; - c += mem[i+2]; d += mem[i+3]; - e += mem[i+4]; f += mem[i+5]; - g += mem[i+6]; h += mem[i+7]; - mix(&mut a, &mut b, &mut c, &mut d, - &mut e, &mut f, &mut g, &mut h); - mem[i ] = a; mem[i+1] = b; - mem[i+2] = c; mem[i+3] = d; - mem[i+4] = e; mem[i+5] = f; - mem[i+6] = g; mem[i+7] = h; - } - } - - Self { mem, a: w(0), b: w(0), c: w(0) } - } -} - -impl SeedableRng for IsaacCore { - type Seed = [u8; 32]; - - fn from_seed(seed: Self::Seed) -> Self { - let mut seed_u32 = [0u32; 8]; - le::read_u32_into(&seed, &mut seed_u32); - // Convert the seed to `Wrapping` and zero-extend to `RAND_SIZE`. - let mut seed_extended = [w(0); RAND_SIZE]; - for (x, y) in seed_extended.iter_mut().zip(seed_u32.iter()) { - *x = w(*y); - } - Self::init(seed_extended, 2) - } - - /// Create an ISAAC random number generator using an `u64` as seed. - /// If `seed == 0` this will produce the same stream of random numbers as - /// the reference implementation when used unseeded. - fn seed_from_u64(seed: u64) -> Self { - let mut key = [w(0); RAND_SIZE]; - key[0] = w(seed as u32); - key[1] = w((seed >> 32) as u32); - // Initialize with only one pass. - // A second pass does not improve the quality here, because all of the - // seed was already available in the first round. - // Not doing the second pass has the small advantage that if - // `seed == 0` this method produces exactly the same state as the - // reference implementation when used unseeded. - Self::init(key, 1) - } - - fn from_rng(mut rng: R) -> Result { - // Custom `from_rng` implementation that fills a seed with the same size - // as the entire state. - let mut seed = [w(0u32); RAND_SIZE]; - unsafe { - let ptr = seed.as_mut_ptr() as *mut u8; - - let slice = slice::from_raw_parts_mut(ptr, RAND_SIZE * 4); - rng.try_fill_bytes(slice)?; - } - for i in seed.iter_mut() { - *i = w(i.0.to_le()); - } - - Ok(Self::init(seed, 2)) - } -} - -#[cfg(test)] -mod test { - use rand_core::{RngCore, SeedableRng}; - use super::IsaacRng; - - #[test] - fn test_isaac_construction() { - // Test that various construction techniques produce a working RNG. - let seed = [1,0,0,0, 23,0,0,0, 200,1,0,0, 210,30,0,0, - 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; - let mut rng1 = IsaacRng::from_seed(seed); - assert_eq!(rng1.next_u32(), 2869442790); - - let mut rng2 = IsaacRng::from_rng(rng1).unwrap(); - assert_eq!(rng2.next_u32(), 3094074039); - } - - #[test] - fn test_isaac_true_values_32() { - let seed = [1,0,0,0, 23,0,0,0, 200,1,0,0, 210,30,0,0, - 57,48,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; - let mut rng1 = IsaacRng::from_seed(seed); - let mut results = [0u32; 10]; - for i in results.iter_mut() { *i = rng1.next_u32(); } - let expected = [ - 2558573138, 873787463, 263499565, 2103644246, 3595684709, - 4203127393, 264982119, 2765226902, 2737944514, 3900253796]; - assert_eq!(results, expected); - - let seed = [57,48,0,0, 50,9,1,0, 49,212,0,0, 148,38,0,0, - 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; - let mut rng2 = IsaacRng::from_seed(seed); - // skip forward to the 10000th number - for _ in 0..10000 { rng2.next_u32(); } - - for i in results.iter_mut() { *i = rng2.next_u32(); } - let expected = [ - 3676831399, 3183332890, 2834741178, 3854698763, 2717568474, - 1576568959, 3507990155, 179069555, 141456972, 2478885421]; - assert_eq!(results, expected); - } - - #[test] - fn test_isaac_true_values_64() { - // As above, using little-endian versions of above values - let seed = [1,0,0,0, 23,0,0,0, 200,1,0,0, 210,30,0,0, - 57,48,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; - let mut rng = IsaacRng::from_seed(seed); - let mut results = [0u64; 5]; - for i in results.iter_mut() { *i = rng.next_u64(); } - let expected = [ - 3752888579798383186, 9035083239252078381,18052294697452424037, - 11876559110374379111, 16751462502657800130]; - assert_eq!(results, expected); - } - - #[test] - fn test_isaac_true_bytes() { - let seed = [1,0,0,0, 23,0,0,0, 200,1,0,0, 210,30,0,0, - 57,48,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; - let mut rng = IsaacRng::from_seed(seed); - let mut results = [0u8; 32]; - rng.fill_bytes(&mut results); - // Same as first values in test_isaac_true_values as bytes in LE order - let expected = [82, 186, 128, 152, 71, 240, 20, 52, - 45, 175, 180, 15, 86, 16, 99, 125, - 101, 203, 81, 214, 97, 162, 134, 250, - 103, 78, 203, 15, 150, 3, 210, 164]; - assert_eq!(results, expected); - } - - #[test] - fn test_isaac_new_uninitialized() { - // Compare the results from initializing `IsaacRng` with - // `seed_from_u64(0)`, to make sure it is the same as the reference - // implementation when used uninitialized. - // Note: We only test the first 16 integers, not the full 256 of the - // first block. - let mut rng = IsaacRng::seed_from_u64(0); - let mut results = [0u32; 16]; - for i in results.iter_mut() { *i = rng.next_u32(); } - let expected: [u32; 16] = [ - 0x71D71FD2, 0xB54ADAE7, 0xD4788559, 0xC36129FA, - 0x21DC1EA9, 0x3CB879CA, 0xD83B237F, 0xFA3CE5BD, - 0x8D048509, 0xD82E9489, 0xDB452848, 0xCA20E846, - 0x500F972E, 0x0EEFF940, 0x00D6B993, 0xBC12C17F]; - assert_eq!(results, expected); - } - - #[test] - fn test_isaac_clone() { - let seed = [1,0,0,0, 23,0,0,0, 200,1,0,0, 210,30,0,0, - 57,48,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; - let mut rng1 = IsaacRng::from_seed(seed); - let mut rng2 = rng1.clone(); - for _ in 0..16 { - assert_eq!(rng1.next_u32(), rng2.next_u32()); - } - } - - #[test] - #[cfg(feature="serde1")] - fn test_isaac_serde() { - use bincode; - use std::io::{BufWriter, BufReader}; - - let seed = [1,0,0,0, 23,0,0,0, 200,1,0,0, 210,30,0,0, - 57,48,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; - let mut rng = IsaacRng::from_seed(seed); - - let buf: Vec = Vec::new(); - let mut buf = BufWriter::new(buf); - bincode::serialize_into(&mut buf, &rng).expect("Could not serialize"); - - let buf = buf.into_inner().unwrap(); - let mut read = BufReader::new(&buf[..]); - let mut deserialized: IsaacRng = bincode::deserialize_from(&mut read).expect("Could not deserialize"); - - for _ in 0..300 { // more than the 256 buffered results - assert_eq!(rng.next_u32(), deserialized.next_u32()); - } - } -} diff --git a/rand/rand_isaac/src/isaac64.rs b/rand/rand_isaac/src/isaac64.rs deleted file mode 100644 index 7d4b88c..0000000 --- a/rand/rand_isaac/src/isaac64.rs +++ /dev/null @@ -1,466 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// Copyright 2013-2018 The Rust Project Developers. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The ISAAC-64 random number generator. - -use core::{fmt, slice}; -use core::num::Wrapping as w; -#[cfg(feature="serde1")] use serde::{Serialize, Deserialize}; -use rand_core::{RngCore, SeedableRng, Error, le}; -use rand_core::block::{BlockRngCore, BlockRng64}; -use crate::isaac_array::IsaacArray; - -#[allow(non_camel_case_types)] -type w64 = w; - -const RAND_SIZE_LEN: usize = 8; -const RAND_SIZE: usize = 1 << RAND_SIZE_LEN; - -/// A random number generator that uses ISAAC-64, the 64-bit variant of the -/// ISAAC algorithm. -/// -/// ISAAC stands for "Indirection, Shift, Accumulate, Add, and Count" which are -/// the principal bitwise operations employed. It is the most advanced of a -/// series of array based random number generator designed by Robert Jenkins -/// in 1996[^1]. -/// -/// ISAAC-64 is mostly similar to ISAAC. Because it operates on 64-bit integers -/// instead of 32-bit, it uses twice as much memory to hold its state and -/// results. Also it uses different constants for shifts and indirect indexing, -/// optimized to give good results for 64bit arithmetic. -/// -/// ISAAC-64 is notably fast and produces excellent quality random numbers for -/// non-cryptographic applications. -/// -/// In spite of being designed with cryptographic security in mind, ISAAC hasn't -/// been stringently cryptanalyzed and thus cryptographers do not not -/// consensually trust it to be secure. When looking for a secure RNG, prefer -/// `Hc128Rng` from the [`rand_hc`] crate instead, which, like ISAAC, is an -/// array-based RNG and one of the stream-ciphers selected the by eSTREAM -/// -/// ## Overview of the ISAAC-64 algorithm: -/// (in pseudo-code) -/// -/// ```text -/// Input: a, b, c, s[256] // state -/// Output: r[256] // results -/// -/// mix(a,i) = !(a ^ a << 21) if i = 0 mod 4 -/// a ^ a >> 5 if i = 1 mod 4 -/// a ^ a << 12 if i = 2 mod 4 -/// a ^ a >> 33 if i = 3 mod 4 -/// -/// c = c + 1 -/// b = b + c -/// -/// for i in 0..256 { -/// x = s_[i] -/// a = mix(a,i) + s[i+128 mod 256] -/// y = a + b + s[x>>3 mod 256] -/// s[i] = y -/// b = x + s[y>>11 mod 256] -/// r[i] = b -/// } -/// ``` -/// -/// This implementation uses [`BlockRng64`] to implement the [`RngCore`] methods. -/// -/// See for more information the documentation of [`IsaacRng`]. -/// -/// [^1]: Bob Jenkins, [*ISAAC and RC4*]( -/// http://burtleburtle.net/bob/rand/isaac.html) -/// -/// [`IsaacRng`]: crate::isaac::IsaacRng -/// [`rand_hc`]: https://docs.rs/rand_hc -/// [`BlockRng64`]: rand_core::block::BlockRng64 -#[derive(Clone, Debug)] -#[cfg_attr(feature="serde1", derive(Serialize, Deserialize))] -pub struct Isaac64Rng(BlockRng64); - -impl RngCore for Isaac64Rng { - #[inline] - fn next_u32(&mut self) -> u32 { - self.0.next_u32() - } - - #[inline] - fn next_u64(&mut self) -> u64 { - self.0.next_u64() - } - - #[inline] - fn fill_bytes(&mut self, dest: &mut [u8]) { - self.0.fill_bytes(dest) - } - - #[inline] - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - self.0.try_fill_bytes(dest) - } -} - -impl SeedableRng for Isaac64Rng { - type Seed = ::Seed; - - #[inline] - fn from_seed(seed: Self::Seed) -> Self { - Isaac64Rng(BlockRng64::::from_seed(seed)) - } - - /// Create an ISAAC random number generator using an `u64` as seed. - /// If `seed == 0` this will produce the same stream of random numbers as - /// the reference implementation when used unseeded. - #[inline] - fn seed_from_u64(seed: u64) -> Self { - Isaac64Rng(BlockRng64::::seed_from_u64(seed)) - } - - #[inline] - fn from_rng(rng: S) -> Result { - BlockRng64::::from_rng(rng).map(|rng| Isaac64Rng(rng)) - } -} - -/// The core of `Isaac64Rng`, used with `BlockRng`. -#[derive(Clone)] -#[cfg_attr(feature="serde1", derive(Serialize, Deserialize))] -pub struct Isaac64Core { - #[cfg_attr(feature="serde1",serde(with="super::isaac_array::isaac_array_serde"))] - mem: [w64; RAND_SIZE], - a: w64, - b: w64, - c: w64, -} - -// Custom Debug implementation that does not expose the internal state -impl fmt::Debug for Isaac64Core { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "Isaac64Core {{}}") - } -} - -impl BlockRngCore for Isaac64Core { - type Item = u64; - type Results = IsaacArray; - - /// Refills the output buffer, `results`. See also the pseudocode desciption - /// of the algorithm in the `Isaac64Rng` documentation. - /// - /// Optimisations used (similar to the reference implementation): - /// - /// - The loop is unrolled 4 times, once for every constant of mix(). - /// - The contents of the main loop are moved to a function `rngstep`, to - /// reduce code duplication. - /// - We use local variables for a and b, which helps with optimisations. - /// - We split the main loop in two, one that operates over 0..128 and one - /// over 128..256. This way we can optimise out the addition and modulus - /// from `s[i+128 mod 256]`. - /// - We maintain one index `i` and add `m` or `m2` as base (m2 for the - /// `s[i+128 mod 256]`), relying on the optimizer to turn it into pointer - /// arithmetic. - /// - We fill `results` backwards. The reference implementation reads values - /// from `results` in reverse. We read them in the normal direction, to - /// make `fill_bytes` a memcopy. To maintain compatibility we fill in - /// reverse. - fn generate(&mut self, results: &mut IsaacArray) { - self.c += w(1); - // abbreviations - let mut a = self.a; - let mut b = self.b + self.c; - const MIDPOINT: usize = RAND_SIZE / 2; - - #[inline] - fn ind(mem:&[w64; RAND_SIZE], v: w64, amount: usize) -> w64 { - let index = (v >> amount).0 as usize % RAND_SIZE; - mem[index] - } - - #[inline] - fn rngstep(mem: &mut [w64; RAND_SIZE], - results: &mut [u64; RAND_SIZE], - mix: w64, - a: &mut w64, - b: &mut w64, - base: usize, - m: usize, - m2: usize) { - let x = mem[base + m]; - *a = mix + mem[base + m2]; - let y = *a + *b + ind(&mem, x, 3); - mem[base + m] = y; - *b = x + ind(&mem, y, 3 + RAND_SIZE_LEN); - results[RAND_SIZE - 1 - base - m] = (*b).0; - } - - let mut m = 0; - let mut m2 = MIDPOINT; - for i in (0..MIDPOINT/4).map(|i| i * 4) { - rngstep(&mut self.mem, results, !(a ^ (a << 21)), &mut a, &mut b, i + 0, m, m2); - rngstep(&mut self.mem, results, a ^ (a >> 5 ), &mut a, &mut b, i + 1, m, m2); - rngstep(&mut self.mem, results, a ^ (a << 12), &mut a, &mut b, i + 2, m, m2); - rngstep(&mut self.mem, results, a ^ (a >> 33), &mut a, &mut b, i + 3, m, m2); - } - - m = MIDPOINT; - m2 = 0; - for i in (0..MIDPOINT/4).map(|i| i * 4) { - rngstep(&mut self.mem, results, !(a ^ (a << 21)), &mut a, &mut b, i + 0, m, m2); - rngstep(&mut self.mem, results, a ^ (a >> 5 ), &mut a, &mut b, i + 1, m, m2); - rngstep(&mut self.mem, results, a ^ (a << 12), &mut a, &mut b, i + 2, m, m2); - rngstep(&mut self.mem, results, a ^ (a >> 33), &mut a, &mut b, i + 3, m, m2); - } - - self.a = a; - self.b = b; - } -} - -impl Isaac64Core { - /// Create a new ISAAC-64 random number generator. - fn init(mut mem: [w64; RAND_SIZE], rounds: u32) -> Self { - fn mix(a: &mut w64, b: &mut w64, c: &mut w64, d: &mut w64, - e: &mut w64, f: &mut w64, g: &mut w64, h: &mut w64) { - *a -= *e; *f ^= *h >> 9; *h += *a; - *b -= *f; *g ^= *a << 9; *a += *b; - *c -= *g; *h ^= *b >> 23; *b += *c; - *d -= *h; *a ^= *c << 15; *c += *d; - *e -= *a; *b ^= *d >> 14; *d += *e; - *f -= *b; *c ^= *e << 20; *e += *f; - *g -= *c; *d ^= *f >> 17; *f += *g; - *h -= *d; *e ^= *g << 14; *g += *h; - } - - // These numbers are the result of initializing a...h with the - // fractional part of the golden ratio in binary (0x9e3779b97f4a7c13) - // and applying mix() 4 times. - let mut a = w(0x647c4677a2884b7c); - let mut b = w(0xb9f8b322c73ac862); - let mut c = w(0x8c0ea5053d4712a0); - let mut d = w(0xb29b2e824a595524); - let mut e = w(0x82f053db8355e0ce); - let mut f = w(0x48fe4a0fa5a09315); - let mut g = w(0xae985bf2cbfc89ed); - let mut h = w(0x98f5704f6c44c0ab); - - // Normally this should do two passes, to make all of the seed effect - // all of `mem` - for _ in 0..rounds { - for i in (0..RAND_SIZE/8).map(|i| i * 8) { - a += mem[i ]; b += mem[i+1]; - c += mem[i+2]; d += mem[i+3]; - e += mem[i+4]; f += mem[i+5]; - g += mem[i+6]; h += mem[i+7]; - mix(&mut a, &mut b, &mut c, &mut d, - &mut e, &mut f, &mut g, &mut h); - mem[i ] = a; mem[i+1] = b; - mem[i+2] = c; mem[i+3] = d; - mem[i+4] = e; mem[i+5] = f; - mem[i+6] = g; mem[i+7] = h; - } - } - - Self { mem, a: w(0), b: w(0), c: w(0) } - } -} - -impl SeedableRng for Isaac64Core { - type Seed = [u8; 32]; - - fn from_seed(seed: Self::Seed) -> Self { - let mut seed_u64 = [0u64; 4]; - le::read_u64_into(&seed, &mut seed_u64); - // Convert the seed to `Wrapping` and zero-extend to `RAND_SIZE`. - let mut seed_extended = [w(0); RAND_SIZE]; - for (x, y) in seed_extended.iter_mut().zip(seed_u64.iter()) { - *x = w(*y); - } - Self::init(seed_extended, 2) - } - - fn seed_from_u64(seed: u64) -> Self { - let mut key = [w(0); RAND_SIZE]; - key[0] = w(seed); - // Initialize with only one pass. - // A second pass does not improve the quality here, because all of the - // seed was already available in the first round. - // Not doing the second pass has the small advantage that if - // `seed == 0` this method produces exactly the same state as the - // reference implementation when used unseeded. - Self::init(key, 1) - } - - fn from_rng(mut rng: R) -> Result { - // Custom `from_rng` implementation that fills a seed with the same size - // as the entire state. - let mut seed = [w(0u64); RAND_SIZE]; - unsafe { - let ptr = seed.as_mut_ptr() as *mut u8; - let slice = slice::from_raw_parts_mut(ptr, RAND_SIZE * 8); - rng.try_fill_bytes(slice)?; - } - for i in seed.iter_mut() { - *i = w(i.0.to_le()); - } - - Ok(Self::init(seed, 2)) - } -} - -#[cfg(test)] -mod test { - use rand_core::{RngCore, SeedableRng}; - use super::Isaac64Rng; - - #[test] - fn test_isaac64_construction() { - // Test that various construction techniques produce a working RNG. - let seed = [1,0,0,0, 23,0,0,0, 200,1,0,0, 210,30,0,0, - 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; - let mut rng1 = Isaac64Rng::from_seed(seed); - assert_eq!(rng1.next_u64(), 14964555543728284049); - - let mut rng2 = Isaac64Rng::from_rng(rng1).unwrap(); - assert_eq!(rng2.next_u64(), 919595328260451758); - } - - #[test] - fn test_isaac64_true_values_64() { - let seed = [1,0,0,0, 0,0,0,0, 23,0,0,0, 0,0,0,0, - 200,1,0,0, 0,0,0,0, 210,30,0,0, 0,0,0,0]; - let mut rng1 = Isaac64Rng::from_seed(seed); - let mut results = [0u64; 10]; - for i in results.iter_mut() { *i = rng1.next_u64(); } - let expected = [ - 15071495833797886820, 7720185633435529318, - 10836773366498097981, 5414053799617603544, - 12890513357046278984, 17001051845652595546, - 9240803642279356310, 12558996012687158051, - 14673053937227185542, 1677046725350116783]; - assert_eq!(results, expected); - - let seed = [57,48,0,0, 0,0,0,0, 50,9,1,0, 0,0,0,0, - 49,212,0,0, 0,0,0,0, 148,38,0,0, 0,0,0,0]; - let mut rng2 = Isaac64Rng::from_seed(seed); - // skip forward to the 10000th number - for _ in 0..10000 { rng2.next_u64(); } - - for i in results.iter_mut() { *i = rng2.next_u64(); } - let expected = [ - 18143823860592706164, 8491801882678285927, 2699425367717515619, - 17196852593171130876, 2606123525235546165, 15790932315217671084, - 596345674630742204, 9947027391921273664, 11788097613744130851, - 10391409374914919106]; - assert_eq!(results, expected); - } - - #[test] - fn test_isaac64_true_values_32() { - let seed = [1,0,0,0, 0,0,0,0, 23,0,0,0, 0,0,0,0, - 200,1,0,0, 0,0,0,0, 210,30,0,0, 0,0,0,0]; - let mut rng = Isaac64Rng::from_seed(seed); - let mut results = [0u32; 12]; - for i in results.iter_mut() { *i = rng.next_u32(); } - // Subset of above values, as an LE u32 sequence - let expected = [ - 3477963620, 3509106075, - 687845478, 1797495790, - 227048253, 2523132918, - 4044335064, 1260557630, - 4079741768, 3001306521, - 69157722, 3958365844]; - assert_eq!(results, expected); - } - - #[test] - fn test_isaac64_true_values_mixed() { - let seed = [1,0,0,0, 0,0,0,0, 23,0,0,0, 0,0,0,0, - 200,1,0,0, 0,0,0,0, 210,30,0,0, 0,0,0,0]; - let mut rng = Isaac64Rng::from_seed(seed); - // Test alternating between `next_u64` and `next_u32` works as expected. - // Values are the same as `test_isaac64_true_values` and - // `test_isaac64_true_values_32`. - assert_eq!(rng.next_u64(), 15071495833797886820); - assert_eq!(rng.next_u32(), 687845478); - assert_eq!(rng.next_u32(), 1797495790); - assert_eq!(rng.next_u64(), 10836773366498097981); - assert_eq!(rng.next_u32(), 4044335064); - // Skip one u32 - assert_eq!(rng.next_u64(), 12890513357046278984); - assert_eq!(rng.next_u32(), 69157722); - } - - #[test] - fn test_isaac64_true_bytes() { - let seed = [1,0,0,0, 0,0,0,0, 23,0,0,0, 0,0,0,0, - 200,1,0,0, 0,0,0,0, 210,30,0,0, 0,0,0,0]; - let mut rng = Isaac64Rng::from_seed(seed); - let mut results = [0u8; 32]; - rng.fill_bytes(&mut results); - // Same as first values in test_isaac64_true_values as bytes in LE order - let expected = [100, 131, 77, 207, 155, 181, 40, 209, - 102, 176, 255, 40, 238, 155, 35, 107, - 61, 123, 136, 13, 246, 243, 99, 150, - 216, 167, 15, 241, 62, 149, 34, 75]; - assert_eq!(results, expected); - } - - #[test] - fn test_isaac64_new_uninitialized() { - // Compare the results from initializing `IsaacRng` with - // `seed_from_u64(0)`, to make sure it is the same as the reference - // implementation when used uninitialized. - // Note: We only test the first 16 integers, not the full 256 of the - // first block. - let mut rng = Isaac64Rng::seed_from_u64(0); - let mut results = [0u64; 16]; - for i in results.iter_mut() { *i = rng.next_u64(); } - let expected: [u64; 16] = [ - 0xF67DFBA498E4937C, 0x84A5066A9204F380, 0xFEE34BD5F5514DBB, - 0x4D1664739B8F80D6, 0x8607459AB52A14AA, 0x0E78BC5A98529E49, - 0xFE5332822AD13777, 0x556C27525E33D01A, 0x08643CA615F3149F, - 0xD0771FAF3CB04714, 0x30E86F68A37B008D, 0x3074EBC0488A3ADF, - 0x270645EA7A2790BC, 0x5601A0A8D3763C6A, 0x2F83071F53F325DD, - 0xB9090F3D42D2D2EA]; - assert_eq!(results, expected); - } - - #[test] - fn test_isaac64_clone() { - let seed = [1,0,0,0, 0,0,0,0, 23,0,0,0, 0,0,0,0, - 200,1,0,0, 0,0,0,0, 210,30,0,0, 0,0,0,0]; - let mut rng1 = Isaac64Rng::from_seed(seed); - let mut rng2 = rng1.clone(); - for _ in 0..16 { - assert_eq!(rng1.next_u64(), rng2.next_u64()); - } - } - - #[test] - #[cfg(feature="serde1")] - fn test_isaac64_serde() { - use bincode; - use std::io::{BufWriter, BufReader}; - - let seed = [1,0,0,0, 23,0,0,0, 200,1,0,0, 210,30,0,0, - 57,48,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; - let mut rng = Isaac64Rng::from_seed(seed); - - let buf: Vec = Vec::new(); - let mut buf = BufWriter::new(buf); - bincode::serialize_into(&mut buf, &rng).expect("Could not serialize"); - - let buf = buf.into_inner().unwrap(); - let mut read = BufReader::new(&buf[..]); - let mut deserialized: Isaac64Rng = bincode::deserialize_from(&mut read).expect("Could not deserialize"); - - for _ in 0..300 { // more than the 256 buffered results - assert_eq!(rng.next_u64(), deserialized.next_u64()); - } - } -} diff --git a/rand/rand_isaac/src/isaac_array.rs b/rand/rand_isaac/src/isaac_array.rs deleted file mode 100644 index cbe4a59..0000000 --- a/rand/rand_isaac/src/isaac_array.rs +++ /dev/null @@ -1,136 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// Copyright 2017-2018 The Rust Project Developers. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! ISAAC helper functions for 256-element arrays. - -// Terrible workaround because arrays with more than 32 elements do not -// implement `AsRef`, `Default`, `Serialize`, `Deserialize`, or any other -// traits for that matter. - -#[cfg(feature="serde")] use serde::{Serialize, Deserialize}; - -const RAND_SIZE_LEN: usize = 8; -const RAND_SIZE: usize = 1 << RAND_SIZE_LEN; - - -#[derive(Copy, Clone)] -#[allow(missing_debug_implementations)] -#[cfg_attr(feature="serde", derive(Serialize, Deserialize))] -pub struct IsaacArray { - #[cfg_attr(feature="serde",serde(with="isaac_array_serde"))] - #[cfg_attr(feature="serde", serde(bound( - serialize = "T: Serialize", - deserialize = "T: Deserialize<'de> + Copy + Default")))] - inner: [T; RAND_SIZE] -} - -impl ::core::convert::AsRef<[T]> for IsaacArray { - #[inline(always)] - fn as_ref(&self) -> &[T] { - &self.inner[..] - } -} - -impl ::core::convert::AsMut<[T]> for IsaacArray { - #[inline(always)] - fn as_mut(&mut self) -> &mut [T] { - &mut self.inner[..] - } -} - -impl ::core::ops::Deref for IsaacArray { - type Target = [T; RAND_SIZE]; - #[inline(always)] - fn deref(&self) -> &Self::Target { - &self.inner - } -} - -impl ::core::ops::DerefMut for IsaacArray { - #[inline(always)] - fn deref_mut(&mut self) -> &mut [T; RAND_SIZE] { - &mut self.inner - } -} - -impl ::core::default::Default for IsaacArray where T: Copy + Default { - fn default() -> IsaacArray { - IsaacArray { inner: [T::default(); RAND_SIZE] } - } -} - - -#[cfg(feature="serde")] -pub(super) mod isaac_array_serde { - const RAND_SIZE_LEN: usize = 8; - const RAND_SIZE: usize = 1 << RAND_SIZE_LEN; - - use serde::{Deserialize, Deserializer, Serialize, Serializer}; - use serde::de::{Visitor,SeqAccess}; - use serde::de; - - use core::fmt; - - pub fn serialize(arr: &[T;RAND_SIZE], ser: S) -> Result - where - T: Serialize, - S: Serializer - { - use serde::ser::SerializeTuple; - - let mut seq = ser.serialize_tuple(RAND_SIZE)?; - - for e in arr.iter() { - seq.serialize_element(&e)?; - } - - seq.end() - } - - #[inline] - pub fn deserialize<'de, T, D>(de: D) -> Result<[T;RAND_SIZE], D::Error> - where - T: Deserialize<'de>+Default+Copy, - D: Deserializer<'de>, - { - use core::marker::PhantomData; - struct ArrayVisitor { - _pd: PhantomData, - }; - impl<'de,T> Visitor<'de> for ArrayVisitor - where - T: Deserialize<'de>+Default+Copy - { - type Value = [T; RAND_SIZE]; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Isaac state array") - } - - #[inline] - fn visit_seq(self, mut seq: A) -> Result<[T; RAND_SIZE], A::Error> - where - A: SeqAccess<'de>, - { - let mut out = [Default::default();RAND_SIZE]; - - for i in 0..RAND_SIZE { - match seq.next_element()? { - Some(val) => out[i] = val, - None => return Err(de::Error::invalid_length(i, &self)), - }; - } - - Ok(out) - } - } - - de.deserialize_tuple(RAND_SIZE, ArrayVisitor{_pd: PhantomData}) - } -} diff --git a/rand/rand_isaac/src/lib.rs b/rand/rand_isaac/src/lib.rs deleted file mode 100644 index 84cdf21..0000000 --- a/rand/rand_isaac/src/lib.rs +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The ISAAC and ISAAC-64 random number generators. - -#![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(not(all(feature="serde", test)), no_std)] - -pub mod isaac; -pub mod isaac64; - -mod isaac_array; - -pub use self::isaac::IsaacRng; -pub use self::isaac64::Isaac64Rng; diff --git a/rand/rand_jitter/CHANGELOG.md b/rand/rand_jitter/CHANGELOG.md deleted file mode 100644 index 9f4bb7e..0000000 --- a/rand/rand_jitter/CHANGELOG.md +++ /dev/null @@ -1,32 +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.2.1] - 2019-08-16 -### Changed -- `TimerError` changed to `repr(u32)` (#864) -- `TimerError` enum values all increased by `1<<30` to match new `rand_core::Error` range (#864) - -## [0.2.0] - 2019-06-06 -- Bump `rand_core` version -- Support new `Error` type in `rand_core` 0.5 -- Remove CryptoRng trait bound (#699, #814) -- Enable doc-testing of README - -## [0.1.4] - 2019-05-02 -- Change error conversion code to partially fix #738 - -## [0.1.3] - 2019-02-05 -- Use libc in `no_std` mode to fix #723 - -## [0.1.2] - 2019-01-31 -- Fix for older rustc compilers on Windows (#722) - -## [0.1.1] - 2019-01-29 -- Fix for older rustc compilers on Mac OSX / iOS (#720) -- Misc. doc fixes - -## [0.1.0] - 2019-01-24 -Initial release. diff --git a/rand/rand_jitter/COPYRIGHT b/rand/rand_jitter/COPYRIGHT deleted file mode 100644 index 468d907..0000000 --- a/rand/rand_jitter/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 or - or the MIT license - or , at your option. - -The Rand project includes code from the Rust project -published under these same licenses. diff --git a/rand/rand_jitter/Cargo.toml b/rand/rand_jitter/Cargo.toml deleted file mode 100644 index 5b7e3c3..0000000 --- a/rand/rand_jitter/Cargo.toml +++ /dev/null @@ -1,30 +0,0 @@ -[package] -name = "rand_jitter" -version = "0.2.1" -authors = ["The Rand Project Developers"] -license = "MIT OR Apache-2.0" -readme = "README.md" -repository = "https://github.com/rust-random/rand" -documentation = "https://docs.rs/rand_jitter" -description = "Random number generator based on timing jitter" -keywords = ["random", "rng", "os"] -edition = "2018" - -[badges] -travis-ci = { repository = "rust-random/rand" } -appveyor = { repository = "rust-random/rand" } - -[dependencies] -rand_core = { path = "../rand_core", version = "0.5" } -log = { version = "0.4", optional = true } - -[target.'cfg(any(target_os = "macos", target_os = "ios"))'.dependencies] -# We don't need the 'use_std' feature and depending on it causes -# issues due to: https://github.com/rust-lang/cargo/issues/1197 -libc = { version = "0.2", default_features = false } - -[target.'cfg(target_os = "windows")'.dependencies] -winapi = { version = "0.3", features = ["profileapi"] } - -[features] -std = ["rand_core/std"] diff --git a/rand/rand_jitter/LICENSE-APACHE b/rand/rand_jitter/LICENSE-APACHE deleted file mode 100644 index 17d7468..0000000 --- a/rand/rand_jitter/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_jitter/LICENSE-MIT b/rand/rand_jitter/LICENSE-MIT deleted file mode 100644 index d93b5ba..0000000 --- a/rand/rand_jitter/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_jitter/README.md b/rand/rand_jitter/README.md deleted file mode 100644 index 2091d6c..0000000 --- a/rand/rand_jitter/README.md +++ /dev/null @@ -1,119 +0,0 @@ -# rand_jitter -[![Build Status](https://travis-ci.org/rust-random/rand.svg?branch=master)](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_jitter.svg)](https://crates.io/crates/rand_jitter) -[![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_jitter) -[![API](https://docs.rs/rand_jitter/badge.svg)](https://docs.rs/rand_jitter) -[![Minimum rustc version](https://img.shields.io/badge/rustc-1.32+-lightgray.svg)](https://github.com/rust-random/rand#rust-version-requirements) - -Non-physical true random number generator based on timing jitter. - -Note that this RNG is not suited for use cases where cryptographic security is -required (also see [this -discussion](https://github.com/rust-random/rand/issues/699)). - -This crate depends on [rand_core](https://crates.io/crates/rand_core) and is -part of the [Rand project](https://github.com/rust-random/rand). - -This crate aims to support all of Rust's `std` platforms with a system-provided -entropy source. Unlike other Rand crates, this crate does not support `no_std` -(handling this gracefully is a current discussion topic). - -Links: - -- [API documentation (master)](https://rust-random.github.io/rand/rand_jitter) -- [API documentation (docs.rs)](https://docs.rs/rand_jitter) -- [Changelog](https://github.com/rust-random/rand/blob/master/rand_jitter/CHANGELOG.md) - -## Features - -This crate has optional `std` support which is *disabled by default*; -this feature is required to provide the `JitterRng::new` function; -without `std` support a timer must be supplied via `JitterRng::new_with_timer`. - -## Quality testing - -`JitterRng::new()` has build-in, but limited, quality testing, however -before using `JitterRng` on untested hardware, or after changes that could -effect how the code is optimized (such as a new LLVM version), it is -recommend to run the much more stringent -[NIST SP 800-90B Entropy Estimation Suite](https://github.com/usnistgov/SP800-90B_EntropyAssessment). - -Use the following code using `timer_stats` to collect the data: - -```rust,no_run -use rand_jitter::JitterRng; - -use std::error::Error; -use std::fs::File; -use std::io::Write; - -fn get_nstime() -> u64 { - use std::time::{SystemTime, UNIX_EPOCH}; - - let dur = SystemTime::now().duration_since(UNIX_EPOCH).unwrap(); - // The correct way to calculate the current time is - // `dur.as_secs() * 1_000_000_000 + dur.subsec_nanos() as u64` - // But this is faster, and the difference in terms of entropy is - // negligible (log2(10^9) == 29.9). - dur.as_secs() << 30 | dur.subsec_nanos() as u64 -} - -fn main() -> Result<(), Box> { - let mut rng = JitterRng::new_with_timer(get_nstime); - - // 1_000_000 results are required for the - // NIST SP 800-90B Entropy Estimation Suite - const ROUNDS: usize = 1_000_000; - let mut deltas_variable: Vec = Vec::with_capacity(ROUNDS); - let mut deltas_minimal: Vec = Vec::with_capacity(ROUNDS); - - for _ in 0..ROUNDS { - deltas_variable.push(rng.timer_stats(true) as u8); - deltas_minimal.push(rng.timer_stats(false) as u8); - } - - // Write out after the statistics collection loop, to not disturb the - // test results. - File::create("jitter_rng_var.bin")?.write(&deltas_variable)?; - File::create("jitter_rng_min.bin")?.write(&deltas_minimal)?; - Ok(()) -} -``` - -This will produce two files: `jitter_rng_var.bin` and `jitter_rng_min.bin`. -Run the Entropy Estimation Suite in three configurations, as outlined below. -Every run has two steps. One step to produce an estimation, another to -validate the estimation. - -1. Estimate the expected amount of entropy that is at least available with - each round of the entropy collector. This number should be greater than - the amount estimated with `64 / test_timer()`. - ```sh - python noniid_main.py -v jitter_rng_var.bin 8 - restart.py -v jitter_rng_var.bin 8 - ``` -2. Estimate the expected amount of entropy that is available in the last 4 - bits of the timer delta after running noice sources. Note that a value of - `3.70` is the minimum estimated entropy for true randomness. - ```sh - python noniid_main.py -v -u 4 jitter_rng_var.bin 4 - restart.py -v -u 4 jitter_rng_var.bin 4 - ``` -3. Estimate the expected amount of entropy that is available to the entropy - collector if both noise sources only run their minimal number of times. - This measures the absolute worst-case, and gives a lower bound for the - available entropy. - ```sh - python noniid_main.py -v -u 4 jitter_rng_min.bin 4 - restart.py -v -u 4 jitter_rng_min.bin 4 - ``` - -## License - -`rand_jitter` 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_jitter/benches/mod.rs b/rand/rand_jitter/benches/mod.rs deleted file mode 100644 index bf7c8a2..0000000 --- a/rand/rand_jitter/benches/mod.rs +++ /dev/null @@ -1,17 +0,0 @@ -#![feature(test)] -#![cfg(std)] - -use test::Bencher; -use rand_jitter::rand_core::RngCore; - -#[bench] -fn bench_add_two(b: &mut Bencher) { - let mut rng = rand_jitter::JitterRng::new().unwrap(); - let mut buf = [0u8; 1024]; - b.iter(|| { - rng.fill_bytes(&mut buf[..]); - test::black_box(&buf); - }); - b.bytes = buf.len() as u64; -} - diff --git a/rand/rand_jitter/src/error.rs b/rand/rand_jitter/src/error.rs deleted file mode 100644 index b54fffa..0000000 --- a/rand/rand_jitter/src/error.rs +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// Copyright 2013-2015 The Rust Project Developers. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use rand_core::Error; -use core::fmt; - -/// Base code for all `JitterRng` errors -const ERROR_BASE: u32 = 0xAE53_0400; - -/// An error that can occur when [`JitterRng::test_timer`] fails. -/// -/// All variants have a value of 0xAE530400 = 2924676096 plus a small -/// increment (1 through 5). -/// -/// [`JitterRng::test_timer`]: crate::JitterRng::test_timer -#[derive(Debug, Clone, PartialEq, Eq)] -#[repr(u32)] -pub enum TimerError { - /// No timer available. - NoTimer = ERROR_BASE + 1, - /// Timer too coarse to use as an entropy source. - CoarseTimer = ERROR_BASE + 2, - /// Timer is not monotonically increasing. - NotMonotonic = ERROR_BASE + 3, - /// Variations of deltas of time too small. - TinyVariantions = ERROR_BASE + 4, - /// Too many stuck results (indicating no added entropy). - TooManyStuck = ERROR_BASE + 5, - #[doc(hidden)] - __Nonexhaustive, -} - -impl TimerError { - fn description(&self) -> &'static str { - match *self { - TimerError::NoTimer => "no timer available", - TimerError::CoarseTimer => "coarse timer", - TimerError::NotMonotonic => "timer not monotonic", - TimerError::TinyVariantions => "time delta variations too small", - TimerError::TooManyStuck => "too many stuck results", - TimerError::__Nonexhaustive => unreachable!(), - } - } -} - -impl fmt::Display for TimerError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self.description()) - } -} - -#[cfg(feature = "std")] -impl ::std::error::Error for TimerError { - fn description(&self) -> &str { - self.description() - } -} - -impl From for Error { - fn from(err: TimerError) -> Error { - // Timer check is already quite permissive of failures so we don't - // expect false-positive failures, i.e. any error is irrecoverable. - #[cfg(feature = "std")] { - Error::new(err) - } - #[cfg(not(feature = "std"))] { - Error::from(core::num::NonZeroU32::new(err as u32).unwrap()) - } - } -} - diff --git a/rand/rand_jitter/src/lib.rs b/rand/rand_jitter/src/lib.rs deleted file mode 100644 index 49c53e6..0000000 --- a/rand/rand_jitter/src/lib.rs +++ /dev/null @@ -1,750 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. -// -// Based on jitterentropy-library, http://www.chronox.de/jent.html. -// Copyright Stephan Mueller , 2014 - 2017. -// -// With permission from Stephan Mueller to relicense the Rust translation under -// the MIT license. - -//! Non-physical true random number generator based on timing jitter. -//! -//! Note that this RNG is not suited for use cases where cryptographic security is -//! required (also see this [discussion]). -//! -//! This is a true random number generator, as opposed to pseudo-random -//! generators. Random numbers generated by `JitterRng` can be seen as fresh -//! entropy. A consequence is that it is orders of magnitude slower than `OsRng` -//! and PRNGs (about 103..106 slower). -//! -//! There are very few situations where using this RNG is appropriate. Only very -//! few applications require true entropy. A normal PRNG can be statistically -//! indistinguishable, and a cryptographic PRNG should also be as impossible to -//! predict. -//! -//! `JitterRng` can be used without the standard library, but not conveniently, -//! you must provide a high-precision timer and carefully have to follow the -//! instructions of [`JitterRng::new_with_timer`]. -//! -//! This implementation is based on [Jitterentropy] version 2.1.0. -//! -//! Note: There is no accurate timer available on WASM platforms, to help -//! prevent fingerprinting or timing side-channel attacks. Therefore -//! [`JitterRng::new()`] is not available on WASM. It is also unavailable -//! with disabled `std` feature. -//! -//! [Jitterentropy]: http://www.chronox.de/jent.html -//! [discussion]: https://github.com/rust-random/rand/issues/699 - -#![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))))] - -// Note: the C implementation of `Jitterentropy` relies on being compiled -// without optimizations. This implementation goes through lengths to make the -// compiler not optimize out code which does influence timing jitter, but is -// technically dead code. -#![no_std] -#[cfg(feature = "std")] -extern crate std; - -pub use rand_core; - -// Coming from https://crates.io/crates/doc-comment -#[cfg(test)] -macro_rules! doc_comment { - ($x:expr) => { - #[doc = $x] - extern {} - }; -} - -#[cfg(test)] -doc_comment!(include_str!("../README.md")); - -#[allow(unused)] -macro_rules! trace { ($($x:tt)*) => ( - #[cfg(feature = "log")] { - log::trace!($($x)*) - } -) } -#[allow(unused)] -macro_rules! debug { ($($x:tt)*) => ( - #[cfg(feature = "log")] { - log::debug!($($x)*) - } -) } -#[allow(unused)] -macro_rules! info { ($($x:tt)*) => ( - #[cfg(feature = "log")] { - log::info!($($x)*) - } -) } -#[allow(unused)] -macro_rules! warn { ($($x:tt)*) => ( - #[cfg(feature = "log")] { - log::warn!($($x)*) - } -) } -#[allow(unused)] -macro_rules! error { ($($x:tt)*) => ( - #[cfg(feature = "log")] { - log::error!($($x)*) - } -) } - -#[cfg(feature = "std")] -mod platform; -mod error; - -use rand_core::{RngCore, Error, impls}; -pub use crate::error::TimerError; - -use core::{fmt, mem, ptr}; -#[cfg(feature = "std")] -use std::sync::atomic::{AtomicUsize, Ordering}; - -const MEMORY_BLOCKS: usize = 64; -const MEMORY_BLOCKSIZE: usize = 32; -const MEMORY_SIZE: usize = MEMORY_BLOCKS * MEMORY_BLOCKSIZE; - -/// A true random number generator based on jitter in the CPU execution time, -/// and jitter in memory access time. -/// -/// Note that this RNG is not suitable for use cases where cryptographic -/// security is required. -pub struct JitterRng { - data: u64, // Actual random number - // Number of rounds to run the entropy collector per 64 bits - rounds: u8, - // Timer used by `measure_jitter` - timer: fn() -> u64, - // Memory for the Memory Access noise source - mem_prev_index: u16, - // Make `next_u32` not waste 32 bits - data_half_used: bool, -} - -// Note: `JitterRng` maintains a small 64-bit entropy pool. With every -// `generate` 64 new bits should be integrated in the pool. If a round of -// `generate` were to collect less than the expected 64 bit, then the returned -// value, and the new state of the entropy pool, would be in some way related to -// the initial state. It is therefore better if the initial state of the entropy -// pool is different on each call to `generate`. This has a few implications: -// - `generate` should be called once before using `JitterRng` to produce the -// first usable value (this is done by default in `new`); -// - We do not zero the entropy pool after generating a result. The reference -// implementation also does not support zeroing, but recommends generating a -// new value without using it if you want to protect a previously generated -// 'secret' value from someone inspecting the memory; -// - Implementing `Clone` seems acceptable, as it would not cause the systematic -// bias a constant might cause. Only instead of one value that could be -// potentially related to the same initial state, there are now two. - -// Entropy collector state. -// These values are not necessary to preserve across runs. -struct EcState { - // Previous time stamp to determine the timer delta - prev_time: u64, - // Deltas used for the stuck test - last_delta: i32, - last_delta2: i32, - // Memory for the Memory Access noise source - mem: [u8; MEMORY_SIZE], -} - -impl EcState { - // Stuck test by checking the: - // - 1st derivation of the jitter measurement (time delta) - // - 2nd derivation of the jitter measurement (delta of time deltas) - // - 3rd derivation of the jitter measurement (delta of delta of time - // deltas) - // - // All values must always be non-zero. - // This test is a heuristic to see whether the last measurement holds - // entropy. - fn stuck(&mut self, current_delta: i32) -> bool { - let delta2 = self.last_delta - current_delta; - let delta3 = delta2 - self.last_delta2; - - self.last_delta = current_delta; - self.last_delta2 = delta2; - - current_delta == 0 || delta2 == 0 || delta3 == 0 - } -} - -// Custom Debug implementation that does not expose the internal state -impl fmt::Debug for JitterRng { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "JitterRng {{}}") - } -} - -impl Clone for JitterRng { - fn clone(&self) -> JitterRng { - JitterRng { - data: self.data, - rounds: self.rounds, - timer: self.timer, - mem_prev_index: self.mem_prev_index, - // The 32 bits that may still be unused from the previous round are - // for the original to use, not for the clone. - data_half_used: false, - } - } -} - -// Initialise to zero; must be positive -#[cfg(all(feature = "std", not(target_arch = "wasm32")))] -static JITTER_ROUNDS: AtomicUsize = AtomicUsize::new(0); - -impl JitterRng { - /// Create a new `JitterRng`. Makes use of `std::time` for a timer, or a - /// platform-specific function with higher accuracy if necessary and - /// available. - /// - /// During initialization CPU execution timing jitter is measured a few - /// hundred times. If this does not pass basic quality tests, an error is - /// returned. The test result is cached to make subsequent calls faster. - #[cfg(all(feature = "std", not(target_arch = "wasm32")))] - pub fn new() -> Result { - if cfg!(target_arch = "wasm32") { - return Err(TimerError::NoTimer); - } - let mut state = JitterRng::new_with_timer(platform::get_nstime); - let mut rounds = JITTER_ROUNDS.load(Ordering::Relaxed) as u8; - if rounds == 0 { - // No result yet: run test. - // This allows the timer test to run multiple times; we don't care. - rounds = state.test_timer()?; - JITTER_ROUNDS.store(rounds as usize, Ordering::Relaxed); - info!("JitterRng: using {} rounds per u64 output", rounds); - } - state.set_rounds(rounds); - - // Fill `data` with a non-zero value. - state.gen_entropy(); - Ok(state) - } - - /// Create a new `JitterRng`. - /// A custom timer can be supplied, making it possible to use `JitterRng` in - /// `no_std` environments. - /// - /// The timer must have nanosecond precision. - /// - /// This method is more low-level than `new()`. It is the responsibility of - /// the caller to run [`test_timer`] before using any numbers generated with - /// `JitterRng`, and optionally call [`set_rounds`]. Also it is important to - /// consume at least one `u64` before using the first result to initialize - /// the entropy collection pool. - /// - /// # Example - /// - /// ``` - /// # use rand_jitter::rand_core::{RngCore, Error}; - /// use rand_jitter::JitterRng; - /// - /// # fn try_inner() -> Result<(), Error> { - /// fn get_nstime() -> u64 { - /// use std::time::{SystemTime, UNIX_EPOCH}; - /// - /// let dur = SystemTime::now().duration_since(UNIX_EPOCH).unwrap(); - /// // The correct way to calculate the current time is - /// // `dur.as_secs() * 1_000_000_000 + dur.subsec_nanos() as u64` - /// // But this is faster, and the difference in terms of entropy is - /// // negligible (log2(10^9) == 29.9). - /// dur.as_secs() << 30 | dur.subsec_nanos() as u64 - /// } - /// - /// let mut rng = JitterRng::new_with_timer(get_nstime); - /// let rounds = rng.test_timer()?; - /// rng.set_rounds(rounds); // optional - /// let _ = rng.next_u64(); - /// - /// // Ready for use - /// let v: u64 = rng.next_u64(); - /// # Ok(()) - /// # } - /// - /// # let _ = try_inner(); - /// ``` - /// - /// [`test_timer`]: JitterRng::test_timer - /// [`set_rounds`]: JitterRng::set_rounds - pub fn new_with_timer(timer: fn() -> u64) -> JitterRng { - JitterRng { - data: 0, - rounds: 64, - timer, - mem_prev_index: 0, - data_half_used: false, - } - } - - /// Configures how many rounds are used to generate each 64-bit value. - /// This must be greater than zero, and has a big impact on performance - /// and output quality. - /// - /// [`new_with_timer`] conservatively uses 64 rounds, but often less rounds - /// can be used. The `test_timer()` function returns the minimum number of - /// rounds required for full strength (platform dependent), so one may use - /// `rng.set_rounds(rng.test_timer()?);` or cache the value. - /// - /// [`new_with_timer`]: JitterRng::new_with_timer - pub fn set_rounds(&mut self, rounds: u8) { - assert!(rounds > 0); - self.rounds = rounds; - } - - // Calculate a random loop count used for the next round of an entropy - // collection, based on bits from a fresh value from the timer. - // - // The timer is folded to produce a number that contains at most `n_bits` - // bits. - // - // Note: A constant should be added to the resulting random loop count to - // prevent loops that run 0 times. - #[inline(never)] - fn random_loop_cnt(&mut self, n_bits: u32) -> u32 { - let mut rounds = 0; - - let mut time = (self.timer)(); - // Mix with the current state of the random number balance the random - // loop counter a bit more. - time ^= self.data; - - // We fold the time value as much as possible to ensure that as many - // bits of the time stamp are included as possible. - let folds = (64 + n_bits - 1) / n_bits; - let mask = (1 << n_bits) - 1; - for _ in 0..folds { - rounds ^= time & mask; - time >>= n_bits; - } - - rounds as u32 - } - - // CPU jitter noise source - // Noise source based on the CPU execution time jitter - // - // This function injects the individual bits of the time value into the - // entropy pool using an LFSR. - // - // The code is deliberately inefficient with respect to the bit shifting. - // This function not only acts as folding operation, but this function's - // execution is used to measure the CPU execution time jitter. Any change to - // the loop in this function implies that careful retesting must be done. - #[inline(never)] - fn lfsr_time(&mut self, time: u64, var_rounds: bool) { - fn lfsr(mut data: u64, time: u64) -> u64{ - for i in 1..65 { - let mut tmp = time << (64 - i); - tmp >>= 64 - 1; - - // Fibonacci LSFR with polynomial of - // x^64 + x^61 + x^56 + x^31 + x^28 + x^23 + 1 which is - // primitive according to - // http://poincare.matf.bg.ac.rs/~ezivkovm/publications/primpol1.pdf - // (the shift values are the polynomial values minus one - // due to counting bits from 0 to 63). As the current - // position is always the LSB, the polynomial only needs - // to shift data in from the left without wrap. - data ^= tmp; - data ^= (data >> 63) & 1; - data ^= (data >> 60) & 1; - data ^= (data >> 55) & 1; - data ^= (data >> 30) & 1; - data ^= (data >> 27) & 1; - data ^= (data >> 22) & 1; - data = data.rotate_left(1); - } - data - } - - // Note: in the reference implementation only the last round effects - // `self.data`, all the other results are ignored. To make sure the - // other rounds are not optimised out, we first run all but the last - // round on a throw-away value instead of the real `self.data`. - let mut lfsr_loop_cnt = 0; - if var_rounds { lfsr_loop_cnt = self.random_loop_cnt(4) }; - - let mut throw_away: u64 = 0; - for _ in 0..lfsr_loop_cnt { - throw_away = lfsr(throw_away, time); - } - black_box(throw_away); - - self.data = lfsr(self.data, time); - } - - // Memory Access noise source - // This is a noise source based on variations in memory access times - // - // This function performs memory accesses which will add to the timing - // variations due to an unknown amount of CPU wait states that need to be - // added when accessing memory. The memory size should be larger than the L1 - // caches as outlined in the documentation and the associated testing. - // - // The L1 cache has a very high bandwidth, albeit its access rate is usually - // slower than accessing CPU registers. Therefore, L1 accesses only add - // minimal variations as the CPU has hardly to wait. Starting with L2, - // significant variations are added because L2 typically does not belong to - // the CPU any more and therefore a wider range of CPU wait states is - // necessary for accesses. L3 and real memory accesses have even a wider - // range of wait states. However, to reliably access either L3 or memory, - // the `self.mem` memory must be quite large which is usually not desirable. - #[inline(never)] - fn memaccess(&mut self, mem: &mut [u8; MEMORY_SIZE], var_rounds: bool) { - let mut acc_loop_cnt = 128; - if var_rounds { acc_loop_cnt += self.random_loop_cnt(4) }; - - let mut index = self.mem_prev_index as usize; - for _ in 0..acc_loop_cnt { - // Addition of memblocksize - 1 to index with wrap around logic to - // ensure that every memory location is hit evenly. - // The modulus also allows the compiler to remove the indexing - // bounds check. - index = (index + MEMORY_BLOCKSIZE - 1) % MEMORY_SIZE; - - // memory access: just add 1 to one byte - // memory access implies read from and write to memory location - mem[index] = mem[index].wrapping_add(1); - } - self.mem_prev_index = index as u16; - } - - // This is the heart of the entropy generation: calculate time deltas and - // use the CPU jitter in the time deltas. The jitter is injected into the - // entropy pool. - // - // Ensure that `ec.prev_time` is primed before using the output of this - // function. This can be done by calling this function and not using its - // result. - fn measure_jitter(&mut self, ec: &mut EcState) -> Option<()> { - // Invoke one noise source before time measurement to add variations - self.memaccess(&mut ec.mem, true); - - // Get time stamp and calculate time delta to previous - // invocation to measure the timing variations - let time = (self.timer)(); - // Note: wrapping_sub combined with a cast to `i64` generates a correct - // delta, even in the unlikely case this is a timer that is not strictly - // monotonic. - let current_delta = time.wrapping_sub(ec.prev_time) as i64 as i32; - ec.prev_time = time; - - // Call the next noise source which also injects the data - self.lfsr_time(current_delta as u64, true); - - // Check whether we have a stuck measurement (i.e. does the last - // measurement holds entropy?). - if ec.stuck(current_delta) { return None }; - - // Rotate the data buffer by a prime number (any odd number would - // do) to ensure that every bit position of the input time stamp - // has an even chance of being merged with a bit position in the - // entropy pool. We do not use one here as the adjacent bits in - // successive time deltas may have some form of dependency. The - // chosen value of 7 implies that the low 7 bits of the next - // time delta value is concatenated with the current time delta. - self.data = self.data.rotate_left(7); - - Some(()) - } - - // Shuffle the pool a bit by mixing some value with a bijective function - // (XOR) into the pool. - // - // The function generates a mixer value that depends on the bits set and - // the location of the set bits in the random number generated by the - // entropy source. Therefore, based on the generated random number, this - // mixer value can have 2^64 different values. That mixer value is - // initialized with the first two SHA-1 constants. After obtaining the - // mixer value, it is XORed into the random number. - // - // The mixer value is not assumed to contain any entropy. But due to the - // XOR operation, it can also not destroy any entropy present in the - // entropy pool. - #[inline(never)] - fn stir_pool(&mut self) { - // This constant is derived from the first two 32 bit initialization - // vectors of SHA-1 as defined in FIPS 180-4 section 5.3.1 - // The order does not really matter as we do not rely on the specific - // numbers. We just pick the SHA-1 constants as they have a good mix of - // bit set and unset. - const CONSTANT: u64 = 0x67452301efcdab89; - - // The start value of the mixer variable is derived from the third - // and fourth 32 bit initialization vector of SHA-1 as defined in - // FIPS 180-4 section 5.3.1 - let mut mixer = 0x98badcfe10325476; - - // This is a constant time function to prevent leaking timing - // information about the random number. - // The normal code is: - // ``` - // for i in 0..64 { - // if ((self.data >> i) & 1) == 1 { mixer ^= CONSTANT; } - // } - // ``` - // This is a bit fragile, as LLVM really wants to use branches here, and - // we rely on it to not recognise the opportunity. - for i in 0..64 { - let apply = (self.data >> i) & 1; - let mask = !apply.wrapping_sub(1); - mixer ^= CONSTANT & mask; - mixer = mixer.rotate_left(1); - } - - self.data ^= mixer; - } - - fn gen_entropy(&mut self) -> u64 { - trace!("JitterRng: collecting entropy"); - - // Prime `ec.prev_time`, and run the noice sources to make sure the - // first loop round collects the expected entropy. - let mut ec = EcState { - prev_time: (self.timer)(), - last_delta: 0, - last_delta2: 0, - mem: [0; MEMORY_SIZE], - }; - let _ = self.measure_jitter(&mut ec); - - for _ in 0..self.rounds { - // If a stuck measurement is received, repeat measurement - // Note: we do not guard against an infinite loop, that would mean - // the timer suddenly became broken. - while self.measure_jitter(&mut ec).is_none() {} - } - - // Do a single read from `self.mem` to make sure the Memory Access noise - // source is not optimised out. - black_box(ec.mem[0]); - - self.stir_pool(); - self.data - } - - /// Basic quality tests on the timer, by measuring CPU timing jitter a few - /// hundred times. - /// - /// If successful, this will return the estimated number of rounds necessary - /// to collect 64 bits of entropy. Otherwise a [`TimerError`] with the cause - /// of the failure will be returned. - pub fn test_timer(&mut self) -> Result { - debug!("JitterRng: testing timer ..."); - // We could add a check for system capabilities such as `clock_getres` - // or check for `CONFIG_X86_TSC`, but it does not make much sense as the - // following sanity checks verify that we have a high-resolution timer. - - let mut delta_sum = 0; - let mut old_delta = 0; - - let mut time_backwards = 0; - let mut count_mod = 0; - let mut count_stuck = 0; - - let mut ec = EcState { - prev_time: (self.timer)(), - last_delta: 0, - last_delta2: 0, - mem: [0; MEMORY_SIZE], - }; - - // TESTLOOPCOUNT needs some loops to identify edge systems. - // 100 is definitely too little. - const TESTLOOPCOUNT: u64 = 300; - const CLEARCACHE: u64 = 100; - - for i in 0..(CLEARCACHE + TESTLOOPCOUNT) { - // Measure time delta of core entropy collection logic - let time = (self.timer)(); - self.memaccess(&mut ec.mem, true); - self.lfsr_time(time, true); - let time2 = (self.timer)(); - - // Test whether timer works - if time == 0 || time2 == 0 { - return Err(TimerError::NoTimer); - } - let delta = time2.wrapping_sub(time) as i64 as i32; - - // Test whether timer is fine grained enough to provide delta even - // when called shortly after each other -- this implies that we also - // have a high resolution timer - if delta == 0 { - return Err(TimerError::CoarseTimer); - } - - // Up to here we did not modify any variable that will be - // evaluated later, but we already performed some work. Thus we - // already have had an impact on the caches, branch prediction, - // etc. with the goal to clear it to get the worst case - // measurements. - if i < CLEARCACHE { continue; } - - if ec.stuck(delta) { count_stuck += 1; } - - // Test whether we have an increasing timer. - if !(time2 > time) { time_backwards += 1; } - - // Count the number of times the counter increases in steps of 100ns - // or greater. - if (delta % 100) == 0 { count_mod += 1; } - - // Ensure that we have a varying delta timer which is necessary for - // the calculation of entropy -- perform this check only after the - // first loop is executed as we need to prime the old_delta value - delta_sum += (delta - old_delta).abs() as u64; - old_delta = delta; - } - - // Do a single read from `self.mem` to make sure the Memory Access noise - // source is not optimised out. - black_box(ec.mem[0]); - - // We allow the time to run backwards for up to three times. - // This can happen if the clock is being adjusted by NTP operations. - // If such an operation just happens to interfere with our test, it - // should not fail. The value of 3 should cover the NTP case being - // performed during our test run. - if time_backwards > 3 { - return Err(TimerError::NotMonotonic); - } - - // Test that the available amount of entropy per round does not get to - // low. We expect 1 bit of entropy per round as a reasonable minimum - // (although less is possible, it means the collector loop has to run - // much more often). - // `assert!(delta_average >= log2(1))` - // `assert!(delta_sum / TESTLOOPCOUNT >= 1)` - // `assert!(delta_sum >= TESTLOOPCOUNT)` - if delta_sum < TESTLOOPCOUNT { - return Err(TimerError::TinyVariantions); - } - - // Ensure that we have variations in the time stamp below 100 for at - // least 10% of all checks -- on some platforms, the counter increments - // in multiples of 100, but not always - if count_mod > (TESTLOOPCOUNT * 9 / 10) { - return Err(TimerError::CoarseTimer); - } - - // If we have more than 90% stuck results, then this Jitter RNG is - // likely to not work well. - if count_stuck > (TESTLOOPCOUNT * 9 / 10) { - return Err(TimerError::TooManyStuck); - } - - // Estimate the number of `measure_jitter` rounds necessary for 64 bits - // of entropy. - // - // We don't try very hard to come up with a good estimate of the - // available bits of entropy per round here for two reasons: - // 1. Simple estimates of the available bits (like Shannon entropy) are - // too optimistic. - // 2. Unless we want to waste a lot of time during intialization, there - // only a small number of samples are available. - // - // Therefore we use a very simple and conservative estimate: - // `let bits_of_entropy = log2(delta_average) / 2`. - // - // The number of rounds `measure_jitter` should run to collect 64 bits - // of entropy is `64 / bits_of_entropy`. - let delta_average = delta_sum / TESTLOOPCOUNT; - - if delta_average >= 16 { - let log2 = 64 - delta_average.leading_zeros(); - // Do something similar to roundup(64/(log2/2)): - Ok( ((64u32 * 2 + log2 - 1) / log2) as u8) - } else { - // For values < 16 the rounding error becomes too large, use a - // lookup table. - // Values 0 and 1 are invalid, and filtered out by the - // `delta_sum < TESTLOOPCOUNT` test above. - let log2_lookup = [0, 0, 128, 81, 64, 56, 50, 46, - 43, 41, 39, 38, 36, 35, 34, 33]; - Ok(log2_lookup[delta_average as usize]) - } - } - - /// Statistical test: return the timer delta of one normal run of the - /// `JitterRng` entropy collector. - /// - /// Setting `var_rounds` to `true` will execute the memory access and the - /// CPU jitter noice sources a variable amount of times (just like a real - /// `JitterRng` round). - /// - /// Setting `var_rounds` to `false` will execute the noice sources the - /// minimal number of times. This can be used to measure the minimum amount - /// of entropy one round of the entropy collector can collect in the worst - /// case. - /// - /// See this crate's README on how to use `timer_stats` to test the quality - /// of `JitterRng`. - pub fn timer_stats(&mut self, var_rounds: bool) -> i64 { - let mut mem = [0; MEMORY_SIZE]; - - let time = (self.timer)(); - self.memaccess(&mut mem, var_rounds); - self.lfsr_time(time, var_rounds); - let time2 = (self.timer)(); - time2.wrapping_sub(time) as i64 - } -} - -// A function that is opaque to the optimizer to assist in avoiding dead-code -// elimination. Taken from `bencher`. -fn black_box(dummy: T) -> T { - unsafe { - let ret = ptr::read_volatile(&dummy); - mem::forget(dummy); - ret - } -} - -impl RngCore for JitterRng { - fn next_u32(&mut self) -> u32 { - // We want to use both parts of the generated entropy - if self.data_half_used { - self.data_half_used = false; - (self.data >> 32) as u32 - } else { - self.data = self.next_u64(); - self.data_half_used = true; - self.data as u32 - } - } - - fn next_u64(&mut self) -> u64 { - self.data_half_used = false; - self.gen_entropy() - } - - fn fill_bytes(&mut self, dest: &mut [u8]) { - // Fill using `next_u32`. This is faster for filling small slices (four - // bytes or less), while the overhead is negligible. - // - // This is done especially for wrappers that implement `next_u32` - // themselves via `fill_bytes`. - impls::fill_bytes_via_next(self, dest) - } - - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - Ok(self.fill_bytes(dest)) - } -} diff --git a/rand/rand_jitter/src/platform.rs b/rand/rand_jitter/src/platform.rs deleted file mode 100644 index 8e3d0fb..0000000 --- a/rand/rand_jitter/src/platform.rs +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// Copyright 2013-2015 The Rust Project Developers. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "windows")))] -pub fn get_nstime() -> u64 { - use std::time::{SystemTime, UNIX_EPOCH}; - - let dur = SystemTime::now().duration_since(UNIX_EPOCH).unwrap(); - // The correct way to calculate the current time is - // `dur.as_secs() * 1_000_000_000 + dur.subsec_nanos() as u64` - // But this is faster, and the difference in terms of entropy is - // negligible (log2(10^9) == 29.9). - dur.as_secs() << 30 | dur.subsec_nanos() as u64 -} - -#[cfg(any(target_os = "macos", target_os = "ios"))] -pub fn get_nstime() -> u64 { - use libc; - - // On Mac OS and iOS std::time::SystemTime only has 1000ns resolution. - // We use `mach_absolute_time` instead. This provides a CPU dependent - // unit, to get real nanoseconds the result should by multiplied by - // numer/denom from `mach_timebase_info`. - // But we are not interested in the exact nanoseconds, just entropy. So - // we use the raw result. - unsafe { libc::mach_absolute_time() } -} - -#[cfg(target_os = "windows")] -pub fn get_nstime() -> u64 { - use winapi; - - unsafe { - let mut t = super::mem::zeroed(); - winapi::um::profileapi::QueryPerformanceCounter(&mut t); - *t.QuadPart() as u64 - } -} diff --git a/rand/rand_jitter/tests/mod.rs b/rand/rand_jitter/tests/mod.rs deleted file mode 100644 index 961dc27..0000000 --- a/rand/rand_jitter/tests/mod.rs +++ /dev/null @@ -1,28 +0,0 @@ -use rand_jitter::JitterRng; -#[cfg(feature = "std")] -use rand_core::RngCore; - -#[cfg(feature = "std")] -#[test] -fn test_jitter_init() { - // Because this is a debug build, measurements here are not representive - // of the final release build. - // Don't fail this test if initializing `JitterRng` fails because of a - // bad timer (the timer from the standard library may not have enough - // accuracy on all platforms). - match JitterRng::new() { - Ok(ref mut rng) => { - // false positives are possible, but extremely unlikely - assert!(rng.next_u32() | rng.next_u32() != 0); - }, - Err(_) => {}, - } -} - -#[test] -fn test_jitter_bad_timer() { - fn bad_timer() -> u64 { 0 } - let mut rng = JitterRng::new_with_timer(bad_timer); - assert!(rng.test_timer().is_err()); -} - diff --git a/rand/rand_os/CHANGELOG.md b/rand/rand_os/CHANGELOG.md deleted file mode 100644 index b0c6549..0000000 --- a/rand/rand_os/CHANGELOG.md +++ /dev/null @@ -1,35 +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.2.2] - 2019-09-02 -### Changed -- `OsRng` added to `rand_core`, rendering this crate deprecated (#863) - -## [0.2.1] - 2019-08-08 -### Fixed -- Fix `no_std` support. - -## [0.2.0] - 2019-06-06 -### Changed -- Minimum Supported Rust Version has changed to 1.32. -- Replaced implementation with a backwards-compatible shim around -[getrandom](https://crates.io/crates/getrandom). - -## [0.1.3] - 2019-03-05 -### Fixed -- Fix support for Illumos (#730) -- Fix deprecation warnings from atomic init (#739) - -## [0.1.2] - 2019-01-28 -### Changed -- Fuchsia: Replaced fuchsia-zircon with fuchsia-cprng - -## [0.1.1] - 2019-01-08 -### Added -- Add support for x86_64-fortanix-unknown-sgx target (#670) - -## [0.1.0] - 2019-01-04 -Initial release. diff --git a/rand/rand_os/COPYRIGHT b/rand/rand_os/COPYRIGHT deleted file mode 100644 index 468d907..0000000 --- a/rand/rand_os/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 or - or the MIT license - or , at your option. - -The Rand project includes code from the Rust project -published under these same licenses. diff --git a/rand/rand_os/Cargo.toml b/rand/rand_os/Cargo.toml deleted file mode 100644 index c8010e2..0000000 --- a/rand/rand_os/Cargo.toml +++ /dev/null @@ -1,26 +0,0 @@ -[package] -name = "rand_os" -version = "0.2.2" -authors = ["The Rand Project Developers"] -license = "MIT OR Apache-2.0" -readme = "README.md" -repository = "https://github.com/rust-random/rand" -documentation = "https://docs.rs/rand_os" -homepage = "https://crates.io/crates/rand_os" -description = "OS backed Random Number Generator" -keywords = ["random", "rng", "os"] -edition = "2018" - -[badges] -travis-ci = { repository = "rust-random/rand" } -appveyor = { repository = "rust-random/rand" } - -[features] -log = ["getrandom/log"] -# re-export optional WASM dependencies to avoid breakage: -wasm-bindgen = ["getrandom/wasm-bindgen"] -stdweb = ["getrandom/stdweb"] - -[dependencies] -rand_core = { path = "../rand_core", version = "0.5", features = ["getrandom"] } -getrandom = "0.1.1" diff --git a/rand/rand_os/LICENSE-APACHE b/rand/rand_os/LICENSE-APACHE deleted file mode 100644 index 17d7468..0000000 --- a/rand/rand_os/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_os/LICENSE-MIT b/rand/rand_os/LICENSE-MIT deleted file mode 100644 index d93b5ba..0000000 --- a/rand/rand_os/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_os/README.md b/rand/rand_os/README.md deleted file mode 100644 index 7b68b35..0000000 --- a/rand/rand_os/README.md +++ /dev/null @@ -1,35 +0,0 @@ -# rand_os - -[![Build Status](https://travis-ci.org/rust-random/rand.svg?branch=master)](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_os.svg)](https://crates.io/crates/rand_os) -[![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_os) -[![API](https://docs.rs/rand_os/badge.svg)](https://docs.rs/rand_os) -[![Minimum rustc version](https://img.shields.io/badge/rustc-1.32+-lightgray.svg)](https://github.com/rust-random/rand#rust-version-requirements) - -A random number generator that retrieves randomness straight from the -operating system. - -**This crate is deprecated:** `OsRng` is available in `rand_core` since version 0.5.1. - -This crate provides `OsRng` as a shim around -[getrandom](https://crates.io/crates/getrandom) -implementing `RngCore` from [rand_core](https://crates.io/crates/rand_core). - -Note: the `rand` crate provides an equivalent `OsRng`; the two implementations -are equivalent, though distinct types. - -Links: - -- [API documentation (master)](https://rust-random.github.io/rand/rand_os) -- [API documentation (docs.rs)](https://docs.rs/rand_os) -- [Changelog](https://github.com/rust-random/rand/blob/master/rand_os/CHANGELOG.md) - -## License - -`rand_os` 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_os/src/lib.rs b/rand/rand_os/src/lib.rs deleted file mode 100644 index abfdf79..0000000 --- a/rand/rand_os/src/lib.rs +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// Copyright 2013-2015 The Rust Project Developers. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , 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::rngs::os module! - -#![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))))] - -#![no_std] // but see getrandom crate - -#![deprecated(since="0.2.2", note="OsRng is now provided by rand_core and rand")] - -pub use rand_core; // re-export - -use getrandom::getrandom; -use rand_core::{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. -/// -/// # 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 -/// ``` -/// #![allow(deprecated)] -/// use rand_os::rand_core::RngCore; -/// use rand_os::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 OsRng { - /// Create a new `OsRng`. - #[deprecated(since="0.2.0", note="replace OsRng::new().unwrap() with just OsRng")] - pub fn new() -> Result { - Ok(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); -} diff --git a/rand/rand_pcg/CHANGELOG.md b/rand/rand_pcg/CHANGELOG.md deleted file mode 100644 index a9b82fd..0000000 --- a/rand/rand_pcg/CHANGELOG.md +++ /dev/null @@ -1,24 +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.2.0] - 2019-06-12 -- Add `Lcg128Xsl64` aka `Pcg64` -- Bump minor crate version since rand_core bump is a breaking change -- Switch to Edition 2018 - -## [0.1.2] - 2019-02-23 -- require `bincode` 1.1.2 for i128 auto-detection -- make `bincode` a dev-dependency again #663 -- clean up tests and Serde support - -## [0.1.1] - 2018-10-04 -- make `bincode` an explicit dependency when using Serde - -## [0.1.0] - 2018-10-04 -Initial release, including: - -- `Lcg64Xsh32` aka `Pcg32` -- `Mcg128Xsl64` aka `Pcg64Mcg` diff --git a/rand/rand_pcg/COPYRIGHT b/rand/rand_pcg/COPYRIGHT deleted file mode 100644 index 468d907..0000000 --- a/rand/rand_pcg/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 or - or the MIT license - or , at your option. - -The Rand project includes code from the Rust project -published under these same licenses. diff --git a/rand/rand_pcg/Cargo.toml b/rand/rand_pcg/Cargo.toml deleted file mode 100644 index e2aa157..0000000 --- a/rand/rand_pcg/Cargo.toml +++ /dev/null @@ -1,32 +0,0 @@ -[package] -name = "rand_pcg" -version = "0.2.0" -authors = ["The Rand 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_pcg/" -homepage = "https://crates.io/crates/rand_pcg" -description = """ -Selected PCG random number generators -""" -keywords = ["random", "rng", "pcg"] -categories = ["algorithms", "no-std"] -edition = "2018" - -[badges] -travis-ci = { repository = "rust-random/rand" } -appveyor = { repository = "rust-random/rand" } - -[features] -serde1 = ["serde"] - -[dependencies] -rand_core = { path = "../rand_core", version = "0.5" } -serde = { version = "1", features = ["derive"], optional = true } - -[dev-dependencies] -# This is for testing serde, unfortunately we can't specify feature-gated dev -# deps yet, see: https://github.com/rust-lang/cargo/issues/1596 -# We require at least 1.1.2 for i128 auto-detection -bincode = { version = "1.1.2" } diff --git a/rand/rand_pcg/LICENSE-APACHE b/rand/rand_pcg/LICENSE-APACHE deleted file mode 100644 index 17d7468..0000000 --- a/rand/rand_pcg/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_pcg/LICENSE-MIT b/rand/rand_pcg/LICENSE-MIT deleted file mode 100644 index d46f058..0000000 --- a/rand/rand_pcg/LICENSE-MIT +++ /dev/null @@ -1,26 +0,0 @@ -Copyright (c) 2014-2017 Melissa O'Neill and PCG Project contributors -Copyright 2018 Developers of the Rand project - -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_pcg/README.md b/rand/rand_pcg/README.md deleted file mode 100644 index fe47f2d..0000000 --- a/rand/rand_pcg/README.md +++ /dev/null @@ -1,43 +0,0 @@ -# rand_pcg - -[![Build Status](https://travis-ci.org/rust-random/rand.svg?branch=master)](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_pcg.svg)](https://crates.io/crates/rand_pcg) -[[![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_pcg) -[![API](https://docs.rs/rand_pcg/badge.svg)](https://docs.rs/rand_pcg) -[![Minimum rustc version](https://img.shields.io/badge/rustc-1.32+-lightgray.svg)](https://github.com/rust-random/rand#rust-version-requirements) - -Implements a selection of PCG random number generators. - -> PCG is a family of simple fast space-efficient statistically good algorithms -> for random number generation. [Melissa O'Neill, Harvey Mudd College, 2014]. - -The PCG algorithms are not suitable for cryptographic uses, but perform well -in statistical tests, use little memory and are fairly fast. -See the [pcg-random website](http://www.pcg-random.org/). - -This crate depends on [rand_core](https://crates.io/crates/rand_core) and is -part of the [Rand project](https://github.com/rust-random/rand). - -Links: - -- [API documentation (master)](https://rust-random.github.io/rand/rand_pcg) -- [API documentation (docs.rs)](https://docs.rs/rand_pcg) -- [Changelog](https://github.com/rust-random/rand/blob/master/rand_pcg/CHANGELOG.md) - - -## Crate Features - -`rand_pcg` is `no_std` compatible by default. - -The `serde1` feature includes implementations of `Serialize` and `Deserialize` -for the included RNGs. - -## License - -`rand_pcg` 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_pcg/src/lib.rs b/rand/rand_pcg/src/lib.rs deleted file mode 100644 index 22ba4a0..0000000 --- a/rand/rand_pcg/src/lib.rs +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The PCG random number generators. -//! -//! This is a native Rust implementation of a small selection of PCG generators. -//! The primary goal of this crate is simple, minimal, well-tested code; in -//! other words it is explicitly not a goal to re-implement all of PCG. -//! -//! This crate provides: -//! -//! - `Pcg32` aka `Lcg64Xsh32`, officially known as `pcg32`, a general -//! purpose RNG. This is a good choice on both 32-bit and 64-bit CPUs -//! (for 32-bit output). -//! - `Pcg64` aka `Lcg128Xsl64`, officially known as `pcg64`, a general -//! purpose RNG. This is a good choice on 64-bit CPUs. -//! - `Pcg64Mcg` aka `Mcg128Xsl64`, officially known as `pcg64_fast`, -//! a general purpose RNG using 128-bit multiplications. This has poor -//! performance on 32-bit CPUs but is a good choice on 64-bit CPUs for -//! both 32-bit and 64-bit output. -//! -//! Both of these use 16 bytes of state and 128-bit seeds, and are considered -//! value-stable (i.e. any change affecting the output given a fixed seed would -//! be considered a breaking change to the crate). - -#![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)] - -#![allow(clippy::unreadable_literal)] - -#![no_std] - -mod pcg64; -#[cfg(not(target_os = "emscripten"))] mod pcg128; - -pub use self::pcg64::{Pcg32, Lcg64Xsh32}; -#[cfg(not(target_os = "emscripten"))] pub use self::pcg128::{ - Pcg64, Lcg128Xsl64, - Pcg64Mcg, Mcg128Xsl64, -}; diff --git a/rand/rand_pcg/src/pcg128.rs b/rand/rand_pcg/src/pcg128.rs deleted file mode 100644 index 311a41b..0000000 --- a/rand/rand_pcg/src/pcg128.rs +++ /dev/null @@ -1,225 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// Copyright 2017 Paul Dicker. -// Copyright 2014-2017 Melissa O'Neill and PCG Project contributors -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! PCG random number generators - -// This is the default multiplier used by PCG for 64-bit state. -const MULTIPLIER: u128 = 0x2360_ED05_1FC6_5DA4_4385_DF64_9FCC_F645; - -use core::fmt; -use rand_core::{RngCore, SeedableRng, Error, le}; -#[cfg(feature="serde1")] use serde::{Serialize, Deserialize}; - -/// A PCG random number generator (XSL RR 128/64 (LCG) variant). -/// -/// Permuted Congruential Generator with 128-bit state, internal Linear -/// Congruential Generator, and 64-bit output via "xorshift low (bits), -/// random rotation" output function. -/// -/// This is a 128-bit LCG with explicitly chosen stream with the PCG-XSL-RR -/// output function. This combination is the standard `pcg64`. -/// -/// Despite the name, this implementation uses 32 bytes (256 bit) space -/// comprising 128 bits of state and 128 bits stream selector. These are both -/// set by `SeedableRng`, using a 256-bit seed. -#[derive(Clone)] -#[cfg_attr(feature="serde1", derive(Serialize,Deserialize))] -pub struct Lcg128Xsl64 { - state: u128, - increment: u128, -} - -/// `Lcg128Xsl64` is also officially known as `pcg64`. -pub type Pcg64 = Lcg128Xsl64; - -impl Lcg128Xsl64 { - /// Construct an instance compatible with PCG seed and stream. - /// - /// Note that PCG specifies default values for both parameters: - /// - /// - `state = 0xcafef00dd15ea5e5` - /// - `stream = 0xa02bdbf7bb3c0a7ac28fa16a64abf96` - pub fn new(state: u128, stream: u128) -> Self { - // The increment must be odd, hence we discard one bit: - let increment = (stream << 1) | 1; - Lcg128Xsl64::from_state_incr(state, increment) - } - - #[inline] - fn from_state_incr(state: u128, increment: u128) -> Self { - let mut pcg = Lcg128Xsl64 { state, increment }; - // Move away from inital value: - pcg.state = pcg.state.wrapping_add(pcg.increment); - pcg.step(); - pcg - } - - #[inline] - fn step(&mut self) { - // prepare the LCG for the next round - self.state = self.state - .wrapping_mul(MULTIPLIER) - .wrapping_add(self.increment); - } -} - -// Custom Debug implementation that does not expose the internal state -impl fmt::Debug for Lcg128Xsl64 { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "Lcg128Xsl64 {{}}") - } -} - -/// We use a single 255-bit seed to initialise the state and select a stream. -/// One `seed` bit (lowest bit of `seed[8]`) is ignored. -impl SeedableRng for Lcg128Xsl64 { - type Seed = [u8; 32]; - - fn from_seed(seed: Self::Seed) -> Self { - let mut seed_u64 = [0u64; 4]; - le::read_u64_into(&seed, &mut seed_u64); - let state = u128::from(seed_u64[0]) | (u128::from(seed_u64[1]) << 64); - let incr = u128::from(seed_u64[2]) | (u128::from(seed_u64[3]) << 64); - - // The increment must be odd, hence we discard one bit: - Lcg128Xsl64::from_state_incr(state, incr | 1) - } -} - -impl RngCore for Lcg128Xsl64 { - #[inline] - fn next_u32(&mut self) -> u32 { - self.next_u64() as u32 - } - - #[inline] - fn next_u64(&mut self) -> u64 { - self.step(); - output_xsl_rr(self.state) - } - - #[inline] - fn fill_bytes(&mut self, dest: &mut [u8]) { - fill_bytes_impl(self, dest) - } - - #[inline] - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - self.fill_bytes(dest); - Ok(()) - } -} - - -/// A PCG random number generator (XSL 128/64 (MCG) variant). -/// -/// Permuted Congruential Generator with 128-bit state, internal Multiplicative -/// Congruential Generator, and 64-bit output via "xorshift low (bits), -/// random rotation" output function. -/// -/// This is a 128-bit MCG with the PCG-XSL-RR output function, also known as -/// `pcg64_fast`. -/// Note that compared to the standard `pcg64` (128-bit LCG with PCG-XSL-RR -/// output function), this RNG is faster, also has a long cycle, and still has -/// good performance on statistical tests. -#[derive(Clone)] -#[cfg_attr(feature="serde1", derive(Serialize,Deserialize))] -pub struct Mcg128Xsl64 { - state: u128, -} - -/// A friendly name for `Mcg128Xsl64` (also known as `pcg64_fast`). -pub type Pcg64Mcg = Mcg128Xsl64; - -impl Mcg128Xsl64 { - /// Construct an instance compatible with PCG seed. - /// - /// Note that PCG specifies a default value for the parameter: - /// - /// - `state = 0xcafef00dd15ea5e5` - pub fn new(state: u128) -> Self { - // Force low bit to 1, as in C version (C++ uses `state | 3` instead). - Mcg128Xsl64 { state: state | 1 } - } -} - -// Custom Debug implementation that does not expose the internal state -impl fmt::Debug for Mcg128Xsl64 { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "Mcg128Xsl64 {{}}") - } -} - -/// We use a single 126-bit seed to initialise the state and select a stream. -/// Two `seed` bits (lowest order of last byte) are ignored. -impl SeedableRng for Mcg128Xsl64 { - type Seed = [u8; 16]; - - fn from_seed(seed: Self::Seed) -> Self { - // Read as if a little-endian u128 value: - let mut seed_u64 = [0u64; 2]; - le::read_u64_into(&seed, &mut seed_u64); - let state = u128::from(seed_u64[0]) | - u128::from(seed_u64[1]) << 64; - Mcg128Xsl64::new(state) - } -} - -impl RngCore for Mcg128Xsl64 { - #[inline] - fn next_u32(&mut self) -> u32 { - self.next_u64() as u32 - } - - #[inline] - fn next_u64(&mut self) -> u64 { - self.state = self.state.wrapping_mul(MULTIPLIER); - output_xsl_rr(self.state) - } - - #[inline] - fn fill_bytes(&mut self, dest: &mut [u8]) { - fill_bytes_impl(self, dest) - } - - #[inline] - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - self.fill_bytes(dest); - Ok(()) - } -} - -#[inline(always)] -fn output_xsl_rr(state: u128) -> u64 { - // Output function XSL RR ("xorshift low (bits), random rotation") - // Constants are for 128-bit state, 64-bit output - const XSHIFT: u32 = 64; // (128 - 64 + 64) / 2 - const ROTATE: u32 = 122; // 128 - 6 - - let rot = (state >> ROTATE) as u32; - let xsl = ((state >> XSHIFT) as u64) ^ (state as u64); - xsl.rotate_right(rot) -} - -#[inline(always)] -fn fill_bytes_impl(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 > 0 { - let chunk: [u8; 8] = rng.next_u64().to_le_bytes(); - left.copy_from_slice(&chunk[..n]); - } -} diff --git a/rand/rand_pcg/src/pcg64.rs b/rand/rand_pcg/src/pcg64.rs deleted file mode 100644 index fadc6dc..0000000 --- a/rand/rand_pcg/src/pcg64.rs +++ /dev/null @@ -1,127 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// Copyright 2017 Paul Dicker. -// Copyright 2014-2017 Melissa O'Neill and PCG Project contributors -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! PCG random number generators - -use core::fmt; -use rand_core::{RngCore, SeedableRng, Error, le, impls}; -#[cfg(feature="serde1")] use serde::{Serialize, Deserialize}; - -// This is the default multiplier used by PCG for 64-bit state. -const MULTIPLIER: u64 = 6364136223846793005; - -/// A PCG random number generator (XSH RR 64/32 (LCG) variant). -/// -/// Permuted Congruential Generator with 64-bit state, internal Linear -/// Congruential Generator, and 32-bit output via "xorshift high (bits), -/// random rotation" output function. -/// -/// This is a 64-bit LCG with explicitly chosen stream with the PCG-XSH-RR -/// output function. This combination is the standard `pcg32`. -/// -/// Despite the name, this implementation uses 16 bytes (128 bit) space -/// comprising 64 bits of state and 64 bits stream selector. These are both set -/// by `SeedableRng`, using a 128-bit seed. -#[derive(Clone)] -#[cfg_attr(feature="serde1", derive(Serialize,Deserialize))] -pub struct Lcg64Xsh32 { - state: u64, - increment: u64, -} - -/// `Lcg64Xsh32` is also officially known as `pcg32`. -pub type Pcg32 = Lcg64Xsh32; - -impl Lcg64Xsh32 { - /// Construct an instance compatible with PCG seed and stream. - /// - /// Note that PCG specifies default values for both parameters: - /// - /// - `state = 0xcafef00dd15ea5e5` - /// - `stream = 0xa02bdbf7bb3c0a7` - // Note: stream is 1442695040888963407u64 >> 1 - pub fn new(state: u64, stream: u64) -> Self { - // The increment must be odd, hence we discard one bit: - let increment = (stream << 1) | 1; - Lcg64Xsh32::from_state_incr(state, increment) - } - - #[inline] - fn from_state_incr(state: u64, increment: u64) -> Self { - let mut pcg = Lcg64Xsh32 { state, increment }; - // Move away from inital value: - pcg.state = pcg.state.wrapping_add(pcg.increment); - pcg.step(); - pcg - } - - #[inline] - fn step(&mut self) { - // prepare the LCG for the next round - self.state = self.state - .wrapping_mul(MULTIPLIER) - .wrapping_add(self.increment); - } -} - -// Custom Debug implementation that does not expose the internal state -impl fmt::Debug for Lcg64Xsh32 { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "Lcg64Xsh32 {{}}") - } -} - -/// We use a single 127-bit seed to initialise the state and select a stream. -/// One `seed` bit (lowest bit of `seed[8]`) is ignored. -impl SeedableRng for Lcg64Xsh32 { - type Seed = [u8; 16]; - - fn from_seed(seed: Self::Seed) -> Self { - let mut seed_u64 = [0u64; 2]; - le::read_u64_into(&seed, &mut seed_u64); - - // The increment must be odd, hence we discard one bit: - Lcg64Xsh32::from_state_incr(seed_u64[0], seed_u64[1] | 1) - } -} - -impl RngCore for Lcg64Xsh32 { - #[inline] - fn next_u32(&mut self) -> u32 { - let state = self.state; - self.step(); - - // Output function XSH RR: xorshift high (bits), followed by a random rotate - // Constants are for 64-bit state, 32-bit output - const ROTATE: u32 = 59; // 64 - 5 - const XSHIFT: u32 = 18; // (5 + 32) / 2 - const SPARE: u32 = 27; // 64 - 32 - 5 - - let rot = (state >> ROTATE) as u32; - let xsh = (((state >> XSHIFT) ^ state) >> SPARE) as u32; - xsh.rotate_right(rot) - } - - #[inline] - fn next_u64(&mut self) -> u64 { - impls::next_u64_via_u32(self) - } - - #[inline] - fn fill_bytes(&mut self, dest: &mut [u8]) { - impls::fill_bytes_via_next(self, dest) - } - - #[inline] - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - self.fill_bytes(dest); - Ok(()) - } -} diff --git a/rand/rand_pcg/tests/lcg128xsl64.rs b/rand/rand_pcg/tests/lcg128xsl64.rs deleted file mode 100644 index efc72ff..0000000 --- a/rand/rand_pcg/tests/lcg128xsl64.rs +++ /dev/null @@ -1,55 +0,0 @@ -use rand_core::{RngCore, SeedableRng}; -use rand_pcg::{Lcg128Xsl64, Pcg64}; - -#[test] -fn test_lcg128xsl64_construction() { - // Test that various construction techniques produce a working RNG. - let seed = [1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, - 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32]; - let mut rng1 = Lcg128Xsl64::from_seed(seed); - assert_eq!(rng1.next_u64(), 8740028313290271629); - - let mut rng2 = Lcg128Xsl64::from_rng(&mut rng1).unwrap(); - assert_eq!(rng2.next_u64(), 1922280315005786345); - - let mut rng3 = Lcg128Xsl64::seed_from_u64(0); - assert_eq!(rng3.next_u64(), 2354861276966075475); - - // This is the same as Lcg128Xsl64, so we only have a single test: - let mut rng4 = Pcg64::seed_from_u64(0); - assert_eq!(rng4.next_u64(), 2354861276966075475); -} - -#[test] -fn test_lcg128xsl64_true_values() { - // Numbers copied from official test suite (C version). - let mut rng = Lcg128Xsl64::new(42, 54); - - let mut results = [0u64; 6]; - for i in results.iter_mut() { *i = rng.next_u64(); } - let expected: [u64; 6] = [0x86b1da1d72062b68, 0x1304aa46c9853d39, - 0xa3670e9e0dd50358, 0xf9090e529a7dae00, 0xc85b9fd837996f2c, 0x606121f8e3919196]; - assert_eq!(results, expected); -} - -#[cfg(feature="serde1")] -#[test] -fn test_lcg128xsl64_serde() { - use bincode; - use std::io::{BufWriter, BufReader}; - - let mut rng = Lcg128Xsl64::seed_from_u64(0); - - let buf: Vec = Vec::new(); - let mut buf = BufWriter::new(buf); - bincode::serialize_into(&mut buf, &rng).expect("Could not serialize"); - - let buf = buf.into_inner().unwrap(); - let mut read = BufReader::new(&buf[..]); - let mut deserialized: Lcg128Xsl64 = bincode::deserialize_from(&mut read) - .expect("Could not deserialize"); - - for _ in 0..16 { - assert_eq!(rng.next_u64(), deserialized.next_u64()); - } -} diff --git a/rand/rand_pcg/tests/lcg64xsh32.rs b/rand/rand_pcg/tests/lcg64xsh32.rs deleted file mode 100644 index e05bcc1..0000000 --- a/rand/rand_pcg/tests/lcg64xsh32.rs +++ /dev/null @@ -1,54 +0,0 @@ -use rand_core::{RngCore, SeedableRng}; -use rand_pcg::{Lcg64Xsh32, Pcg32}; - -#[test] -fn test_lcg64xsh32_construction() { - // Test that various construction techniques produce a working RNG. - let seed = [1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16]; - let mut rng1 = Lcg64Xsh32::from_seed(seed); - assert_eq!(rng1.next_u64(), 1204678643940597513); - - let mut rng2 = Lcg64Xsh32::from_rng(&mut rng1).unwrap(); - assert_eq!(rng2.next_u64(), 12384929573776311845); - - let mut rng3 = Lcg64Xsh32::seed_from_u64(0); - assert_eq!(rng3.next_u64(), 18195738587432868099); - - // This is the same as Lcg64Xsh32, so we only have a single test: - let mut rng4 = Pcg32::seed_from_u64(0); - assert_eq!(rng4.next_u64(), 18195738587432868099); -} - -#[test] -fn test_lcg64xsh32_true_values() { - // Numbers copied from official test suite. - let mut rng = Lcg64Xsh32::new(42, 54); - - let mut results = [0u32; 6]; - for i in results.iter_mut() { *i = rng.next_u32(); } - let expected: [u32; 6] = [0xa15c02b7, 0x7b47f409, 0xba1d3330, - 0x83d2f293, 0xbfa4784b, 0xcbed606e]; - assert_eq!(results, expected); -} - -#[cfg(feature="serde1")] -#[test] -fn test_lcg64xsh32_serde() { - use bincode; - use std::io::{BufWriter, BufReader}; - - let mut rng = Lcg64Xsh32::seed_from_u64(0); - - let buf: Vec = Vec::new(); - let mut buf = BufWriter::new(buf); - bincode::serialize_into(&mut buf, &rng).expect("Could not serialize"); - - let buf = buf.into_inner().unwrap(); - let mut read = BufReader::new(&buf[..]); - let mut deserialized: Lcg64Xsh32 = bincode::deserialize_from(&mut read) - .expect("Could not deserialize"); - - for _ in 0..16 { - assert_eq!(rng.next_u64(), deserialized.next_u64()); - } -} diff --git a/rand/rand_pcg/tests/mcg128xsl64.rs b/rand/rand_pcg/tests/mcg128xsl64.rs deleted file mode 100644 index d58fa75..0000000 --- a/rand/rand_pcg/tests/mcg128xsl64.rs +++ /dev/null @@ -1,54 +0,0 @@ -use rand_core::{RngCore, SeedableRng}; -use rand_pcg::{Mcg128Xsl64, Pcg64Mcg}; - -#[test] -fn test_mcg128xsl64_construction() { - // Test that various construction techniques produce a working RNG. - let seed = [1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16]; - let mut rng1 = Mcg128Xsl64::from_seed(seed); - assert_eq!(rng1.next_u64(), 7071994460355047496); - - let mut rng2 = Mcg128Xsl64::from_rng(&mut rng1).unwrap(); - assert_eq!(rng2.next_u64(), 12300796107712034932); - - let mut rng3 = Mcg128Xsl64::seed_from_u64(0); - assert_eq!(rng3.next_u64(), 6198063878555692194); - - // This is the same as Mcg128Xsl64, so we only have a single test: - let mut rng4 = Pcg64Mcg::seed_from_u64(0); - assert_eq!(rng4.next_u64(), 6198063878555692194); -} - -#[test] -fn test_mcg128xsl64_true_values() { - // Numbers copied from official test suite (C version). - let mut rng = Mcg128Xsl64::new(42); - - let mut results = [0u64; 6]; - for i in results.iter_mut() { *i = rng.next_u64(); } - let expected: [u64; 6] = [0x63b4a3a813ce700a, 0x382954200617ab24, - 0xa7fd85ae3fe950ce, 0xd715286aa2887737, 0x60c92fee2e59f32c, 0x84c4e96beff30017]; - assert_eq!(results, expected); -} - -#[cfg(feature="serde1")] -#[test] -fn test_mcg128xsl64_serde() { - use bincode; - use std::io::{BufWriter, BufReader}; - - let mut rng = Mcg128Xsl64::seed_from_u64(0); - - let buf: Vec = Vec::new(); - let mut buf = BufWriter::new(buf); - bincode::serialize_into(&mut buf, &rng).expect("Could not serialize"); - - let buf = buf.into_inner().unwrap(); - let mut read = BufReader::new(&buf[..]); - let mut deserialized: Mcg128Xsl64 = bincode::deserialize_from(&mut read) - .expect("Could not deserialize"); - - for _ in 0..16 { - assert_eq!(rng.next_u64(), deserialized.next_u64()); - } -} diff --git a/rand/rand_xorshift/CHANGELOG.md b/rand/rand_xorshift/CHANGELOG.md deleted file mode 100644 index ce3098a..0000000 --- a/rand/rand_xorshift/CHANGELOG.md +++ /dev/null @@ -1,19 +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.2.0] - 2019-06-12 -- Bump minor crate version since rand_core bump is a breaking change -- Switch to Edition 2018 - -## [0.1.2] - 2019-06-06 - yanked -- Bump `rand_core` version -- Make XorShiftRng::from_rng portable by enforcing Endianness (#815) - -## [0.1.1] - 2019-01-04 -- Reorganise code and tests; tweak doc - -## [0.1.0] - 2018-07-16 -- Pulled out of the Rand crate diff --git a/rand/rand_xorshift/COPYRIGHT b/rand/rand_xorshift/COPYRIGHT deleted file mode 100644 index 468d907..0000000 --- a/rand/rand_xorshift/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 or - or the MIT license - or , at your option. - -The Rand project includes code from the Rust project -published under these same licenses. diff --git a/rand/rand_xorshift/Cargo.toml b/rand/rand_xorshift/Cargo.toml deleted file mode 100644 index 9cb257b..0000000 --- a/rand/rand_xorshift/Cargo.toml +++ /dev/null @@ -1,31 +0,0 @@ -[package] -name = "rand_xorshift" -version = "0.2.0" -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_xorshift/" -homepage = "https://crates.io/crates/rand_xorshift" -description = """ -Xorshift random number generator -""" -keywords = ["random", "rng", "xorshift"] -categories = ["algorithms", "no-std"] -edition = "2018" - -[badges] -travis-ci = { repository = "rust-random/rand" } -appveyor = { repository = "rust-random/rand" } - -[features] -serde1 = ["serde"] - -[dependencies] -rand_core = { path = "../rand_core", version = "0.5" } -serde = { version = "1", features = ["derive"], optional = true } - -[dev-dependencies] -# This is for testing serde, unfortunately we can't specify feature-gated dev -# deps yet, see: https://github.com/rust-lang/cargo/issues/1596 -bincode = "1" diff --git a/rand/rand_xorshift/LICENSE-APACHE b/rand/rand_xorshift/LICENSE-APACHE deleted file mode 100644 index 17d7468..0000000 --- a/rand/rand_xorshift/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_xorshift/LICENSE-MIT b/rand/rand_xorshift/LICENSE-MIT deleted file mode 100644 index d93b5ba..0000000 --- a/rand/rand_xorshift/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_xorshift/README.md b/rand/rand_xorshift/README.md deleted file mode 100644 index 57de284..0000000 --- a/rand/rand_xorshift/README.md +++ /dev/null @@ -1,45 +0,0 @@ -# rand_xorshift - -[![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_xorshift.svg)](https://crates.io/crates/rand_xorshift) -[![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_xorshift) -[![API](https://docs.rs/rand_xorshift/badge.svg)](https://docs.rs/rand_xorshift) -[![Minimum rustc version](https://img.shields.io/badge/rustc-1.32+-lightgray.svg)](https://github.com/rust-random/rand#rust-version-requirements) - -Implements the Xorshift random number generator. - -The Xorshift[^1] algorithm is not suitable for cryptographic purposes -but is very fast. If you do not know for sure that it fits your -requirements, use a more secure one such as `StdRng` or `OsRng`. - -[^1]: Marsaglia, George (July 2003). - ["Xorshift RNGs"](https://www.jstatsoft.org/v08/i14/paper). - *Journal of Statistical Software*. Vol. 8 (Issue 14). - -Links: - -- [API documentation (master)](https://rust-random.github.io/rand/rand_xorshift) -- [API documentation (docs.rs)](https://docs.rs/rand_xorshift) -- [Changelog](https://github.com/rust-random/rand/blob/master/rand_xorshift/CHANGELOG.md) - -[rand]: https://crates.io/crates/rand - - -## Crate Features - -`rand_xorshift` is `no_std` compatible. It does not require any functionality -outside of the `core` lib, thus there are no features to configure. - -The `serde1` feature includes implementations of `Serialize` and `Deserialize` -for the included RNGs. - - -## License - -`rand_xorshift` 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_xorshift/src/lib.rs b/rand/rand_xorshift/src/lib.rs deleted file mode 100644 index b9fef23..0000000 --- a/rand/rand_xorshift/src/lib.rs +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The xorshift random number generator. - -#![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)] - -#![no_std] - -use core::num::Wrapping as w; -use core::fmt; -use rand_core::{RngCore, SeedableRng, Error, impls, le}; -#[cfg(feature="serde1")] use serde::{Serialize, Deserialize}; - -/// An Xorshift random number generator. -/// -/// The Xorshift[^1] algorithm is not suitable for cryptographic purposes -/// but is very fast. If you do not know for sure that it fits your -/// requirements, use a more secure one such as `StdRng` or `OsRng`. -/// -/// [^1]: Marsaglia, George (July 2003). -/// ["Xorshift RNGs"](https://www.jstatsoft.org/v08/i14/paper). -/// *Journal of Statistical Software*. Vol. 8 (Issue 14). -#[derive(Clone)] -#[cfg_attr(feature="serde1", derive(Serialize,Deserialize))] -pub struct XorShiftRng { - x: w, - y: w, - z: w, - w: w, -} - -// Custom Debug implementation that does not expose the internal state -impl fmt::Debug for XorShiftRng { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "XorShiftRng {{}}") - } -} - -impl RngCore for XorShiftRng { - #[inline] - fn next_u32(&mut self) -> u32 { - let x = self.x; - let t = x ^ (x << 11); - self.x = self.y; - self.y = self.z; - self.z = self.w; - let w_ = self.w; - self.w = w_ ^ (w_ >> 19) ^ (t ^ (t >> 8)); - self.w.0 - } - - #[inline] - fn next_u64(&mut self) -> u64 { - impls::next_u64_via_u32(self) - } - - #[inline] - 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> { - self.fill_bytes(dest); - Ok(()) - } -} - -impl SeedableRng for XorShiftRng { - type Seed = [u8; 16]; - - fn from_seed(seed: Self::Seed) -> Self { - let mut seed_u32 = [0u32; 4]; - le::read_u32_into(&seed, &mut seed_u32); - - // Xorshift cannot be seeded with 0 and we cannot return an Error, but - // also do not wish to panic (because a random seed can legitimately be - // 0); our only option is therefore to use a preset value. - if seed_u32.iter().all(|&x| x == 0) { - seed_u32 = [0xBAD_5EED, 0xBAD_5EED, 0xBAD_5EED, 0xBAD_5EED]; - } - - XorShiftRng { - x: w(seed_u32[0]), - y: w(seed_u32[1]), - z: w(seed_u32[2]), - w: w(seed_u32[3]), - } - } - - fn from_rng(mut rng: R) -> Result { - let mut b = [0u8; 16]; - loop { - rng.try_fill_bytes(&mut b[..])?; - if !b.iter().all(|&x| x == 0) { - break; - } - } - - Ok(XorShiftRng { - x: w(u32::from_le_bytes([b[0], b[1], b[2], b[3]])), - y: w(u32::from_le_bytes([b[4], b[5], b[6], b[7]])), - z: w(u32::from_le_bytes([b[8], b[9], b[10], b[11]])), - w: w(u32::from_le_bytes([b[12], b[13], b[14], b[15]])), - }) - } -} diff --git a/rand/rand_xorshift/tests/mod.rs b/rand/rand_xorshift/tests/mod.rs deleted file mode 100644 index 7ecdeae..0000000 --- a/rand/rand_xorshift/tests/mod.rs +++ /dev/null @@ -1,89 +0,0 @@ -use rand_core::{RngCore, SeedableRng}; -use rand_xorshift::XorShiftRng; - -#[test] -fn test_xorshift_construction() { - // Test that various construction techniques produce a working RNG. - let seed = [1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16]; - let mut rng1 = XorShiftRng::from_seed(seed); - assert_eq!(rng1.next_u64(), 4325440999699518727); - - let mut rng2 = XorShiftRng::from_rng(&mut rng1).unwrap(); - // Yes, this makes rng2 a clone of rng1! - assert_eq!(rng1.next_u64(), 15614385950550801700); - assert_eq!(rng2.next_u64(), 15614385950550801700); -} - -#[test] -fn test_xorshift_true_values() { - let seed = [16,15,14,13, 12,11,10,9, 8,7,6,5, 4,3,2,1]; - let mut rng = XorShiftRng::from_seed(seed); - - let mut results = [0u32; 9]; - for i in results.iter_mut() { *i = rng.next_u32(); } - let expected: [u32; 9] = [ - 2081028795, 620940381, 269070770, 16943764, 854422573, 29242889, - 1550291885, 1227154591, 271695242]; - assert_eq!(results, expected); - - let mut results = [0u64; 9]; - for i in results.iter_mut() { *i = rng.next_u64(); } - let expected: [u64; 9] = [ - 9247529084182843387, 8321512596129439293, 14104136531997710878, - 6848554330849612046, 343577296533772213, 17828467390962600268, - 9847333257685787782, 7717352744383350108, 1133407547287910111]; - assert_eq!(results, expected); - - let mut results = [0u8; 32]; - rng.fill_bytes(&mut results); - let expected = [102, 57, 212, 16, 233, 130, 49, 183, - 158, 187, 44, 203, 63, 149, 45, 17, - 117, 129, 131, 160, 70, 121, 158, 155, - 224, 209, 192, 53, 10, 62, 57, 72]; - assert_eq!(results, expected); -} - -#[test] -fn test_xorshift_zero_seed() { - // Xorshift does not work with an all zero seed. - // Assert it does not panic. - let seed = [0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; - let mut rng = XorShiftRng::from_seed(seed); - let a = rng.next_u64(); - let b = rng.next_u64(); - assert!(a != 0); - assert!(b != a); -} - -#[test] -fn test_xorshift_clone() { - let seed = [1,2,3,4, 5,5,7,8, 8,7,6,5, 4,3,2,1]; - let mut rng1 = XorShiftRng::from_seed(seed); - let mut rng2 = rng1.clone(); - for _ in 0..16 { - assert_eq!(rng1.next_u64(), rng2.next_u64()); - } -} - -#[cfg(feature="serde1")] -#[test] -fn test_xorshift_serde() { - use bincode; - use std::io::{BufWriter, BufReader}; - - let seed = [1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16]; - let mut rng = XorShiftRng::from_seed(seed); - - let buf: Vec = Vec::new(); - let mut buf = BufWriter::new(buf); - bincode::serialize_into(&mut buf, &rng).expect("Could not serialize"); - - let buf = buf.into_inner().unwrap(); - let mut read = BufReader::new(&buf[..]); - let mut deserialized: XorShiftRng = bincode::deserialize_from(&mut read) - .expect("Could not deserialize"); - - for _ in 0..16 { - assert_eq!(rng.next_u64(), deserialized.next_u64()); - } -} diff --git a/rand/rand_xoshiro/CHANGELOG.md b/rand/rand_xoshiro/CHANGELOG.md deleted file mode 100644 index 56cb9c2..0000000 --- a/rand/rand_xoshiro/CHANGELOG.md +++ /dev/null @@ -1,24 +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.3.1] - 2019-08-06 -- Drop `byteorder`-dependency in favor of `stdlib`-implementation. - -## [0.3.0] - 2019-06-12 -- Bump minor crate version since rand_core bump is a breaking change -- Switch to Edition 2018 - -## [0.2.1] - 2019-06-06 - yanked -- Bump `rand_core` version -- Document crate features in README - -## [0.2.0] - 2019-05-28 -- Fix `seed_from_u64(0)` for `Xoroshiro64StarStar` and `Xoroshiro64Star`. This - breaks value stability for these generators if initialized with `seed_from_u64`. -- Implement Serde support. - -## [0.1.0] - 2019-01-04 -Initial release. diff --git a/rand/rand_xoshiro/COPYRIGHT b/rand/rand_xoshiro/COPYRIGHT deleted file mode 100644 index 468d907..0000000 --- a/rand/rand_xoshiro/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 or - or the MIT license - or , at your option. - -The Rand project includes code from the Rust project -published under these same licenses. diff --git a/rand/rand_xoshiro/Cargo.toml b/rand/rand_xoshiro/Cargo.toml deleted file mode 100644 index 128c213..0000000 --- a/rand/rand_xoshiro/Cargo.toml +++ /dev/null @@ -1,25 +0,0 @@ -[package] -name = "rand_xoshiro" -version = "0.3.1" # NB: When modifying, also modify html_root_url in lib.rs -authors = ["The Rand Project Developers"] -license = "MIT OR Apache-2.0" -readme = "README.md" -repository = "https://github.com/rust-random/rand" -documentation = "https://docs.rs/rand_xoshiro" -homepage = "https://crates.io/crates/rand_xoshiro" -description = "Xoshiro, xoroshiro and splitmix64 random number generators" -keywords = ["random", "rng"] -categories = ["algorithms"] -edition = "2018" - -[features] -serde1 = ["serde"] - -[dependencies] -rand_core = { path = "../rand_core", version = "0.5" } -serde = { version = "1", features = ["derive"], optional=true } - -[dev-dependencies] -# This is for testing serde, unfortunately we can't specify feature-gated dev -# deps yet, see: https://github.com/rust-lang/cargo/issues/1596 -bincode = { version = "1" } diff --git a/rand/rand_xoshiro/LICENSE-APACHE b/rand/rand_xoshiro/LICENSE-APACHE deleted file mode 100644 index 16fe87b..0000000 --- a/rand/rand_xoshiro/LICENSE-APACHE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://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 - - http://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_xoshiro/LICENSE-MIT b/rand/rand_xoshiro/LICENSE-MIT deleted file mode 100644 index a5e040c..0000000 --- a/rand/rand_xoshiro/LICENSE-MIT +++ /dev/null @@ -1,25 +0,0 @@ -Copyright (c) 2018 Developers of the Rand project - -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_xoshiro/README.md b/rand/rand_xoshiro/README.md deleted file mode 100644 index 1c02992..0000000 --- a/rand/rand_xoshiro/README.md +++ /dev/null @@ -1,34 +0,0 @@ -# rand_xoshiro - -[![Build Status](https://travis-ci.org/rust-random/rand.svg?branch=master)](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_xoshiro.svg)](https://crates.io/crates/rand_xoshiro) -[![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_xoshiro) -[![API](https://docs.rs/rand_xoshiro/badge.svg)](https://docs.rs/rand_xoshiro) -[![Minimum rustc version](https://img.shields.io/badge/rustc-1.32+-lightgray.svg)](https://github.com/rust-random/rand#rust-version-requirements) - -Rust implementation of the [xoshiro, xoroshiro and splitmix64](http://xoshiro.di.unimi.it) random number generators. - -This crate depends on [rand_core](https://crates.io/crates/rand_core) and is -part of the [Rand project](https://github.com/rust-random/rand). - -Links: - -- [API documentation (master)](https://rust-random.github.io/rand/rand_xoshiro) -- [API documentation (docs.rs)](https://docs.rs/rand_xoshiro) -- [Changelog](https://github.com/rust-random/rand/blob/master/rand_xoshiro/CHANGELOG.md) - -## Crate Features - -`rand_xoshiro` is no_std compatible by default. - -The `serde1` feature includes implementations of `Serialize` and `Deserialize` for the included RNGs. - -## License - -`rand_xoshiro` 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_xoshiro/src/common.rs b/rand/rand_xoshiro/src/common.rs deleted file mode 100644 index b188dd6..0000000 --- a/rand/rand_xoshiro/src/common.rs +++ /dev/null @@ -1,243 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -/// Initialize a RNG from a `u64` seed using `SplitMix64`. -macro_rules! from_splitmix { - ($seed:expr) => { { - let mut rng = crate::SplitMix64::seed_from_u64($seed); - Self::from_rng(&mut rng).unwrap() - } } -} - -/// Apply the ** scrambler used by some RNGs from the xoshiro family. -macro_rules! starstar_u64 { - ($x:expr) => { - $x.wrapping_mul(5).rotate_left(7).wrapping_mul(9) - } -} - -/// Apply the ** scrambler used by some RNGs from the xoshiro family. -macro_rules! starstar_u32 { - ($x:expr) => { - $x.wrapping_mul(0x9E3779BB).rotate_left(5).wrapping_mul(5) - } -} - -/// Implement a jump function for an RNG from the xoshiro family. -macro_rules! impl_jump { - (u32, $self:expr, [$j0:expr, $j1:expr]) => { - const JUMP: [u32; 2] = [$j0, $j1]; - let mut s0 = 0; - let mut s1 = 0; - for j in &JUMP { - for b in 0..32 { - if (j & 1 << b) != 0 { - s0 ^= $self.s0; - s1 ^= $self.s1; - } - $self.next_u32(); - } - } - $self.s0 = s0; - $self.s1 = s1; - }; - (u64, $self:expr, [$j0:expr, $j1:expr]) => { - const JUMP: [u64; 2] = [$j0, $j1]; - let mut s0 = 0; - let mut s1 = 0; - for j in &JUMP { - for b in 0..64 { - if (j & 1 << b) != 0 { - s0 ^= $self.s0; - s1 ^= $self.s1; - } - $self.next_u64(); - } - } - $self.s0 = s0; - $self.s1 = s1; - }; - (u32, $self:expr, [$j0:expr, $j1:expr, $j2:expr, $j3:expr]) => { - const JUMP: [u32; 4] = [$j0, $j1, $j2, $j3]; - let mut s0 = 0; - let mut s1 = 0; - let mut s2 = 0; - let mut s3 = 0; - for j in &JUMP { - for b in 0..32 { - if (j & 1 << b) != 0 { - s0 ^= $self.s[0]; - s1 ^= $self.s[1]; - s2 ^= $self.s[2]; - s3 ^= $self.s[3]; - } - $self.next_u32(); - } - } - $self.s[0] = s0; - $self.s[1] = s1; - $self.s[2] = s2; - $self.s[3] = s3; - }; - (u64, $self:expr, [$j0:expr, $j1:expr, $j2:expr, $j3:expr]) => { - const JUMP: [u64; 4] = [$j0, $j1, $j2, $j3]; - let mut s0 = 0; - let mut s1 = 0; - let mut s2 = 0; - let mut s3 = 0; - for j in &JUMP { - for b in 0..64 { - if (j & 1 << b) != 0 { - s0 ^= $self.s[0]; - s1 ^= $self.s[1]; - s2 ^= $self.s[2]; - s3 ^= $self.s[3]; - } - $self.next_u64(); - } - } - $self.s[0] = s0; - $self.s[1] = s1; - $self.s[2] = s2; - $self.s[3] = s3; - }; - (u64, $self:expr, [$j0:expr, $j1:expr, $j2:expr, $j3:expr, - $j4:expr, $j5:expr, $j6:expr, $j7:expr]) => { - const JUMP: [u64; 8] = [$j0, $j1, $j2, $j3, $j4, $j5, $j6, $j7]; - let mut s = [0; 8]; - for j in &JUMP { - for b in 0..64 { - if (j & 1 << b) != 0 { - s[0] ^= $self.s[0]; - s[1] ^= $self.s[1]; - s[2] ^= $self.s[2]; - s[3] ^= $self.s[3]; - s[4] ^= $self.s[4]; - s[5] ^= $self.s[5]; - s[6] ^= $self.s[6]; - s[7] ^= $self.s[7]; - } - $self.next_u64(); - } - } - $self.s = s; - }; -} - -/// Implement the xoroshiro iteration. -macro_rules! impl_xoroshiro_u32 { - ($self:expr) => { - $self.s1 ^= $self.s0; - $self.s0 = $self.s0.rotate_left(26) ^ $self.s1 ^ ($self.s1 << 9); - $self.s1 = $self.s1.rotate_left(13); - } -} - -/// Implement the xoroshiro iteration. -macro_rules! impl_xoroshiro_u64 { - ($self:expr) => { - $self.s1 ^= $self.s0; - $self.s0 = $self.s0.rotate_left(24) ^ $self.s1 ^ ($self.s1 << 16); - $self.s1 = $self.s1.rotate_left(37); - } -} - -/// Implement the xoshiro iteration for `u32` output. -macro_rules! impl_xoshiro_u32 { - ($self:expr) => { - let t = $self.s[1] << 9; - - $self.s[2] ^= $self.s[0]; - $self.s[3] ^= $self.s[1]; - $self.s[1] ^= $self.s[2]; - $self.s[0] ^= $self.s[3]; - - $self.s[2] ^= t; - - $self.s[3] = $self.s[3].rotate_left(11); - } -} - -/// Implement the xoshiro iteration for `u64` output. -macro_rules! impl_xoshiro_u64 { - ($self:expr) => { - let t = $self.s[1] << 17; - - $self.s[2] ^= $self.s[0]; - $self.s[3] ^= $self.s[1]; - $self.s[1] ^= $self.s[2]; - $self.s[0] ^= $self.s[3]; - - $self.s[2] ^= t; - - $self.s[3] = $self.s[3].rotate_left(45); - } -} - -/// Implement the large-state xoshiro iteration. -macro_rules! impl_xoshiro_large { - ($self:expr) => { - let t = $self.s[1] << 11; - - $self.s[2] ^= $self.s[0]; - $self.s[5] ^= $self.s[1]; - $self.s[1] ^= $self.s[2]; - $self.s[7] ^= $self.s[3]; - $self.s[3] ^= $self.s[4]; - $self.s[4] ^= $self.s[5]; - $self.s[0] ^= $self.s[6]; - $self.s[6] ^= $self.s[7]; - - $self.s[6] ^= t; - - $self.s[7] = $self.s[7].rotate_left(21); - } -} - -/// Map an all-zero seed to a different one. -macro_rules! deal_with_zero_seed { - ($seed:expr, $Self:ident) => { - if $seed.iter().all(|&x| x == 0) { - return $Self::seed_from_u64(0); - } - } -} - -/// 512-bit seed for a generator. -/// -/// This wrapper is necessary, because some traits required for a seed are not -/// implemented on large arrays. -#[derive(Clone)] -pub struct Seed512(pub [u8; 64]); - -use core; -impl Seed512 { - /// Return an iterator over the seed. - pub fn iter(&self) -> core::slice::Iter { - self.0.iter() - } -} - -impl core::fmt::Debug for Seed512 { - fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { - self.0[..].fmt(f) - } -} - -impl Default for Seed512 { - fn default() -> Seed512 { - Seed512([0; 64]) - } -} - -impl AsMut<[u8]> for Seed512 { - fn as_mut(&mut self) -> &mut [u8] { - &mut self.0 - } -} - diff --git a/rand/rand_xoshiro/src/lib.rs b/rand/rand_xoshiro/src/lib.rs deleted file mode 100644 index 3047e92..0000000 --- a/rand/rand_xoshiro/src/lib.rs +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! This crate implements the [xoshiro] family of pseudorandom number generators -//! designed by David Blackman and Sebastiano Vigna. They feature high -//! perfomance and a small state and superseed the previous xorshift-based -//! generators. However, they are no cryptographically secure and their output -//! can be predicted by observing a few samples. -//! -//! The following generators are implemented: -//! -//! # 64-bit generators -//! - [`Xoshiro256StarStar`]: Recommended for all purposes. Excellent speed and -//! a state space (256 bits) large enough for any parallel application. -//! - [`Xoshiro256Plus`]: Recommended for generating 64-bit floating-point -//! numbers. About 15% faster than `Xoshiro256StarStar`, but has a [low linear -//! complexity] in the lowest bits (which are discarded when generating -//! floats), making it fail linearity tests. This is unlikely to have any -//! impact in practise. -//! - [`Xoroshiro128StarStar`]: An alternative to `Xoshiro256StarStar`, having -//! the same speed but using half the state. Only suited for low-scale parallel -//! applications. -//! - [`Xoroshiro128Plus`]: An alternative to `Xoshiro256Plus`, having the same -//! speed but using half the state. Only suited for low-scale parallel -//! applications. Has a [low linear complexity] in the lowest bits (which are -//! discarded when generating floats), making it fail linearity tests. This is -//! unlikely to have any impact in practise. -//! - [`Xoshiro512StarStar`]: An alternative to `Xoshiro256StarStar` with more -//! state and the same speed. -//! - [`Xoshiro512Plus`]: An alternative to `Xoshiro512Plus` with more -//! state and the same speed. Has a [low linear complexity] in the lowest bits -//! (which are discarded when generating floats), making it fail linearity -//! tests. This is unlikely to have any impact in practise. -//! - [`SplitMix64`]: Recommended for initializing generators of the xoshiro -//! familiy from a 64-bit seed. Used for implementing `seed_from_u64`. -//! -//! # 32-bit generators -//! - [`Xoshiro128StarStar`]: Recommended for all purposes. Excellent speed. -//! - [`Xoshiro128Plus`]: Recommended for generating 32-bit floating-point -//! numbers. Faster than `Xoshiro128StarStar`, but has a [low linear -//! complexity] in the lowest bits (which are discarded when generating -//! floats), making it fail linearity tests. This is unlikely to have any -//! impact in practise. -//! - [`Xoroshiro64StarStar`]: An alternative to `Xoshiro128StarStar`, having -//! the same speed but using half the state. -//! - [`Xoroshiro64Star`]: An alternative to `Xoshiro128Plus`, having the -//! same speed but using half the state. Has a [low linear complexity] in the -//! lowest bits (which are discarded when generating floats), making it fail -//! linearity tests. This is unlikely to have any impact in practise. -//! -//! [xoshiro]: http://xoshiro.di.unimi.it/ -//! [low linear complexity]: http://xoshiro.di.unimi.it/lowcomp.php - -#![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://docs.rs/rand_xoshiro/0.3.1")] - -#![deny(missing_docs)] -#![deny(missing_debug_implementations)] -#![allow(clippy::unreadable_literal)] -#![no_std] - -#[macro_use] -mod common; -mod splitmix64; -mod xoshiro128starstar; -mod xoshiro128plus; -mod xoshiro256starstar; -mod xoshiro256plus; -mod xoshiro512starstar; -mod xoshiro512plus; -mod xoroshiro128plus; -mod xoroshiro128starstar; -mod xoroshiro64starstar; -mod xoroshiro64star; - -pub use rand_core; -pub use splitmix64::SplitMix64; -pub use xoshiro128starstar::Xoshiro128StarStar; -pub use xoshiro128plus::Xoshiro128Plus; -pub use xoshiro256starstar::Xoshiro256StarStar; -pub use xoshiro256plus::Xoshiro256Plus; -pub use common::Seed512; -pub use xoshiro512starstar::Xoshiro512StarStar; -pub use xoshiro512plus::Xoshiro512Plus; -pub use xoroshiro128plus::Xoroshiro128Plus; -pub use xoroshiro128starstar::Xoroshiro128StarStar; -pub use xoroshiro64starstar::Xoroshiro64StarStar; -pub use xoroshiro64star::Xoroshiro64Star; diff --git a/rand/rand_xoshiro/src/splitmix64.rs b/rand/rand_xoshiro/src/splitmix64.rs deleted file mode 100644 index 3a41450..0000000 --- a/rand/rand_xoshiro/src/splitmix64.rs +++ /dev/null @@ -1,149 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#[cfg(feature="serde1")] use serde::{Serialize, Deserialize}; -use rand_core::le::read_u64_into; -use rand_core::impls::fill_bytes_via_next; -use rand_core::{RngCore, SeedableRng, Error}; - -/// A splitmix64 random number generator. -/// -/// The splitmix algorithm is not suitable for cryptographic purposes, but is -/// very fast and has a 64 bit state. -/// -/// The algorithm used here is translated from [the `splitmix64.c` -/// reference source code](http://xoshiro.di.unimi.it/splitmix64.c) by -/// Sebastiano Vigna. For `next_u32`, a more efficient mixing function taken -/// from [`dsiutils`](http://dsiutils.di.unimi.it/) is used. -#[allow(missing_copy_implementations)] -#[derive(Debug, Clone)] -#[cfg_attr(feature="serde1", derive(Serialize, Deserialize))] -pub struct SplitMix64 { - x: u64, -} - -const PHI: u64 = 0x9e3779b97f4a7c15; - -impl RngCore for SplitMix64 { - #[inline] - fn next_u32(&mut self) -> u32 { - self.x = self.x.wrapping_add(PHI); - let mut z = self.x; - // David Stafford's - // (http://zimbry.blogspot.com/2011/09/better-bit-mixing-improving-on.html) - // "Mix4" variant of the 64-bit finalizer in Austin Appleby's - // MurmurHash3 algorithm. - z = (z ^ (z >> 33)).wrapping_mul(0x62A9D9ED799705F5); - z = (z ^ (z >> 28)).wrapping_mul(0xCB24D0A5C88C35B3); - (z >> 32) as u32 - } - - #[inline] - fn next_u64(&mut self) -> u64 { - self.x = self.x.wrapping_add(PHI); - let mut z = self.x; - z = (z ^ (z >> 30)).wrapping_mul(0xbf58476d1ce4e5b9); - z = (z ^ (z >> 27)).wrapping_mul(0x94d049bb133111eb); - z ^ (z >> 31) - } - - #[inline] - fn fill_bytes(&mut self, dest: &mut [u8]) { - fill_bytes_via_next(self, dest); - } - - #[inline] - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - self.fill_bytes(dest); - Ok(()) - } -} - -impl SeedableRng for SplitMix64 { - type Seed = [u8; 8]; - - /// Create a new `SplitMix64`. - fn from_seed(seed: [u8; 8]) -> SplitMix64 { - let mut state = [0; 1]; - read_u64_into(&seed, &mut state); - SplitMix64 { - x: state[0], - } - } - - /// Seed a `SplitMix64` from a `u64`. - fn seed_from_u64(seed: u64) -> SplitMix64 { - SplitMix64::from_seed(seed.to_le_bytes()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn reference() { - let mut rng = SplitMix64::seed_from_u64(1477776061723855037); - // These values were produced with the reference implementation: - // http://xoshiro.di.unimi.it/splitmix64.c - let expected : [u64 ; 50]= [ - 1985237415132408290, 2979275885539914483, 13511426838097143398, - 8488337342461049707, 15141737807933549159, 17093170987380407015, - 16389528042912955399, 13177319091862933652, 10841969400225389492, - 17094824097954834098, 3336622647361835228, 9678412372263018368, - 11111587619974030187, 7882215801036322410, 5709234165213761869, - 7799681907651786826, 4616320717312661886, 4251077652075509767, - 7836757050122171900, 5054003328188417616, 12919285918354108358, - 16477564761813870717, 5124667218451240549, 18099554314556827626, - 7603784838804469118, 6358551455431362471, 3037176434532249502, - 3217550417701719149, 9958699920490216947, 5965803675992506258, - 12000828378049868312, 12720568162811471118, 245696019213873792, - 8351371993958923852, 14378754021282935786, 5655432093647472106, - 5508031680350692005, 8515198786865082103, 6287793597487164412, - 14963046237722101617, 3630795823534910476, 8422285279403485710, - 10554287778700714153, 10871906555720704584, 8659066966120258468, - 9420238805069527062, 10338115333623340156, 13514802760105037173, - 14635952304031724449, 15419692541594102413, - ]; - for &e in expected.iter() { - assert_eq!(rng.next_u64(), e); - } - } - - #[test] - fn next_u32() { - let mut rng = SplitMix64::seed_from_u64(10); - // These values were produced with the reference implementation: - // http://dsiutils.di.unimi.it/dsiutils-2.5.1-src.tar.gz - let expected : [u32 ; 100]= [ - 3930361779, 4016923089, 4113052479, 925926767, 1755287528, - 802865554, 954171070, 3724185978, 173676273, 1414488795, 12664133, - 1784889697, 1303817078, 261610523, 941280008, 2571813643, - 2954453492, 378291111, 2546873158, 3923319175, 645257028, - 3881821278, 2681538690, 3037029984, 1999958137, 1853970361, - 2989951788, 2126166628, 839962987, 3989679659, 3656977858, - 684284364, 1673258011, 170979192, 3037622326, 1600748179, - 1780764218, 1141430714, 4139736875, 3336905707, 2262051600, - 3830850262, 2430765325, 1073032139, 1668888979, 2716938970, - 4102420032, 40305196, 386350562, 2754480591, 622869439, 2129598760, - 2306038241, 4218338739, 412298926, 3453855056, 3061469690, - 4284292697, 994843708, 1591016681, 414726151, 1238182607, 18073498, - 1237631493, 351884714, 2347486264, 2488990876, 802846256, 645670443, - 957607012, 3126589776, 1966356370, 3036485766, 868696717, - 2808613630, 2070968151, 1025536863, 1743949425, 466212687, - 2994327271, 209776458, 1246125124, 3344380309, 2203947859, - 968313105, 2805485302, 197484837, 3472483632, 3931823935, - 3288490351, 4165666529, 3671080416, 689542830, 1272555356, - 1039141475, 3984640460, 4142959054, 2252788890, 2459379590, - 991872507, - ]; - for &e in expected.iter() { - assert_eq!(rng.next_u32(), e); - } - } -} diff --git a/rand/rand_xoshiro/src/xoroshiro128plus.rs b/rand/rand_xoshiro/src/xoroshiro128plus.rs deleted file mode 100644 index a7b4ebc..0000000 --- a/rand/rand_xoshiro/src/xoroshiro128plus.rs +++ /dev/null @@ -1,130 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#[cfg(feature="serde1")] use serde::{Serialize, Deserialize}; -use rand_core; -use rand_core::le::read_u64_into; -use rand_core::impls::fill_bytes_via_next; -use rand_core::{RngCore, SeedableRng}; - -/// A xoroshiro128+ random number generator. -/// -/// The xoroshiro128+ algorithm is not suitable for cryptographic purposes, but -/// is very fast and has good statistical properties, besides a low linear -/// complexity in the lowest bits. -/// -/// The algorithm used here is translated from [the `xoroshiro128plus.c` -/// reference source code](http://xoshiro.di.unimi.it/xoroshiro128plus.c) by -/// David Blackman and Sebastiano Vigna. -#[allow(missing_copy_implementations)] -#[derive(Debug, Clone)] -#[cfg_attr(feature="serde1", derive(Serialize, Deserialize))] -pub struct Xoroshiro128Plus { - s0: u64, - s1: u64, -} - -impl Xoroshiro128Plus { - /// Jump forward, equivalently to 2^64 calls to `next_u64()`. - /// - /// This can be used to generate 2^64 non-overlapping subsequences for - /// parallel computations. - /// - /// ``` - /// use rand_xoshiro::rand_core::SeedableRng; - /// use rand_xoshiro::Xoroshiro128Plus; - /// - /// let rng1 = Xoroshiro128Plus::seed_from_u64(0); - /// let mut rng2 = rng1.clone(); - /// rng2.jump(); - /// let mut rng3 = rng2.clone(); - /// rng3.jump(); - /// ``` - pub fn jump(&mut self) { - impl_jump!(u64, self, [0xdf900294d8f554a5, 0x170865df4b3201fc]); - } - - /// Jump forward, equivalently to 2^96 calls to `next_u64()`. - /// - /// This can be used to generate 2^32 starting points, from each of which - /// `jump()` will generate 2^32 non-overlapping subsequences for parallel - /// distributed computations. - pub fn long_jump(&mut self) { - impl_jump!(u64, self, [0xd2a98b26625eee7b, 0xdddf9b1090aa7ac1]); - } -} - -impl RngCore for Xoroshiro128Plus { - #[inline] - fn next_u32(&mut self) -> u32 { - // The two lowest bits have some linear dependencies, so we use the - // upper bits instead. - (self.next_u64() >> 32) as u32 - } - - #[inline] - fn next_u64(&mut self) -> u64 { - let r = self.s0.wrapping_add(self.s1); - impl_xoroshiro_u64!(self); - r - } - - #[inline] - fn fill_bytes(&mut self, dest: &mut [u8]) { - fill_bytes_via_next(self, dest); - } - - #[inline] - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core::Error> { - self.fill_bytes(dest); - Ok(()) - } -} - -impl SeedableRng for Xoroshiro128Plus { - type Seed = [u8; 16]; - - /// Create a new `Xoroshiro128Plus`. If `seed` is entirely 0, it will be - /// mapped to a different seed. - fn from_seed(seed: [u8; 16]) -> Xoroshiro128Plus { - deal_with_zero_seed!(seed, Self); - let mut s = [0; 2]; - read_u64_into(&seed, &mut s); - - Xoroshiro128Plus { - s0: s[0], - s1: s[1], - } - } - - /// Seed a `Xoroshiro128Plus` from a `u64` using `SplitMix64`. - fn seed_from_u64(seed: u64) -> Xoroshiro128Plus { - from_splitmix!(seed) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn reference() { - let mut rng = Xoroshiro128Plus::from_seed( - [1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0]); - // These values were produced with the reference implementation: - // http://xoshiro.di.unimi.it/xoshiro128starstar.c - let expected = [ - 3, 412333834243, 2360170716294286339, 9295852285959843169, - 2797080929874688578, 6019711933173041966, 3076529664176959358, - 3521761819100106140, 7493067640054542992, 920801338098114767, - ]; - for &e in &expected { - assert_eq!(rng.next_u64(), e); - } - } -} diff --git a/rand/rand_xoshiro/src/xoroshiro128starstar.rs b/rand/rand_xoshiro/src/xoroshiro128starstar.rs deleted file mode 100644 index 21823f5..0000000 --- a/rand/rand_xoshiro/src/xoroshiro128starstar.rs +++ /dev/null @@ -1,127 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#[cfg(feature="serde1")] use serde::{Serialize, Deserialize}; -use rand_core; -use rand_core::le::read_u64_into; -use rand_core::impls::fill_bytes_via_next; -use rand_core::{RngCore, SeedableRng}; - -/// A xoroshiro128** random number generator. -/// -/// The xoroshiro128** algorithm is not suitable for cryptographic purposes, but -/// is very fast and has excellent statistical properties. -/// -/// The algorithm used here is translated from [the `xoroshiro128starstar.c` -/// reference source code](http://xoshiro.di.unimi.it/xoroshiro128starstar.c) by -/// David Blackman and Sebastiano Vigna. -#[allow(missing_copy_implementations)] -#[derive(Debug, Clone)] -#[cfg_attr(feature="serde1", derive(Serialize, Deserialize))] -pub struct Xoroshiro128StarStar { - s0: u64, - s1: u64, -} - -impl Xoroshiro128StarStar { - /// Jump forward, equivalently to 2^64 calls to `next_u64()`. - /// - /// This can be used to generate 2^64 non-overlapping subsequences for - /// parallel computations. - /// - /// ``` - /// use rand_xoshiro::rand_core::SeedableRng; - /// use rand_xoshiro::Xoroshiro128StarStar; - /// - /// let rng1 = Xoroshiro128StarStar::seed_from_u64(0); - /// let mut rng2 = rng1.clone(); - /// rng2.jump(); - /// let mut rng3 = rng2.clone(); - /// rng3.jump(); - /// ``` - pub fn jump(&mut self) { - impl_jump!(u64, self, [0xdf900294d8f554a5, 0x170865df4b3201fc]); - } - - /// Jump forward, equivalently to 2^96 calls to `next_u64()`. - /// - /// This can be used to generate 2^32 starting points, from each of which - /// `jump()` will generate 2^32 non-overlapping subsequences for parallel - /// distributed computations. - pub fn long_jump(&mut self) { - impl_jump!(u64, self, [0xd2a98b26625eee7b, 0xdddf9b1090aa7ac1]); - } -} - -impl RngCore for Xoroshiro128StarStar { - #[inline] - fn next_u32(&mut self) -> u32 { - self.next_u64() as u32 - } - - #[inline] - fn next_u64(&mut self) -> u64 { - let r = starstar_u64!(self.s0); - impl_xoroshiro_u64!(self); - r - } - - #[inline] - fn fill_bytes(&mut self, dest: &mut [u8]) { - fill_bytes_via_next(self, dest); - } - - #[inline] - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core::Error> { - self.fill_bytes(dest); - Ok(()) - } -} - -impl SeedableRng for Xoroshiro128StarStar { - type Seed = [u8; 16]; - - /// Create a new `Xoroshiro128StarStar`. If `seed` is entirely 0, it will be - /// mapped to a different seed. - fn from_seed(seed: [u8; 16]) -> Xoroshiro128StarStar { - deal_with_zero_seed!(seed, Self); - let mut s = [0; 2]; - read_u64_into(&seed, &mut s); - - Xoroshiro128StarStar { - s0: s[0], - s1: s[1], - } - } - - /// Seed a `Xoroshiro128StarStar` from a `u64` using `SplitMix64`. - fn seed_from_u64(seed: u64) -> Xoroshiro128StarStar { - from_splitmix!(seed) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn reference() { - let mut rng = Xoroshiro128StarStar::from_seed( - [1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0]); - // These values were produced with the reference implementation: - // http://xoshiro.di.unimi.it/xoshiro128starstar.c - let expected = [ - 5760, 97769243520, 9706862127477703552, 9223447511460779954, - 8358291023205304566, 15695619998649302768, 8517900938696309774, - 16586480348202605369, 6959129367028440372, 16822147227405758281, - ]; - for &e in &expected { - assert_eq!(rng.next_u64(), e); - } - } -} diff --git a/rand/rand_xoshiro/src/xoroshiro64star.rs b/rand/rand_xoshiro/src/xoroshiro64star.rs deleted file mode 100644 index 6bb708a..0000000 --- a/rand/rand_xoshiro/src/xoroshiro64star.rs +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#[cfg(feature="serde1")] use serde::{Serialize, Deserialize}; -use rand_core; -use rand_core::le::read_u32_into; -use rand_core::impls::{fill_bytes_via_next, next_u64_via_u32}; -use rand_core::{RngCore, SeedableRng}; - -/// A xoroshiro64* random number generator. -/// -/// The xoroshiro64* algorithm is not suitable for cryptographic purposes, but -/// is very fast and has good statistical properties, besides a low linear -/// complexity in the lowest bits. -/// -/// The algorithm used here is translated from [the `xoroshiro64star.c` -/// reference source code](http://xoshiro.di.unimi.it/xoroshiro64star.c) by -/// David Blackman and Sebastiano Vigna. -#[allow(missing_copy_implementations)] -#[derive(Debug, Clone)] -#[cfg_attr(feature="serde1", derive(Serialize, Deserialize))] -pub struct Xoroshiro64Star { - s0: u32, - s1: u32, -} - -impl RngCore for Xoroshiro64Star { - #[inline] - fn next_u32(&mut self) -> u32 { - let r = self.s0.wrapping_mul(0x9E3779BB); - impl_xoroshiro_u32!(self); - r - } - - #[inline] - fn next_u64(&mut self) -> u64 { - next_u64_via_u32(self) - } - - #[inline] - fn fill_bytes(&mut self, dest: &mut [u8]) { - fill_bytes_via_next(self, dest); - } - - #[inline] - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core::Error> { - self.fill_bytes(dest); - Ok(()) - } -} - -impl SeedableRng for Xoroshiro64Star { - type Seed = [u8; 8]; - - /// Create a new `Xoroshiro64Star`. If `seed` is entirely 0, it will be - /// mapped to a different seed. - fn from_seed(seed: [u8; 8]) -> Xoroshiro64Star { - deal_with_zero_seed!(seed, Self); - let mut s = [0; 2]; - read_u32_into(&seed, &mut s); - - Xoroshiro64Star { - s0: s[0], - s1: s[1], - } - } - - /// Seed a `Xoroshiro64Star` from a `u64` using `SplitMix64`. - fn seed_from_u64(seed: u64) -> Xoroshiro64Star { - from_splitmix!(seed) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn reference() { - let mut rng = Xoroshiro64Star::from_seed([1, 0, 0, 0, 2, 0, 0, 0]); - // These values were produced with the reference implementation: - // http://xoshiro.di.unimi.it/xoshiro64star.c - let expected = [ - 2654435771, 327208753, 4063491769, 4259754937, 261922412, 168123673, - 552743735, 1672597395, 1031040050, 2755315674, - ]; - for &e in &expected { - assert_eq!(rng.next_u32(), e); - } - } - - #[test] - fn zero_seed() { - let mut rng = Xoroshiro64Star::seed_from_u64(0); - assert_ne!(rng.next_u64(), 0); - } -} diff --git a/rand/rand_xoshiro/src/xoroshiro64starstar.rs b/rand/rand_xoshiro/src/xoroshiro64starstar.rs deleted file mode 100644 index 8e1aea1..0000000 --- a/rand/rand_xoshiro/src/xoroshiro64starstar.rs +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#[cfg(feature="serde1")] use serde::{Serialize, Deserialize}; -use rand_core; -use rand_core::le::read_u32_into; -use rand_core::impls::{fill_bytes_via_next, next_u64_via_u32}; -use rand_core::{RngCore, SeedableRng}; - -/// A xoroshiro64** random number generator. -/// -/// The xoshiro64** algorithm is not suitable for cryptographic purposes, but -/// is very fast and has excellent statistical properties. -/// -/// The algorithm used here is translated from [the `xoroshiro64starstar.c` -/// reference source code](http://xoshiro.di.unimi.it/xoroshiro64starstar.c) by -/// David Blackman and Sebastiano Vigna. -#[allow(missing_copy_implementations)] -#[derive(Debug, Clone)] -#[cfg_attr(feature="serde1", derive(Serialize, Deserialize))] -pub struct Xoroshiro64StarStar { - s0: u32, - s1: u32, -} - -impl RngCore for Xoroshiro64StarStar { - #[inline] - fn next_u32(&mut self) -> u32 { - let r = starstar_u32!(self.s0); - impl_xoroshiro_u32!(self); - r - } - - #[inline] - fn next_u64(&mut self) -> u64 { - next_u64_via_u32(self) - } - - #[inline] - fn fill_bytes(&mut self, dest: &mut [u8]) { - fill_bytes_via_next(self, dest); - } - - #[inline] - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core::Error> { - self.fill_bytes(dest); - Ok(()) - } -} - -impl SeedableRng for Xoroshiro64StarStar { - type Seed = [u8; 8]; - - /// Create a new `Xoroshiro64StarStar`. If `seed` is entirely 0, it will be - /// mapped to a different seed. - fn from_seed(seed: [u8; 8]) -> Xoroshiro64StarStar { - deal_with_zero_seed!(seed, Self); - let mut s = [0; 2]; - read_u32_into(&seed, &mut s); - - Xoroshiro64StarStar { - s0: s[0], - s1: s[1], - } - } - - /// Seed a `Xoroshiro64StarStar` from a `u64` using `SplitMix64`. - fn seed_from_u64(seed: u64) -> Xoroshiro64StarStar { - from_splitmix!(seed) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn reference() { - let mut rng = Xoroshiro64StarStar::from_seed([1, 0, 0, 0, 2, 0, 0, 0]); - // These values were produced with the reference implementation: - // http://xoshiro.di.unimi.it/xoshiro64starstar.c - let expected = [ - 3802928447, 813792938, 1618621494, 2955957307, 3252880261, - 1129983909, 2539651700, 1327610908, 1757650787, 2763843748, - ]; - for &e in &expected { - assert_eq!(rng.next_u32(), e); - } - } - - #[test] - fn zero_seed() { - let mut rng = Xoroshiro64StarStar::seed_from_u64(0); - assert_ne!(rng.next_u64(), 0); - } -} diff --git a/rand/rand_xoshiro/src/xoshiro128plus.rs b/rand/rand_xoshiro/src/xoshiro128plus.rs deleted file mode 100644 index 7cbd612..0000000 --- a/rand/rand_xoshiro/src/xoshiro128plus.rs +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#[cfg(feature="serde1")] use serde::{Serialize, Deserialize}; -use rand_core::impls::{next_u64_via_u32, fill_bytes_via_next}; -use rand_core::le::read_u32_into; -use rand_core::{SeedableRng, RngCore, Error}; - -/// A xoshiro128+ random number generator. -/// -/// The xoshiro128+ algorithm is not suitable for cryptographic purposes, but -/// is very fast and has good statistical properties, besides a low linear -/// complexity in the lowest bits. -/// -/// The algorithm used here is translated from [the `xoshiro128starstar.c` -/// reference source code](http://xoshiro.di.unimi.it/xoshiro128starstar.c) by -/// David Blackman and Sebastiano Vigna. -#[derive(Debug, Clone)] -#[cfg_attr(feature="serde1", derive(Serialize, Deserialize))] -pub struct Xoshiro128Plus { - s: [u32; 4], -} - -impl Xoshiro128Plus { - /// Jump forward, equivalently to 2^64 calls to `next_u32()`. - /// - /// This can be used to generate 2^64 non-overlapping subsequences for - /// parallel computations. - /// - /// ``` - /// use rand_xoshiro::rand_core::SeedableRng; - /// use rand_xoshiro::Xoroshiro128StarStar; - /// - /// let rng1 = Xoroshiro128StarStar::seed_from_u64(0); - /// let mut rng2 = rng1.clone(); - /// rng2.jump(); - /// let mut rng3 = rng2.clone(); - /// rng3.jump(); - /// ``` - pub fn jump(&mut self) { - impl_jump!(u32, self, [0x8764000b, 0xf542d2d3, 0x6fa035c3, 0x77f2db5b]); - } -} - -impl SeedableRng for Xoshiro128Plus { - type Seed = [u8; 16]; - - /// Create a new `Xoshiro128Plus`. If `seed` is entirely 0, it will be - /// mapped to a different seed. - #[inline] - fn from_seed(seed: [u8; 16]) -> Xoshiro128Plus { - deal_with_zero_seed!(seed, Self); - let mut state = [0; 4]; - read_u32_into(&seed, &mut state); - Xoshiro128Plus { s: state } - } - - /// Seed a `Xoshiro128Plus` from a `u64` using `SplitMix64`. - fn seed_from_u64(seed: u64) -> Xoshiro128Plus { - from_splitmix!(seed) - } -} - -impl RngCore for Xoshiro128Plus { - #[inline] - fn next_u32(&mut self) -> u32 { - let result_plus = self.s[0].wrapping_add(self.s[3]); - impl_xoshiro_u32!(self); - result_plus - } - - #[inline] - fn next_u64(&mut self) -> u64 { - next_u64_via_u32(self) - } - - #[inline] - fn fill_bytes(&mut self, dest: &mut [u8]) { - fill_bytes_via_next(self, dest); - } - - #[inline] - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - self.fill_bytes(dest); - Ok(()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn reference() { - let mut rng = Xoshiro128Plus::from_seed( - [1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0]); - // These values were produced with the reference implementation: - // http://xoshiro.di.unimi.it/xoshiro128plus.c - let expected = [ - 5, 12295, 25178119, 27286542, 39879690, 1140358681, 3276312097, - 4110231701, 399823256, 2144435200, - ]; - for &e in &expected { - assert_eq!(rng.next_u32(), e); - } - } -} diff --git a/rand/rand_xoshiro/src/xoshiro128starstar.rs b/rand/rand_xoshiro/src/xoshiro128starstar.rs deleted file mode 100644 index 7af1e50..0000000 --- a/rand/rand_xoshiro/src/xoshiro128starstar.rs +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#[cfg(feature="serde1")] use serde::{Serialize, Deserialize}; -use rand_core::impls::{next_u64_via_u32, fill_bytes_via_next}; -use rand_core::le::read_u32_into; -use rand_core::{SeedableRng, RngCore, Error}; - -/// A xoshiro128** random number generator. -/// -/// The xoshiro128** algorithm is not suitable for cryptographic purposes, but -/// is very fast and has excellent statistical properties. -/// -/// The algorithm used here is translated from [the `xoshiro128starstar.c` -/// reference source code](http://xoshiro.di.unimi.it/xoshiro128starstar.c) by -/// David Blackman and Sebastiano Vigna. -#[derive(Debug, Clone)] -#[cfg_attr(feature="serde1", derive(Serialize, Deserialize))] -pub struct Xoshiro128StarStar { - s: [u32; 4], -} - -impl Xoshiro128StarStar { - /// Jump forward, equivalently to 2^64 calls to `next_u32()`. - /// - /// This can be used to generate 2^64 non-overlapping subsequences for - /// parallel computations. - /// - /// ``` - /// use rand_xoshiro::rand_core::SeedableRng; - /// use rand_xoshiro::Xoroshiro128StarStar; - /// - /// let rng1 = Xoroshiro128StarStar::seed_from_u64(0); - /// let mut rng2 = rng1.clone(); - /// rng2.jump(); - /// let mut rng3 = rng2.clone(); - /// rng3.jump(); - /// ``` - pub fn jump(&mut self) { - impl_jump!(u32, self, [0x8764000b, 0xf542d2d3, 0x6fa035c3, 0x77f2db5b]); - } -} - -impl SeedableRng for Xoshiro128StarStar { - type Seed = [u8; 16]; - - /// Create a new `Xoshiro128StarStar`. If `seed` is entirely 0, it will be - /// mapped to a different seed. - #[inline] - fn from_seed(seed: [u8; 16]) -> Xoshiro128StarStar { - deal_with_zero_seed!(seed, Self); - let mut state = [0; 4]; - read_u32_into(&seed, &mut state); - Xoshiro128StarStar { s: state } - } - - /// Seed a `Xoshiro128StarStar` from a `u64` using `SplitMix64`. - fn seed_from_u64(seed: u64) -> Xoshiro128StarStar { - from_splitmix!(seed) - } -} - -impl RngCore for Xoshiro128StarStar { - #[inline] - fn next_u32(&mut self) -> u32 { - let result_starstar = starstar_u64!(self.s[0]); - impl_xoshiro_u32!(self); - result_starstar - } - - #[inline] - fn next_u64(&mut self) -> u64 { - next_u64_via_u32(self) - } - - #[inline] - fn fill_bytes(&mut self, dest: &mut [u8]) { - fill_bytes_via_next(self, dest); - } - - #[inline] - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - self.fill_bytes(dest); - Ok(()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn reference() { - let mut rng = Xoshiro128StarStar::from_seed( - [1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0]); - // These values were produced with the reference implementation: - // http://xoshiro.di.unimi.it/xoshiro128starstar.c - let expected = [ - 5760, 40320, 70819200, 3297914139, 2480851620, 1792823698, - 4118739149, 1251203317, 1581886583, 1721184582, - ]; - for &e in &expected { - assert_eq!(rng.next_u32(), e); - } - } -} diff --git a/rand/rand_xoshiro/src/xoshiro256plus.rs b/rand/rand_xoshiro/src/xoshiro256plus.rs deleted file mode 100644 index 396f588..0000000 --- a/rand/rand_xoshiro/src/xoshiro256plus.rs +++ /dev/null @@ -1,131 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#[cfg(feature="serde1")] use serde::{Serialize, Deserialize}; -use rand_core::impls::fill_bytes_via_next; -use rand_core::le::read_u64_into; -use rand_core::{SeedableRng, RngCore, Error}; - -/// A xoshiro256+ random number generator. -/// -/// The xoshiro256+ algorithm is not suitable for cryptographic purposes, but -/// is very fast and has good statistical properties, besides a low linear -/// complexity in the lowest bits. -/// -/// The algorithm used here is translated from [the `xoshiro256plus.c` -/// reference source code](http://xoshiro.di.unimi.it/xoshiro256plus.c) by -/// David Blackman and Sebastiano Vigna. -#[derive(Debug, Clone)] -#[cfg_attr(feature="serde1", derive(Serialize, Deserialize))] -pub struct Xoshiro256Plus { - s: [u64; 4], -} - -impl Xoshiro256Plus { - /// Jump forward, equivalently to 2^128 calls to `next_u64()`. - /// - /// This can be used to generate 2^128 non-overlapping subsequences for - /// parallel computations. - /// - /// ``` - /// use rand_xoshiro::rand_core::SeedableRng; - /// use rand_xoshiro::Xoshiro256Plus; - /// - /// let rng1 = Xoshiro256Plus::seed_from_u64(0); - /// let mut rng2 = rng1.clone(); - /// rng2.jump(); - /// let mut rng3 = rng2.clone(); - /// rng3.jump(); - /// ``` - pub fn jump(&mut self) { - impl_jump!(u64, self, [ - 0x180ec6d33cfd0aba, 0xd5a61266f0c9392c, - 0xa9582618e03fc9aa, 0x39abdc4529b1661c - ]); - } - - /// Jump forward, equivalently to 2^192 calls to `next_u64()`. - /// - /// This can be used to generate 2^64 starting points, from each of which - /// `jump()` will generate 2^64 non-overlapping subsequences for parallel - /// distributed computations. - pub fn long_jump(&mut self) { - impl_jump!(u64, self, [ - 0x76e15d3efefdcbbf, 0xc5004e441c522fb3, - 0x77710069854ee241, 0x39109bb02acbe635 - ]); - } -} - -impl SeedableRng for Xoshiro256Plus { - type Seed = [u8; 32]; - - /// Create a new `Xoshiro256Plus`. If `seed` is entirely 0, it will be - /// mapped to a different seed. - #[inline] - fn from_seed(seed: [u8; 32]) -> Xoshiro256Plus { - deal_with_zero_seed!(seed, Self); - let mut state = [0; 4]; - read_u64_into(&seed, &mut state); - Xoshiro256Plus { s: state } - } - - /// Seed a `Xoshiro256Plus` from a `u64` using `SplitMix64`. - fn seed_from_u64(seed: u64) -> Xoshiro256Plus { - from_splitmix!(seed) - } -} - -impl RngCore for Xoshiro256Plus { - #[inline] - fn next_u32(&mut self) -> u32 { - // The lowest bits have some linear dependencies, so we use the - // upper bits instead. - (self.next_u64() >> 32) as u32 - } - - #[inline] - fn next_u64(&mut self) -> u64 { - let result_plus = self.s[0].wrapping_add(self.s[3]); - impl_xoshiro_u64!(self); - result_plus - } - - #[inline] - fn fill_bytes(&mut self, dest: &mut [u8]) { - fill_bytes_via_next(self, dest); - } - - #[inline] - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - self.fill_bytes(dest); - Ok(()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn reference() { - let mut rng = Xoshiro256Plus::from_seed( - [1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, - 3, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0]); - // These values were produced with the reference implementation: - // http://xoshiro.di.unimi.it/xoshiro256plus.c - let expected = [ - 5, 211106232532999, 211106635186183, 9223759065350669058, - 9250833439874351877, 13862484359527728515, 2346507365006083650, - 1168864526675804870, 34095955243042024, 3466914240207415127, - ]; - for &e in &expected { - assert_eq!(rng.next_u64(), e); - } - } -} diff --git a/rand/rand_xoshiro/src/xoshiro256starstar.rs b/rand/rand_xoshiro/src/xoshiro256starstar.rs deleted file mode 100644 index 2cc2029..0000000 --- a/rand/rand_xoshiro/src/xoshiro256starstar.rs +++ /dev/null @@ -1,128 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#[cfg(feature="serde1")] use serde::{Serialize, Deserialize}; -use rand_core::impls::fill_bytes_via_next; -use rand_core::le::read_u64_into; -use rand_core::{SeedableRng, RngCore, Error}; - -/// A xoshiro256** random number generator. -/// -/// The xoshiro256** algorithm is not suitable for cryptographic purposes, but -/// is very fast and has excellent statistical properties. -/// -/// The algorithm used here is translated from [the `xoshiro256starstar.c` -/// reference source code](http://xoshiro.di.unimi.it/xoshiro256starstar.c) by -/// David Blackman and Sebastiano Vigna. -#[derive(Debug, Clone)] -#[cfg_attr(feature="serde1", derive(Serialize, Deserialize))] -pub struct Xoshiro256StarStar { - s: [u64; 4], -} - -impl Xoshiro256StarStar { - /// Jump forward, equivalently to 2^128 calls to `next_u64()`. - /// - /// This can be used to generate 2^128 non-overlapping subsequences for - /// parallel computations. - /// - /// ``` - /// use rand_xoshiro::rand_core::SeedableRng; - /// use rand_xoshiro::Xoshiro256StarStar; - /// - /// let rng1 = Xoshiro256StarStar::seed_from_u64(0); - /// let mut rng2 = rng1.clone(); - /// rng2.jump(); - /// let mut rng3 = rng2.clone(); - /// rng3.jump(); - /// ``` - pub fn jump(&mut self) { - impl_jump!(u64, self, [ - 0x180ec6d33cfd0aba, 0xd5a61266f0c9392c, - 0xa9582618e03fc9aa, 0x39abdc4529b1661c - ]); - } - - /// Jump forward, equivalently to 2^192 calls to `next_u64()`. - /// - /// This can be used to generate 2^64 starting points, from each of which - /// `jump()` will generate 2^64 non-overlapping subsequences for parallel - /// distributed computations. - pub fn long_jump(&mut self) { - impl_jump!(u64, self, [ - 0x76e15d3efefdcbbf, 0xc5004e441c522fb3, - 0x77710069854ee241, 0x39109bb02acbe635 - ]); - } -} - -impl SeedableRng for Xoshiro256StarStar { - type Seed = [u8; 32]; - - /// Create a new `Xoshiro256StarStar`. If `seed` is entirely 0, it will be - /// mapped to a different seed. - #[inline] - fn from_seed(seed: [u8; 32]) -> Xoshiro256StarStar { - deal_with_zero_seed!(seed, Self); - let mut state = [0; 4]; - read_u64_into(&seed, &mut state); - Xoshiro256StarStar { s: state } - } - - /// Seed a `Xoshiro256StarStar` from a `u64` using `SplitMix64`. - fn seed_from_u64(seed: u64) -> Xoshiro256StarStar { - from_splitmix!(seed) - } -} - -impl RngCore for Xoshiro256StarStar { - #[inline] - fn next_u32(&mut self) -> u32 { - self.next_u64() as u32 - } - - #[inline] - fn next_u64(&mut self) -> u64 { - let result_starstar = starstar_u64!(self.s[1]); - impl_xoshiro_u64!(self); - result_starstar - } - - #[inline] - fn fill_bytes(&mut self, dest: &mut [u8]) { - fill_bytes_via_next(self, dest); - } - - #[inline] - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - self.fill_bytes(dest); - Ok(()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn reference() { - let mut rng = Xoshiro256StarStar::from_seed( - [1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, - 3, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0]); - // These values were produced with the reference implementation: - // http://xoshiro.di.unimi.it/xoshiro128starstar.c - let expected = [ - 11520, 0, 1509978240, 1215971899390074240, 1216172134540287360, - 607988272756665600, 16172922978634559625, 8476171486693032832, - 10595114339597558777, 2904607092377533576, - ]; - for &e in &expected { - assert_eq!(rng.next_u64(), e); - } - } -} diff --git a/rand/rand_xoshiro/src/xoshiro512plus.rs b/rand/rand_xoshiro/src/xoshiro512plus.rs deleted file mode 100644 index 4b589f2..0000000 --- a/rand/rand_xoshiro/src/xoshiro512plus.rs +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#[cfg(feature="serde1")] use serde::{Serialize, Deserialize}; -use rand_core::impls::fill_bytes_via_next; -use rand_core::le::read_u64_into; -use rand_core::{SeedableRng, RngCore, Error}; - -use crate::Seed512; - -/// A xoshiro512+ random number generator. -/// -/// The xoshiro512+ algorithm is not suitable for cryptographic purposes, but -/// is very fast and has good statistical properties, besides a low linear -/// complexity in the lowest bits. -/// -/// The algorithm used here is translated from [the `xoshiro512plus.c` -/// reference source code](http://xoshiro.di.unimi.it/xoshiro512plus.c) by -/// David Blackman and Sebastiano Vigna. -#[derive(Debug, Clone)] -#[cfg_attr(feature="serde1", derive(Serialize, Deserialize))] -pub struct Xoshiro512Plus { - s: [u64; 8], -} - -impl Xoshiro512Plus { - /// Jump forward, equivalently to 2^256 calls to `next_u64()`. - /// - /// This can be used to generate 2^256 non-overlapping subsequences for - /// parallel computations. - /// - /// ``` - /// use rand_xoshiro::rand_core::SeedableRng; - /// use rand_xoshiro::Xoshiro512Plus; - /// - /// let rng1 = Xoshiro512Plus::seed_from_u64(0); - /// let mut rng2 = rng1.clone(); - /// rng2.jump(); - /// let mut rng3 = rng2.clone(); - /// rng3.jump(); - /// ``` - pub fn jump(&mut self) { - impl_jump!(u64, self, [ - 0x33ed89b6e7a353f9, 0x760083d7955323be, 0x2837f2fbb5f22fae, - 0x4b8c5674d309511c, 0xb11ac47a7ba28c25, 0xf1be7667092bcc1c, - 0x53851efdb6df0aaf, 0x1ebbc8b23eaf25db - ]); - } -} - -impl SeedableRng for Xoshiro512Plus { - type Seed = Seed512; - - /// Create a new `Xoshiro512Plus`. If `seed` is entirely 0, it will be - /// mapped to a different seed. - #[inline] - fn from_seed(seed: Seed512) -> Xoshiro512Plus { - deal_with_zero_seed!(seed, Self); - let mut state = [0; 8]; - read_u64_into(&seed.0, &mut state); - Xoshiro512Plus { s: state } - } - - /// Seed a `Xoshiro512Plus` from a `u64` using `SplitMix64`. - fn seed_from_u64(seed: u64) -> Xoshiro512Plus { - from_splitmix!(seed) - } -} - -impl RngCore for Xoshiro512Plus { - #[inline] - fn next_u32(&mut self) -> u32 { - self.next_u64() as u32 - } - - #[inline] - fn next_u64(&mut self) -> u64 { - let result_plus = self.s[0].wrapping_add(self.s[2]); - impl_xoshiro_large!(self); - result_plus - } - - #[inline] - fn fill_bytes(&mut self, dest: &mut [u8]) { - fill_bytes_via_next(self, dest); - } - - #[inline] - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - self.fill_bytes(dest); - Ok(()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn reference() { - let mut rng = Xoshiro512Plus::from_seed(Seed512( - [1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, - 3, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, - 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, - 7, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0])); - // These values were produced with the reference implementation: - // http://xoshiro.di.unimi.it/xoshiro512plus.c - let expected = [ - 4, 8, 4113, 25169936, 52776585412635, 57174648719367, - 9223482039571869716, 9331471677901559830, 9340533895746033672, - 14078399799840753678, - ]; - for &e in &expected { - assert_eq!(rng.next_u64(), e); - } - } -} diff --git a/rand/rand_xoshiro/src/xoshiro512starstar.rs b/rand/rand_xoshiro/src/xoshiro512starstar.rs deleted file mode 100644 index 2db9ac1..0000000 --- a/rand/rand_xoshiro/src/xoshiro512starstar.rs +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#[cfg(feature="serde1")] use serde::{Serialize, Deserialize}; -use rand_core::impls::fill_bytes_via_next; -use rand_core::le::read_u64_into; -use rand_core::{SeedableRng, RngCore, Error}; - -use crate::Seed512; - -/// A xoshiro512** random number generator. -/// -/// The xoshiro512** algorithm is not suitable for cryptographic purposes, but -/// is very fast and has excellent statistical properties. -/// -/// The algorithm used here is translated from [the `xoshiro512starstar.c` -/// reference source code](http://xoshiro.di.unimi.it/xoshiro512starstar.c) by -/// David Blackman and Sebastiano Vigna. -#[derive(Debug, Clone)] -#[cfg_attr(feature="serde1", derive(Serialize, Deserialize))] -pub struct Xoshiro512StarStar { - s: [u64; 8], -} - -impl Xoshiro512StarStar { - /// Jump forward, equivalently to 2^256 calls to `next_u64()`. - /// - /// This can be used to generate 2^256 non-overlapping subsequences for - /// parallel computations. - /// - /// ``` - /// use rand_xoshiro::rand_core::SeedableRng; - /// use rand_xoshiro::Xoshiro512StarStar; - /// - /// let rng1 = Xoshiro512StarStar::seed_from_u64(0); - /// let mut rng2 = rng1.clone(); - /// rng2.jump(); - /// let mut rng3 = rng2.clone(); - /// rng3.jump(); - /// ``` - pub fn jump(&mut self) { - impl_jump!(u64, self, [ - 0x33ed89b6e7a353f9, 0x760083d7955323be, 0x2837f2fbb5f22fae, - 0x4b8c5674d309511c, 0xb11ac47a7ba28c25, 0xf1be7667092bcc1c, - 0x53851efdb6df0aaf, 0x1ebbc8b23eaf25db - ]); - } -} - - -impl SeedableRng for Xoshiro512StarStar { - type Seed = Seed512; - - /// Create a new `Xoshiro512StarStar`. If `seed` is entirely 0, it will be - /// mapped to a different seed. - #[inline] - fn from_seed(seed: Seed512) -> Xoshiro512StarStar { - deal_with_zero_seed!(seed, Self); - let mut state = [0; 8]; - read_u64_into(&seed.0, &mut state); - Xoshiro512StarStar { s: state } - } - - /// Seed a `Xoshiro512StarStar` from a `u64` using `SplitMix64`. - fn seed_from_u64(seed: u64) -> Xoshiro512StarStar { - from_splitmix!(seed) - } -} - -impl RngCore for Xoshiro512StarStar { - #[inline] - fn next_u32(&mut self) -> u32 { - self.next_u64() as u32 - } - - #[inline] - fn next_u64(&mut self) -> u64 { - let result_starstar = starstar_u64!(self.s[1]); - impl_xoshiro_large!(self); - result_starstar - } - - #[inline] - fn fill_bytes(&mut self, dest: &mut [u8]) { - fill_bytes_via_next(self, dest); - } - - #[inline] - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - self.fill_bytes(dest); - Ok(()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn reference() { - let mut rng = Xoshiro512StarStar::from_seed(Seed512( - [1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, - 3, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, - 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, - 7, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0])); - // These values were produced with the reference implementation: - // http://xoshiro.di.unimi.it/xoshiro512starstar.c - let expected = [ - 11520, 0, 23040, 23667840, 144955163520, 303992986974289920, - 25332796375735680, 296904390158016, 13911081092387501979, - 15304787717237593024, - ]; - for &e in &expected { - assert_eq!(rng.next_u64(), e); - } - } -} diff --git a/rand/rand_xoshiro/tests/serde.rs b/rand/rand_xoshiro/tests/serde.rs deleted file mode 100644 index ee23a1d..0000000 --- a/rand/rand_xoshiro/tests/serde.rs +++ /dev/null @@ -1,83 +0,0 @@ -#![cfg(feature="serde1")] - -use rand_core::{RngCore, SeedableRng}; -use rand_xoshiro::{SplitMix64, Xoroshiro64StarStar, Xoroshiro64Star, - Xoroshiro128Plus, Xoroshiro128StarStar, Xoshiro128StarStar, Xoshiro128Plus, - Xoshiro256StarStar, Xoshiro256Plus, Xoshiro512StarStar, Xoshiro512Plus}; - -macro_rules! serde_rng { - ($rng:ident) => { - use bincode; - use std::io::{BufWriter, BufReader}; - - let mut rng = $rng::seed_from_u64(0); - - let buf: Vec = Vec::new(); - let mut buf = BufWriter::new(buf); - bincode::serialize_into(&mut buf, &rng).expect("Could not serialize"); - - let buf = buf.into_inner().unwrap(); - let mut read = BufReader::new(&buf[..]); - let mut deserialized: $rng = bincode::deserialize_from(&mut read) - .expect("Could not deserialize"); - - for _ in 0..16 { - assert_eq!(rng.next_u64(), deserialized.next_u64()); - } - } -} - -#[test] -fn test_splitmix64() { - serde_rng!(SplitMix64); -} - -#[test] -fn test_xoroshiro64starstar() { - serde_rng!(Xoroshiro64StarStar); -} - -#[test] -fn test_xoroshiro64star() { - serde_rng!(Xoroshiro64Star); -} - -#[test] -fn test_xoroshiro128plus() { - serde_rng!(Xoroshiro128Plus); -} - -#[test] -fn test_xoroshiro128starstar() { - serde_rng!(Xoroshiro128StarStar); -} - -#[test] -fn test_xoshiro128starstar() { - serde_rng!(Xoshiro128StarStar); -} - -#[test] -fn test_xoshiro128plus() { - serde_rng!(Xoshiro128Plus); -} - -#[test] -fn test_xoshiro256starstar() { - serde_rng!(Xoshiro256StarStar); -} - -#[test] -fn test_xoshiro256plus() { - serde_rng!(Xoshiro256Plus); -} - -#[test] -fn test_xoshiro512starstar() { - serde_rng!(Xoshiro512StarStar); -} - -#[test] -fn test_xoshiro512plus() { - serde_rng!(Xoshiro512Plus); -} diff --git a/rand/rustfmt.toml b/rand/rustfmt.toml deleted file mode 100644 index 6b2aba3..0000000 --- a/rand/rustfmt.toml +++ /dev/null @@ -1,30 +0,0 @@ -# This rustfmt file is added for configuration, but in practice much of our -# code is hand-formatted, frequently with more readable results. - -# Comments: -normalize_comments = true -wrap_comments = false -format_doc_comments = true -comment_width = 90 # small excess is okay but prefer 80 - -# Arguments: -use_small_heuristics = "max" -fn_args_density = "compressed" -fn_single_line = false -overflow_delimited_expr = true -where_single_line = true - -# enum_discrim_align_threshold = 20 -# struct_field_align_threshold = 20 - -# Compatibility: -edition = "2018" # we require compatibility back to 1.32.0 - -# Misc: -blank_lines_upper_bound = 2 -reorder_impl_items = true -# report_todo = "Unnumbered" -# report_fixme = "Unnumbered" - -# Ignored files: -ignore = [] diff --git a/rand/src/distributions/bernoulli.rs b/rand/src/distributions/bernoulli.rs deleted file mode 100644 index eadd056..0000000 --- a/rand/src/distributions/bernoulli.rs +++ /dev/null @@ -1,166 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The Bernoulli distribution. - -use crate::Rng; -use crate::distributions::Distribution; - -/// The Bernoulli distribution. -/// -/// This is a special case of the Binomial distribution where `n = 1`. -/// -/// # Example -/// -/// ```rust -/// use rand::distributions::{Bernoulli, Distribution}; -/// -/// let d = Bernoulli::new(0.3).unwrap(); -/// let v = d.sample(&mut rand::thread_rng()); -/// println!("{} is from a Bernoulli distribution", v); -/// ``` -/// -/// # Precision -/// -/// This `Bernoulli` distribution uses 64 bits from the RNG (a `u64`), -/// so only probabilities that are multiples of 2-64 can be -/// represented. -#[derive(Clone, Copy, Debug)] -pub struct Bernoulli { - /// Probability of success, relative to the maximal integer. - p_int: u64, -} - -// To sample from the Bernoulli distribution we use a method that compares a -// random `u64` value `v < (p * 2^64)`. -// -// If `p == 1.0`, the integer `v` to compare against can not represented as a -// `u64`. We manually set it to `u64::MAX` instead (2^64 - 1 instead of 2^64). -// Note that value of `p < 1.0` can never result in `u64::MAX`, because an -// `f64` only has 53 bits of precision, and the next largest value of `p` will -// result in `2^64 - 2048`. -// -// Also there is a 100% theoretical concern: if someone consistenly wants to -// generate `true` using the Bernoulli distribution (i.e. by using a probability -// of `1.0`), just using `u64::MAX` is not enough. On average it would return -// false once every 2^64 iterations. Some people apparently care about this -// case. -// -// That is why we special-case `u64::MAX` to always return `true`, without using -// the RNG, and pay the performance price for all uses that *are* reasonable. -// Luckily, if `new()` and `sample` are close, the compiler can optimize out the -// extra check. -const ALWAYS_TRUE: u64 = ::core::u64::MAX; - -// This is just `2.0.powi(64)`, but written this way because it is not available -// in `no_std` mode. -const SCALE: f64 = 2.0 * (1u64 << 63) as f64; - -/// Error type returned from `Bernoulli::new`. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum BernoulliError { - /// `p < 0` or `p > 1`. - InvalidProbability, -} - -impl Bernoulli { - /// Construct a new `Bernoulli` with the given probability of success `p`. - /// - /// # Precision - /// - /// For `p = 1.0`, the resulting distribution will always generate true. - /// For `p = 0.0`, the resulting distribution will always generate false. - /// - /// This method is accurate for any input `p` in the range `[0, 1]` which is - /// a multiple of 2-64. (Note that not all multiples of - /// 2-64 in `[0, 1]` can be represented as a `f64`.) - #[inline] - pub fn new(p: f64) -> Result { - if p < 0.0 || p >= 1.0 { - if p == 1.0 { return Ok(Bernoulli { p_int: ALWAYS_TRUE }) } - return Err(BernoulliError::InvalidProbability); - } - Ok(Bernoulli { p_int: (p * SCALE) as u64 }) - } - - /// Construct a new `Bernoulli` with the probability of success of - /// `numerator`-in-`denominator`. I.e. `new_ratio(2, 3)` will return - /// a `Bernoulli` with a 2-in-3 chance, or about 67%, of returning `true`. - /// - /// If `numerator == denominator` then the returned `Bernoulli` will always - /// return `true`. If `numerator == 0` it will always return `false`. - #[inline] - pub fn from_ratio(numerator: u32, denominator: u32) -> Result { - if numerator > denominator { - return Err(BernoulliError::InvalidProbability); - } - if numerator == denominator { - return Ok(Bernoulli { p_int: ALWAYS_TRUE }) - } - let p_int = ((f64::from(numerator) / f64::from(denominator)) * SCALE) as u64; - Ok(Bernoulli { p_int }) - } -} - -impl Distribution for Bernoulli { - #[inline] - fn sample(&self, rng: &mut R) -> bool { - // Make sure to always return true for p = 1.0. - if self.p_int == ALWAYS_TRUE { return true; } - let v: u64 = rng.gen(); - v < self.p_int - } -} - -#[cfg(test)] -mod test { - use crate::Rng; - use crate::distributions::Distribution; - use super::Bernoulli; - - #[test] - fn test_trivial() { - let mut r = crate::test::rng(1); - let always_false = Bernoulli::new(0.0).unwrap(); - let always_true = Bernoulli::new(1.0).unwrap(); - for _ in 0..5 { - assert_eq!(r.sample::(&always_false), false); - assert_eq!(r.sample::(&always_true), true); - assert_eq!(Distribution::::sample(&always_false, &mut r), false); - assert_eq!(Distribution::::sample(&always_true, &mut r), true); - } - } - - #[test] - #[cfg(not(miri))] // Miri is too slow - fn test_average() { - const P: f64 = 0.3; - const NUM: u32 = 3; - const DENOM: u32 = 10; - let d1 = Bernoulli::new(P).unwrap(); - let d2 = Bernoulli::from_ratio(NUM, DENOM).unwrap(); - const N: u32 = 100_000; - - let mut sum1: u32 = 0; - let mut sum2: u32 = 0; - let mut rng = crate::test::rng(2); - for _ in 0..N { - if d1.sample(&mut rng) { - sum1 += 1; - } - if d2.sample(&mut rng) { - sum2 += 1; - } - } - let avg1 = (sum1 as f64) / (N as f64); - assert!((avg1 - P).abs() < 5e-3); - - let avg2 = (sum2 as f64) / (N as f64); - assert!((avg2 - (NUM as f64)/(DENOM as f64)).abs() < 5e-3); - } -} diff --git a/rand/src/distributions/binomial.rs b/rand/src/distributions/binomial.rs deleted file mode 100644 index 8fc290a..0000000 --- a/rand/src/distributions/binomial.rs +++ /dev/null @@ -1,313 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// Copyright 2016-2017 The Rust Project Developers. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The binomial distribution. -#![allow(deprecated)] -#![allow(clippy::all)] - -use crate::Rng; -use crate::distributions::{Distribution, Uniform}; - -/// The binomial distribution `Binomial(n, p)`. -/// -/// This distribution has density function: -/// `f(k) = n!/(k! (n-k)!) p^k (1-p)^(n-k)` for `k >= 0`. -#[deprecated(since="0.7.0", note="moved to rand_distr crate")] -#[derive(Clone, Copy, Debug)] -pub struct Binomial { - /// Number of trials. - n: u64, - /// Probability of success. - p: f64, -} - -impl Binomial { - /// Construct a new `Binomial` with the given shape parameters `n` (number - /// of trials) and `p` (probability of success). - /// - /// Panics if `p < 0` or `p > 1`. - pub fn new(n: u64, p: f64) -> Binomial { - assert!(p >= 0.0, "Binomial::new called with p < 0"); - assert!(p <= 1.0, "Binomial::new called with p > 1"); - Binomial { n, p } - } -} - -/// Convert a `f64` to an `i64`, panicing on overflow. -// In the future (Rust 1.34), this might be replaced with `TryFrom`. -fn f64_to_i64(x: f64) -> i64 { - assert!(x < (::std::i64::MAX as f64)); - x as i64 -} - -impl Distribution for Binomial { - fn sample(&self, rng: &mut R) -> u64 { - // Handle these values directly. - if self.p == 0.0 { - return 0; - } else if self.p == 1.0 { - return self.n; - } - - // The binomial distribution is symmetrical with respect to p -> 1-p, - // k -> n-k switch p so that it is less than 0.5 - this allows for lower - // expected values we will just invert the result at the end - let p = if self.p <= 0.5 { - self.p - } else { - 1.0 - self.p - }; - - let result; - let q = 1. - p; - - // For small n * min(p, 1 - p), the BINV algorithm based on the inverse - // transformation of the binomial distribution is efficient. Otherwise, - // the BTPE algorithm is used. - // - // Voratas Kachitvichyanukul and Bruce W. Schmeiser. 1988. Binomial - // random variate generation. Commun. ACM 31, 2 (February 1988), - // 216-222. http://dx.doi.org/10.1145/42372.42381 - - // Threshold for prefering the BINV algorithm. The paper suggests 10, - // Ranlib uses 30, and GSL uses 14. - const BINV_THRESHOLD: f64 = 10.; - - if (self.n as f64) * p < BINV_THRESHOLD && - self.n <= (::std::i32::MAX as u64) { - // Use the BINV algorithm. - let s = p / q; - let a = ((self.n + 1) as f64) * s; - let mut r = q.powi(self.n as i32); - let mut u: f64 = rng.gen(); - let mut x = 0; - while u > r as f64 { - u -= r; - x += 1; - r *= a / (x as f64) - s; - } - result = x; - } else { - // Use the BTPE algorithm. - - // Threshold for using the squeeze algorithm. This can be freely - // chosen based on performance. Ranlib and GSL use 20. - const SQUEEZE_THRESHOLD: i64 = 20; - - // Step 0: Calculate constants as functions of `n` and `p`. - let n = self.n as f64; - let np = n * p; - let npq = np * q; - let f_m = np + p; - let m = f64_to_i64(f_m); - // radius of triangle region, since height=1 also area of region - let p1 = (2.195 * npq.sqrt() - 4.6 * q).floor() + 0.5; - // tip of triangle - let x_m = (m as f64) + 0.5; - // left edge of triangle - let x_l = x_m - p1; - // right edge of triangle - let x_r = x_m + p1; - let c = 0.134 + 20.5 / (15.3 + (m as f64)); - // p1 + area of parallelogram region - let p2 = p1 * (1. + 2. * c); - - fn lambda(a: f64) -> f64 { - a * (1. + 0.5 * a) - } - - let lambda_l = lambda((f_m - x_l) / (f_m - x_l * p)); - let lambda_r = lambda((x_r - f_m) / (x_r * q)); - // p1 + area of left tail - let p3 = p2 + c / lambda_l; - // p1 + area of right tail - let p4 = p3 + c / lambda_r; - - // return value - let mut y: i64; - - let gen_u = Uniform::new(0., p4); - let gen_v = Uniform::new(0., 1.); - - loop { - // Step 1: Generate `u` for selecting the region. If region 1 is - // selected, generate a triangularly distributed variate. - let u = gen_u.sample(rng); - let mut v = gen_v.sample(rng); - if !(u > p1) { - y = f64_to_i64(x_m - p1 * v + u); - break; - } - - if !(u > p2) { - // Step 2: Region 2, parallelograms. Check if region 2 is - // used. If so, generate `y`. - let x = x_l + (u - p1) / c; - v = v * c + 1.0 - (x - x_m).abs() / p1; - if v > 1. { - continue; - } else { - y = f64_to_i64(x); - } - } else if !(u > p3) { - // Step 3: Region 3, left exponential tail. - y = f64_to_i64(x_l + v.ln() / lambda_l); - if y < 0 { - continue; - } else { - v *= (u - p2) * lambda_l; - } - } else { - // Step 4: Region 4, right exponential tail. - y = f64_to_i64(x_r - v.ln() / lambda_r); - if y > 0 && (y as u64) > self.n { - continue; - } else { - v *= (u - p3) * lambda_r; - } - } - - // Step 5: Acceptance/rejection comparison. - - // Step 5.0: Test for appropriate method of evaluating f(y). - let k = (y - m).abs(); - if !(k > SQUEEZE_THRESHOLD && (k as f64) < 0.5 * npq - 1.) { - // Step 5.1: Evaluate f(y) via the recursive relationship. Start the - // search from the mode. - let s = p / q; - let a = s * (n + 1.); - let mut f = 1.0; - if m < y { - let mut i = m; - loop { - i += 1; - f *= a / (i as f64) - s; - if i == y { - break; - } - } - } else if m > y { - let mut i = y; - loop { - i += 1; - f /= a / (i as f64) - s; - if i == m { - break; - } - } - } - if v > f { - continue; - } else { - break; - } - } - - // Step 5.2: Squeezing. Check the value of ln(v) againts upper and - // lower bound of ln(f(y)). - let k = k as f64; - let rho = (k / npq) * ((k * (k / 3. + 0.625) + 1./6.) / npq + 0.5); - let t = -0.5 * k*k / npq; - let alpha = v.ln(); - if alpha < t - rho { - break; - } - if alpha > t + rho { - continue; - } - - // Step 5.3: Final acceptance/rejection test. - let x1 = (y + 1) as f64; - let f1 = (m + 1) as f64; - let z = (f64_to_i64(n) + 1 - m) as f64; - let w = (f64_to_i64(n) - y + 1) as f64; - - fn stirling(a: f64) -> f64 { - let a2 = a * a; - (13860. - (462. - (132. - (99. - 140. / a2) / a2) / a2) / a2) / a / 166320. - } - - if alpha > x_m * (f1 / x1).ln() - + (n - (m as f64) + 0.5) * (z / w).ln() - + ((y - m) as f64) * (w * p / (x1 * q)).ln() - // We use the signs from the GSL implementation, which are - // different than the ones in the reference. According to - // the GSL authors, the new signs were verified to be - // correct by one of the original designers of the - // algorithm. - + stirling(f1) + stirling(z) - stirling(x1) - stirling(w) - { - continue; - } - - break; - } - assert!(y >= 0); - result = y as u64; - } - - // Invert the result for p < 0.5. - if p != self.p { - self.n - result - } else { - result - } - } -} - -#[cfg(test)] -mod test { - use crate::Rng; - use crate::distributions::Distribution; - use super::Binomial; - - fn test_binomial_mean_and_variance(n: u64, p: f64, rng: &mut R) { - let binomial = Binomial::new(n, p); - - let expected_mean = n as f64 * p; - let expected_variance = n as f64 * p * (1.0 - p); - - let mut results = [0.0; 1000]; - for i in results.iter_mut() { *i = binomial.sample(rng) as f64; } - - let mean = results.iter().sum::() / results.len() as f64; - assert!((mean as f64 - expected_mean).abs() < expected_mean / 50.0, - "mean: {}, expected_mean: {}", mean, expected_mean); - - let variance = - results.iter().map(|x| (x - mean) * (x - mean)).sum::() - / results.len() as f64; - assert!((variance - expected_variance).abs() < expected_variance / 10.0, - "variance: {}, expected_variance: {}", variance, expected_variance); - } - - #[test] - #[cfg(not(miri))] // Miri is too slow - fn test_binomial() { - let mut rng = crate::test::rng(351); - test_binomial_mean_and_variance(150, 0.1, &mut rng); - test_binomial_mean_and_variance(70, 0.6, &mut rng); - test_binomial_mean_and_variance(40, 0.5, &mut rng); - test_binomial_mean_and_variance(20, 0.7, &mut rng); - test_binomial_mean_and_variance(20, 0.5, &mut rng); - } - - #[test] - fn test_binomial_end_points() { - let mut rng = crate::test::rng(352); - assert_eq!(rng.sample(Binomial::new(20, 0.0)), 0); - assert_eq!(rng.sample(Binomial::new(20, 1.0)), 20); - } - - #[test] - #[should_panic] - fn test_binomial_invalid_lambda_neg() { - Binomial::new(20, -10.0); - } -} diff --git a/rand/src/distributions/cauchy.rs b/rand/src/distributions/cauchy.rs deleted file mode 100644 index 0a5d149..0000000 --- a/rand/src/distributions/cauchy.rs +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// Copyright 2016-2017 The Rust Project Developers. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The Cauchy distribution. -#![allow(deprecated)] -#![allow(clippy::all)] - -use crate::Rng; -use crate::distributions::Distribution; -use std::f64::consts::PI; - -/// The Cauchy distribution `Cauchy(median, scale)`. -/// -/// This distribution has a density function: -/// `f(x) = 1 / (pi * scale * (1 + ((x - median) / scale)^2))` -#[deprecated(since="0.7.0", note="moved to rand_distr crate")] -#[derive(Clone, Copy, Debug)] -pub struct Cauchy { - median: f64, - scale: f64 -} - -impl Cauchy { - /// Construct a new `Cauchy` with the given shape parameters - /// `median` the peak location and `scale` the scale factor. - /// Panics if `scale <= 0`. - pub fn new(median: f64, scale: f64) -> Cauchy { - assert!(scale > 0.0, "Cauchy::new called with scale factor <= 0"); - Cauchy { - median, - scale - } - } -} - -impl Distribution for Cauchy { - fn sample(&self, rng: &mut R) -> f64 { - // sample from [0, 1) - let x = rng.gen::(); - // get standard cauchy random number - // note that Ο€/2 is not exactly representable, even if x=0.5 the result is finite - let comp_dev = (PI * x).tan(); - // shift and scale according to parameters - let result = self.median + self.scale * comp_dev; - result - } -} - -#[cfg(test)] -mod test { - use crate::distributions::Distribution; - use super::Cauchy; - - fn median(mut numbers: &mut [f64]) -> f64 { - sort(&mut numbers); - let mid = numbers.len() / 2; - numbers[mid] - } - - fn sort(numbers: &mut [f64]) { - numbers.sort_by(|a, b| a.partial_cmp(b).unwrap()); - } - - #[test] - #[cfg(not(miri))] // Miri doesn't support transcendental functions - fn test_cauchy_averages() { - // NOTE: given that the variance and mean are undefined, - // this test does not have any rigorous statistical meaning. - let cauchy = Cauchy::new(10.0, 5.0); - let mut rng = crate::test::rng(123); - let mut numbers: [f64; 1000] = [0.0; 1000]; - let mut sum = 0.0; - for i in 0..1000 { - numbers[i] = cauchy.sample(&mut rng); - sum += numbers[i]; - } - let median = median(&mut numbers); - println!("Cauchy median: {}", median); - assert!((median - 10.0).abs() < 0.4); // not 100% certain, but probable enough - let mean = sum / 1000.0; - println!("Cauchy mean: {}", mean); - // for a Cauchy distribution the mean should not converge - assert!((mean - 10.0).abs() > 0.4); // not 100% certain, but probable enough - } - - #[test] - #[should_panic] - fn test_cauchy_invalid_scale_zero() { - Cauchy::new(0.0, 0.0); - } - - #[test] - #[should_panic] - fn test_cauchy_invalid_scale_neg() { - Cauchy::new(0.0, -10.0); - } -} diff --git a/rand/src/distributions/dirichlet.rs b/rand/src/distributions/dirichlet.rs deleted file mode 100644 index 1ce01fd..0000000 --- a/rand/src/distributions/dirichlet.rs +++ /dev/null @@ -1,128 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// Copyright 2013 The Rust Project Developers. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The dirichlet distribution. -#![allow(deprecated)] -#![allow(clippy::all)] - -use crate::Rng; -use crate::distributions::Distribution; -use crate::distributions::gamma::Gamma; - -/// The dirichelet distribution `Dirichlet(alpha)`. -/// -/// The Dirichlet distribution is a family of continuous multivariate -/// probability distributions parameterized by a vector alpha of positive reals. -/// It is a multivariate generalization of the beta distribution. -#[deprecated(since="0.7.0", note="moved to rand_distr crate")] -#[derive(Clone, Debug)] -pub struct Dirichlet { - /// Concentration parameters (alpha) - alpha: Vec, -} - -impl Dirichlet { - /// Construct a new `Dirichlet` with the given alpha parameter `alpha`. - /// - /// # Panics - /// - if `alpha.len() < 2` - /// - #[inline] - pub fn new>>(alpha: V) -> Dirichlet { - let a = alpha.into(); - assert!(a.len() > 1); - for i in 0..a.len() { - assert!(a[i] > 0.0); - } - - Dirichlet { alpha: a } - } - - /// Construct a new `Dirichlet` with the given shape parameter `alpha` and `size`. - /// - /// # Panics - /// - if `alpha <= 0.0` - /// - if `size < 2` - /// - #[inline] - pub fn new_with_param(alpha: f64, size: usize) -> Dirichlet { - assert!(alpha > 0.0); - assert!(size > 1); - Dirichlet { - alpha: vec![alpha; size], - } - } -} - -impl Distribution> for Dirichlet { - fn sample(&self, rng: &mut R) -> Vec { - let n = self.alpha.len(); - let mut samples = vec![0.0f64; n]; - let mut sum = 0.0f64; - - for i in 0..n { - let g = Gamma::new(self.alpha[i], 1.0); - samples[i] = g.sample(rng); - sum += samples[i]; - } - let invacc = 1.0 / sum; - for i in 0..n { - samples[i] *= invacc; - } - samples - } -} - -#[cfg(test)] -mod test { - use super::Dirichlet; - use crate::distributions::Distribution; - - #[test] - fn test_dirichlet() { - let d = Dirichlet::new(vec![1.0, 2.0, 3.0]); - let mut rng = crate::test::rng(221); - let samples = d.sample(&mut rng); - let _: Vec = samples - .into_iter() - .map(|x| { - assert!(x > 0.0); - x - }) - .collect(); - } - - #[test] - fn test_dirichlet_with_param() { - let alpha = 0.5f64; - let size = 2; - let d = Dirichlet::new_with_param(alpha, size); - let mut rng = crate::test::rng(221); - let samples = d.sample(&mut rng); - let _: Vec = samples - .into_iter() - .map(|x| { - assert!(x > 0.0); - x - }) - .collect(); - } - - #[test] - #[should_panic] - fn test_dirichlet_invalid_length() { - Dirichlet::new_with_param(0.5f64, 1); - } - - #[test] - #[should_panic] - fn test_dirichlet_invalid_alpha() { - Dirichlet::new_with_param(0.0f64, 2); - } -} diff --git a/rand/src/distributions/exponential.rs b/rand/src/distributions/exponential.rs deleted file mode 100644 index 0278248..0000000 --- a/rand/src/distributions/exponential.rs +++ /dev/null @@ -1,108 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// Copyright 2013 The Rust Project Developers. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The exponential distribution. -#![allow(deprecated)] - -use crate::{Rng}; -use crate::distributions::{ziggurat_tables, Distribution}; -use crate::distributions::utils::ziggurat; - -/// Samples floating-point numbers according to the exponential distribution, -/// with rate parameter `Ξ» = 1`. This is equivalent to `Exp::new(1.0)` or -/// sampling with `-rng.gen::().ln()`, but faster. -/// -/// See `Exp` for the general exponential distribution. -/// -/// Implemented via the ZIGNOR variant[^1] of the Ziggurat method. The exact -/// description in the paper was adjusted to use tables for the exponential -/// distribution rather than normal. -/// -/// [^1]: Jurgen A. Doornik (2005). [*An Improved Ziggurat Method to -/// Generate Normal Random Samples*]( -/// https://www.doornik.com/research/ziggurat.pdf). -/// Nuffield College, Oxford -#[deprecated(since="0.7.0", note="moved to rand_distr crate")] -#[derive(Clone, Copy, Debug)] -pub struct Exp1; - -// This could be done via `-rng.gen::().ln()` but that is slower. -impl Distribution for Exp1 { - #[inline] - fn sample(&self, rng: &mut R) -> f64 { - #[inline] - fn pdf(x: f64) -> f64 { - (-x).exp() - } - #[inline] - fn zero_case(rng: &mut R, _u: f64) -> f64 { - ziggurat_tables::ZIG_EXP_R - rng.gen::().ln() - } - - ziggurat(rng, false, - &ziggurat_tables::ZIG_EXP_X, - &ziggurat_tables::ZIG_EXP_F, - pdf, zero_case) - } -} - -/// The exponential distribution `Exp(lambda)`. -/// -/// This distribution has density function: `f(x) = lambda * exp(-lambda * x)` -/// for `x > 0`. -/// -/// Note that [`Exp1`](crate::distributions::Exp1) is an optimised implementation for `lambda = 1`. -#[deprecated(since="0.7.0", note="moved to rand_distr crate")] -#[derive(Clone, Copy, Debug)] -pub struct Exp { - /// `lambda` stored as `1/lambda`, since this is what we scale by. - lambda_inverse: f64 -} - -impl Exp { - /// Construct a new `Exp` with the given shape parameter - /// `lambda`. Panics if `lambda <= 0`. - #[inline] - pub fn new(lambda: f64) -> Exp { - assert!(lambda > 0.0, "Exp::new called with `lambda` <= 0"); - Exp { lambda_inverse: 1.0 / lambda } - } -} - -impl Distribution for Exp { - fn sample(&self, rng: &mut R) -> f64 { - let n: f64 = rng.sample(Exp1); - n * self.lambda_inverse - } -} - -#[cfg(test)] -mod test { - use crate::distributions::Distribution; - use super::Exp; - - #[test] - fn test_exp() { - let exp = Exp::new(10.0); - let mut rng = crate::test::rng(221); - for _ in 0..1000 { - assert!(exp.sample(&mut rng) >= 0.0); - } - } - #[test] - #[should_panic] - fn test_exp_invalid_lambda_zero() { - Exp::new(0.0); - } - #[test] - #[should_panic] - fn test_exp_invalid_lambda_neg() { - Exp::new(-10.0); - } -} diff --git a/rand/src/distributions/float.rs b/rand/src/distributions/float.rs deleted file mode 100644 index bda523a..0000000 --- a/rand/src/distributions/float.rs +++ /dev/null @@ -1,259 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Basic floating-point number distributions - -use core::mem; -use crate::Rng; -use crate::distributions::{Distribution, Standard}; -use crate::distributions::utils::FloatSIMDUtils; -#[cfg(feature="simd_support")] -use packed_simd::*; - -/// A distribution to sample floating point numbers uniformly in the half-open -/// interval `(0, 1]`, i.e. including 1 but not 0. -/// -/// All values that can be generated are of the form `n * Ξ΅/2`. For `f32` -/// the 23 most significant random bits of a `u32` are used and for `f64` the -/// 53 most significant bits of a `u64` are used. The conversion uses the -/// multiplicative method. -/// -/// See also: [`Standard`] which samples from `[0, 1)`, [`Open01`] -/// which samples from `(0, 1)` and [`Uniform`] which samples from arbitrary -/// ranges. -/// -/// # Example -/// ``` -/// use rand::{thread_rng, Rng}; -/// use rand::distributions::OpenClosed01; -/// -/// let val: f32 = thread_rng().sample(OpenClosed01); -/// println!("f32 from (0, 1): {}", val); -/// ``` -/// -/// [`Standard`]: crate::distributions::Standard -/// [`Open01`]: crate::distributions::Open01 -/// [`Uniform`]: crate::distributions::uniform::Uniform -#[derive(Clone, Copy, Debug)] -pub struct OpenClosed01; - -/// A distribution to sample floating point numbers uniformly in the open -/// interval `(0, 1)`, i.e. not including either endpoint. -/// -/// All values that can be generated are of the form `n * Ξ΅ + Ξ΅/2`. For `f32` -/// the 22 most significant random bits of an `u32` are used, for `f64` 52 from -/// an `u64`. The conversion uses a transmute-based method. -/// -/// See also: [`Standard`] which samples from `[0, 1)`, [`OpenClosed01`] -/// which samples from `(0, 1]` and [`Uniform`] which samples from arbitrary -/// ranges. -/// -/// # Example -/// ``` -/// use rand::{thread_rng, Rng}; -/// use rand::distributions::Open01; -/// -/// let val: f32 = thread_rng().sample(Open01); -/// println!("f32 from (0, 1): {}", val); -/// ``` -/// -/// [`Standard`]: crate::distributions::Standard -/// [`OpenClosed01`]: crate::distributions::OpenClosed01 -/// [`Uniform`]: crate::distributions::uniform::Uniform -#[derive(Clone, Copy, Debug)] -pub struct Open01; - - -// This trait is needed by both this lib and rand_distr hence is a hidden export -#[doc(hidden)] -pub trait IntoFloat { - type F; - - /// Helper method to combine the fraction and a contant exponent into a - /// float. - /// - /// Only the least significant bits of `self` may be set, 23 for `f32` and - /// 52 for `f64`. - /// The resulting value will fall in a range that depends on the exponent. - /// As an example the range with exponent 0 will be - /// [20..21), which is [1..2). - fn into_float_with_exponent(self, exponent: i32) -> Self::F; -} - -macro_rules! float_impls { - ($ty:ident, $uty:ident, $f_scalar:ident, $u_scalar:ty, - $fraction_bits:expr, $exponent_bias:expr) => { - impl IntoFloat for $uty { - type F = $ty; - #[inline(always)] - fn into_float_with_exponent(self, exponent: i32) -> $ty { - // The exponent is encoded using an offset-binary representation - let exponent_bits: $u_scalar = - (($exponent_bias + exponent) as $u_scalar) << $fraction_bits; - $ty::from_bits(self | exponent_bits) - } - } - - impl Distribution<$ty> for Standard { - fn sample(&self, rng: &mut R) -> $ty { - // Multiply-based method; 24/53 random bits; [0, 1) interval. - // We use the most significant bits because for simple RNGs - // those are usually more random. - let float_size = mem::size_of::<$f_scalar>() as u32 * 8; - let precision = $fraction_bits + 1; - let scale = 1.0 / ((1 as $u_scalar << precision) as $f_scalar); - - let value: $uty = rng.gen(); - let value = value >> (float_size - precision); - scale * $ty::cast_from_int(value) - } - } - - impl Distribution<$ty> for OpenClosed01 { - fn sample(&self, rng: &mut R) -> $ty { - // Multiply-based method; 24/53 random bits; (0, 1] interval. - // We use the most significant bits because for simple RNGs - // those are usually more random. - let float_size = mem::size_of::<$f_scalar>() as u32 * 8; - let precision = $fraction_bits + 1; - let scale = 1.0 / ((1 as $u_scalar << precision) as $f_scalar); - - let value: $uty = rng.gen(); - let value = value >> (float_size - precision); - // Add 1 to shift up; will not overflow because of right-shift: - scale * $ty::cast_from_int(value + 1) - } - } - - impl Distribution<$ty> for Open01 { - fn sample(&self, rng: &mut R) -> $ty { - // Transmute-based method; 23/52 random bits; (0, 1) interval. - // We use the most significant bits because for simple RNGs - // those are usually more random. - use core::$f_scalar::EPSILON; - let float_size = mem::size_of::<$f_scalar>() as u32 * 8; - - let value: $uty = rng.gen(); - let fraction = value >> (float_size - $fraction_bits); - fraction.into_float_with_exponent(0) - (1.0 - EPSILON / 2.0) - } - } - } -} - -float_impls! { f32, u32, f32, u32, 23, 127 } -float_impls! { f64, u64, f64, u64, 52, 1023 } - -#[cfg(feature="simd_support")] -float_impls! { f32x2, u32x2, f32, u32, 23, 127 } -#[cfg(feature="simd_support")] -float_impls! { f32x4, u32x4, f32, u32, 23, 127 } -#[cfg(feature="simd_support")] -float_impls! { f32x8, u32x8, f32, u32, 23, 127 } -#[cfg(feature="simd_support")] -float_impls! { f32x16, u32x16, f32, u32, 23, 127 } - -#[cfg(feature="simd_support")] -float_impls! { f64x2, u64x2, f64, u64, 52, 1023 } -#[cfg(feature="simd_support")] -float_impls! { f64x4, u64x4, f64, u64, 52, 1023 } -#[cfg(feature="simd_support")] -float_impls! { f64x8, u64x8, f64, u64, 52, 1023 } - - -#[cfg(test)] -mod tests { - use crate::Rng; - use crate::distributions::{Open01, OpenClosed01}; - use crate::rngs::mock::StepRng; - #[cfg(feature="simd_support")] - use packed_simd::*; - - const EPSILON32: f32 = ::core::f32::EPSILON; - const EPSILON64: f64 = ::core::f64::EPSILON; - - macro_rules! test_f32 { - ($fnn:ident, $ty:ident, $ZERO:expr, $EPSILON:expr) => { - #[test] - fn $fnn() { - // Standard - let mut zeros = StepRng::new(0, 0); - assert_eq!(zeros.gen::<$ty>(), $ZERO); - let mut one = StepRng::new(1 << 8 | 1 << (8 + 32), 0); - assert_eq!(one.gen::<$ty>(), $EPSILON / 2.0); - let mut max = StepRng::new(!0, 0); - assert_eq!(max.gen::<$ty>(), 1.0 - $EPSILON / 2.0); - - // OpenClosed01 - let mut zeros = StepRng::new(0, 0); - assert_eq!(zeros.sample::<$ty, _>(OpenClosed01), - 0.0 + $EPSILON / 2.0); - let mut one = StepRng::new(1 << 8 | 1 << (8 + 32), 0); - assert_eq!(one.sample::<$ty, _>(OpenClosed01), $EPSILON); - let mut max = StepRng::new(!0, 0); - assert_eq!(max.sample::<$ty, _>(OpenClosed01), $ZERO + 1.0); - - // Open01 - let mut zeros = StepRng::new(0, 0); - assert_eq!(zeros.sample::<$ty, _>(Open01), 0.0 + $EPSILON / 2.0); - let mut one = StepRng::new(1 << 9 | 1 << (9 + 32), 0); - assert_eq!(one.sample::<$ty, _>(Open01), $EPSILON / 2.0 * 3.0); - let mut max = StepRng::new(!0, 0); - assert_eq!(max.sample::<$ty, _>(Open01), 1.0 - $EPSILON / 2.0); - } - } - } - test_f32! { f32_edge_cases, f32, 0.0, EPSILON32 } - #[cfg(feature="simd_support")] - test_f32! { f32x2_edge_cases, f32x2, f32x2::splat(0.0), f32x2::splat(EPSILON32) } - #[cfg(feature="simd_support")] - test_f32! { f32x4_edge_cases, f32x4, f32x4::splat(0.0), f32x4::splat(EPSILON32) } - #[cfg(feature="simd_support")] - test_f32! { f32x8_edge_cases, f32x8, f32x8::splat(0.0), f32x8::splat(EPSILON32) } - #[cfg(feature="simd_support")] - test_f32! { f32x16_edge_cases, f32x16, f32x16::splat(0.0), f32x16::splat(EPSILON32) } - - macro_rules! test_f64 { - ($fnn:ident, $ty:ident, $ZERO:expr, $EPSILON:expr) => { - #[test] - fn $fnn() { - // Standard - let mut zeros = StepRng::new(0, 0); - assert_eq!(zeros.gen::<$ty>(), $ZERO); - let mut one = StepRng::new(1 << 11, 0); - assert_eq!(one.gen::<$ty>(), $EPSILON / 2.0); - let mut max = StepRng::new(!0, 0); - assert_eq!(max.gen::<$ty>(), 1.0 - $EPSILON / 2.0); - - // OpenClosed01 - let mut zeros = StepRng::new(0, 0); - assert_eq!(zeros.sample::<$ty, _>(OpenClosed01), - 0.0 + $EPSILON / 2.0); - let mut one = StepRng::new(1 << 11, 0); - assert_eq!(one.sample::<$ty, _>(OpenClosed01), $EPSILON); - let mut max = StepRng::new(!0, 0); - assert_eq!(max.sample::<$ty, _>(OpenClosed01), $ZERO + 1.0); - - // Open01 - let mut zeros = StepRng::new(0, 0); - assert_eq!(zeros.sample::<$ty, _>(Open01), 0.0 + $EPSILON / 2.0); - let mut one = StepRng::new(1 << 12, 0); - assert_eq!(one.sample::<$ty, _>(Open01), $EPSILON / 2.0 * 3.0); - let mut max = StepRng::new(!0, 0); - assert_eq!(max.sample::<$ty, _>(Open01), 1.0 - $EPSILON / 2.0); - } - } - } - test_f64! { f64_edge_cases, f64, 0.0, EPSILON64 } - #[cfg(feature="simd_support")] - test_f64! { f64x2_edge_cases, f64x2, f64x2::splat(0.0), f64x2::splat(EPSILON64) } - #[cfg(feature="simd_support")] - test_f64! { f64x4_edge_cases, f64x4, f64x4::splat(0.0), f64x4::splat(EPSILON64) } - #[cfg(feature="simd_support")] - test_f64! { f64x8_edge_cases, f64x8, f64x8::splat(0.0), f64x8::splat(EPSILON64) } -} diff --git a/rand/src/distributions/gamma.rs b/rand/src/distributions/gamma.rs deleted file mode 100644 index b5a97f5..0000000 --- a/rand/src/distributions/gamma.rs +++ /dev/null @@ -1,371 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// Copyright 2013 The Rust Project Developers. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The Gamma and derived distributions. -#![allow(deprecated)] - -use self::GammaRepr::*; -use self::ChiSquaredRepr::*; - -use crate::Rng; -use crate::distributions::normal::StandardNormal; -use crate::distributions::{Distribution, Exp, Open01}; - -/// The Gamma distribution `Gamma(shape, scale)` distribution. -/// -/// The density function of this distribution is -/// -/// ```text -/// f(x) = x^(k - 1) * exp(-x / ΞΈ) / (Ξ“(k) * ΞΈ^k) -/// ``` -/// -/// where `Ξ“` is the Gamma function, `k` is the shape and `ΞΈ` is the -/// scale and both `k` and `ΞΈ` are strictly positive. -/// -/// The algorithm used is that described by Marsaglia & Tsang 2000[^1], -/// falling back to directly sampling from an Exponential for `shape -/// == 1`, and using the boosting technique described in that paper for -/// `shape < 1`. -/// -/// [^1]: George Marsaglia and Wai Wan Tsang. 2000. "A Simple Method for -/// Generating Gamma Variables" *ACM Trans. Math. Softw.* 26, 3 -/// (September 2000), 363-372. -/// DOI:[10.1145/358407.358414](https://doi.acm.org/10.1145/358407.358414) -#[deprecated(since="0.7.0", note="moved to rand_distr crate")] -#[derive(Clone, Copy, Debug)] -pub struct Gamma { - repr: GammaRepr, -} - -#[derive(Clone, Copy, Debug)] -enum GammaRepr { - Large(GammaLargeShape), - One(Exp), - Small(GammaSmallShape) -} - -// These two helpers could be made public, but saving the -// match-on-Gamma-enum branch from using them directly (e.g. if one -// knows that the shape is always > 1) doesn't appear to be much -// faster. - -/// Gamma distribution where the shape parameter is less than 1. -/// -/// Note, samples from this require a compulsory floating-point `pow` -/// call, which makes it significantly slower than sampling from a -/// gamma distribution where the shape parameter is greater than or -/// equal to 1. -/// -/// See `Gamma` for sampling from a Gamma distribution with general -/// shape parameters. -#[derive(Clone, Copy, Debug)] -struct GammaSmallShape { - inv_shape: f64, - large_shape: GammaLargeShape -} - -/// Gamma distribution where the shape parameter is larger than 1. -/// -/// See `Gamma` for sampling from a Gamma distribution with general -/// shape parameters. -#[derive(Clone, Copy, Debug)] -struct GammaLargeShape { - scale: f64, - c: f64, - d: f64 -} - -impl Gamma { - /// Construct an object representing the `Gamma(shape, scale)` - /// distribution. - /// - /// Panics if `shape <= 0` or `scale <= 0`. - #[inline] - pub fn new(shape: f64, scale: f64) -> Gamma { - assert!(shape > 0.0, "Gamma::new called with shape <= 0"); - assert!(scale > 0.0, "Gamma::new called with scale <= 0"); - - let repr = if shape == 1.0 { - One(Exp::new(1.0 / scale)) - } else if shape < 1.0 { - Small(GammaSmallShape::new_raw(shape, scale)) - } else { - Large(GammaLargeShape::new_raw(shape, scale)) - }; - Gamma { repr } - } -} - -impl GammaSmallShape { - fn new_raw(shape: f64, scale: f64) -> GammaSmallShape { - GammaSmallShape { - inv_shape: 1. / shape, - large_shape: GammaLargeShape::new_raw(shape + 1.0, scale) - } - } -} - -impl GammaLargeShape { - fn new_raw(shape: f64, scale: f64) -> GammaLargeShape { - let d = shape - 1. / 3.; - GammaLargeShape { - scale, - c: 1. / (9. * d).sqrt(), - d - } - } -} - -impl Distribution for Gamma { - fn sample(&self, rng: &mut R) -> f64 { - match self.repr { - Small(ref g) => g.sample(rng), - One(ref g) => g.sample(rng), - Large(ref g) => g.sample(rng), - } - } -} -impl Distribution for GammaSmallShape { - fn sample(&self, rng: &mut R) -> f64 { - let u: f64 = rng.sample(Open01); - - self.large_shape.sample(rng) * u.powf(self.inv_shape) - } -} -impl Distribution for GammaLargeShape { - fn sample(&self, rng: &mut R) -> f64 { - loop { - let x = rng.sample(StandardNormal); - let v_cbrt = 1.0 + self.c * x; - if v_cbrt <= 0.0 { // a^3 <= 0 iff a <= 0 - continue - } - - let v = v_cbrt * v_cbrt * v_cbrt; - let u: f64 = rng.sample(Open01); - - let x_sqr = x * x; - if u < 1.0 - 0.0331 * x_sqr * x_sqr || - u.ln() < 0.5 * x_sqr + self.d * (1.0 - v + v.ln()) { - return self.d * v * self.scale - } - } - } -} - -/// The chi-squared distribution `χ²(k)`, where `k` is the degrees of -/// freedom. -/// -/// For `k > 0` integral, this distribution is the sum of the squares -/// of `k` independent standard normal random variables. For other -/// `k`, this uses the equivalent characterisation -/// `χ²(k) = Gamma(k/2, 2)`. -#[deprecated(since="0.7.0", note="moved to rand_distr crate")] -#[derive(Clone, Copy, Debug)] -pub struct ChiSquared { - repr: ChiSquaredRepr, -} - -#[derive(Clone, Copy, Debug)] -enum ChiSquaredRepr { - // k == 1, Gamma(alpha, ..) is particularly slow for alpha < 1, - // e.g. when alpha = 1/2 as it would be for this case, so special- - // casing and using the definition of N(0,1)^2 is faster. - DoFExactlyOne, - DoFAnythingElse(Gamma), -} - -impl ChiSquared { - /// Create a new chi-squared distribution with degrees-of-freedom - /// `k`. Panics if `k < 0`. - pub fn new(k: f64) -> ChiSquared { - let repr = if k == 1.0 { - DoFExactlyOne - } else { - assert!(k > 0.0, "ChiSquared::new called with `k` < 0"); - DoFAnythingElse(Gamma::new(0.5 * k, 2.0)) - }; - ChiSquared { repr } - } -} -impl Distribution for ChiSquared { - fn sample(&self, rng: &mut R) -> f64 { - match self.repr { - DoFExactlyOne => { - // k == 1 => N(0,1)^2 - let norm = rng.sample(StandardNormal); - norm * norm - } - DoFAnythingElse(ref g) => g.sample(rng) - } - } -} - -/// The Fisher F distribution `F(m, n)`. -/// -/// This distribution is equivalent to the ratio of two normalised -/// chi-squared distributions, that is, `F(m,n) = (χ²(m)/m) / -/// (χ²(n)/n)`. -#[deprecated(since="0.7.0", note="moved to rand_distr crate")] -#[derive(Clone, Copy, Debug)] -pub struct FisherF { - numer: ChiSquared, - denom: ChiSquared, - // denom_dof / numer_dof so that this can just be a straight - // multiplication, rather than a division. - dof_ratio: f64, -} - -impl FisherF { - /// Create a new `FisherF` distribution, with the given - /// parameter. Panics if either `m` or `n` are not positive. - pub fn new(m: f64, n: f64) -> FisherF { - assert!(m > 0.0, "FisherF::new called with `m < 0`"); - assert!(n > 0.0, "FisherF::new called with `n < 0`"); - - FisherF { - numer: ChiSquared::new(m), - denom: ChiSquared::new(n), - dof_ratio: n / m - } - } -} -impl Distribution for FisherF { - fn sample(&self, rng: &mut R) -> f64 { - self.numer.sample(rng) / self.denom.sample(rng) * self.dof_ratio - } -} - -/// The Student t distribution, `t(nu)`, where `nu` is the degrees of -/// freedom. -#[deprecated(since="0.7.0", note="moved to rand_distr crate")] -#[derive(Clone, Copy, Debug)] -pub struct StudentT { - chi: ChiSquared, - dof: f64 -} - -impl StudentT { - /// Create a new Student t distribution with `n` degrees of - /// freedom. Panics if `n <= 0`. - pub fn new(n: f64) -> StudentT { - assert!(n > 0.0, "StudentT::new called with `n <= 0`"); - StudentT { - chi: ChiSquared::new(n), - dof: n - } - } -} -impl Distribution for StudentT { - fn sample(&self, rng: &mut R) -> f64 { - let norm = rng.sample(StandardNormal); - norm * (self.dof / self.chi.sample(rng)).sqrt() - } -} - -/// The Beta distribution with shape parameters `alpha` and `beta`. -#[deprecated(since="0.7.0", note="moved to rand_distr crate")] -#[derive(Clone, Copy, Debug)] -pub struct Beta { - gamma_a: Gamma, - gamma_b: Gamma, -} - -impl Beta { - /// Construct an object representing the `Beta(alpha, beta)` - /// distribution. - /// - /// Panics if `shape <= 0` or `scale <= 0`. - pub fn new(alpha: f64, beta: f64) -> Beta { - assert!((alpha > 0.) & (beta > 0.)); - Beta { - gamma_a: Gamma::new(alpha, 1.), - gamma_b: Gamma::new(beta, 1.), - } - } -} - -impl Distribution for Beta { - fn sample(&self, rng: &mut R) -> f64 { - let x = self.gamma_a.sample(rng); - let y = self.gamma_b.sample(rng); - x / (x + y) - } -} - -#[cfg(test)] -mod test { - use crate::distributions::Distribution; - use super::{Beta, ChiSquared, StudentT, FisherF}; - - const N: u32 = 100; - - #[test] - fn test_chi_squared_one() { - let chi = ChiSquared::new(1.0); - let mut rng = crate::test::rng(201); - for _ in 0..N { - chi.sample(&mut rng); - } - } - #[test] - fn test_chi_squared_small() { - let chi = ChiSquared::new(0.5); - let mut rng = crate::test::rng(202); - for _ in 0..N { - chi.sample(&mut rng); - } - } - #[test] - fn test_chi_squared_large() { - let chi = ChiSquared::new(30.0); - let mut rng = crate::test::rng(203); - for _ in 0..N { - chi.sample(&mut rng); - } - } - #[test] - #[should_panic] - fn test_chi_squared_invalid_dof() { - ChiSquared::new(-1.0); - } - - #[test] - fn test_f() { - let f = FisherF::new(2.0, 32.0); - let mut rng = crate::test::rng(204); - for _ in 0..N { - f.sample(&mut rng); - } - } - - #[test] - fn test_t() { - let t = StudentT::new(11.0); - let mut rng = crate::test::rng(205); - for _ in 0..N { - t.sample(&mut rng); - } - } - - #[test] - fn test_beta() { - let beta = Beta::new(1.0, 2.0); - let mut rng = crate::test::rng(201); - for _ in 0..N { - beta.sample(&mut rng); - } - } - - #[test] - #[should_panic] - fn test_beta_invalid_dof() { - Beta::new(0., 0.); - } -} diff --git a/rand/src/distributions/integer.rs b/rand/src/distributions/integer.rs deleted file mode 100644 index 5238339..0000000 --- a/rand/src/distributions/integer.rs +++ /dev/null @@ -1,184 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The implementations of the `Standard` distribution for integer types. - -use crate::{Rng}; -use crate::distributions::{Distribution, Standard}; -use core::num::{NonZeroU8, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroUsize}; -#[cfg(not(target_os = "emscripten"))] use core::num::NonZeroU128; -#[cfg(feature="simd_support")] -use packed_simd::*; -#[cfg(all(target_arch = "x86", feature="nightly"))] -use core::arch::x86::*; -#[cfg(all(target_arch = "x86_64", feature="nightly"))] -use core::arch::x86_64::*; - -impl Distribution for Standard { - #[inline] - fn sample(&self, rng: &mut R) -> u8 { - rng.next_u32() as u8 - } -} - -impl Distribution for Standard { - #[inline] - fn sample(&self, rng: &mut R) -> u16 { - rng.next_u32() as u16 - } -} - -impl Distribution for Standard { - #[inline] - fn sample(&self, rng: &mut R) -> u32 { - rng.next_u32() - } -} - -impl Distribution for Standard { - #[inline] - fn sample(&self, rng: &mut R) -> u64 { - rng.next_u64() - } -} - -#[cfg(not(target_os = "emscripten"))] -impl Distribution for Standard { - #[inline] - fn sample(&self, rng: &mut R) -> u128 { - // Use LE; we explicitly generate one value before the next. - let x = u128::from(rng.next_u64()); - let y = u128::from(rng.next_u64()); - (y << 64) | x - } -} - -impl Distribution for Standard { - #[inline] - #[cfg(any(target_pointer_width = "32", target_pointer_width = "16"))] - fn sample(&self, rng: &mut R) -> usize { - rng.next_u32() as usize - } - - #[inline] - #[cfg(target_pointer_width = "64")] - fn sample(&self, rng: &mut R) -> usize { - rng.next_u64() as usize - } -} - -macro_rules! impl_int_from_uint { - ($ty:ty, $uty:ty) => { - impl Distribution<$ty> for Standard { - #[inline] - fn sample(&self, rng: &mut R) -> $ty { - rng.gen::<$uty>() as $ty - } - } - } -} - -impl_int_from_uint! { i8, u8 } -impl_int_from_uint! { i16, u16 } -impl_int_from_uint! { i32, u32 } -impl_int_from_uint! { i64, u64 } -#[cfg(not(target_os = "emscripten"))] impl_int_from_uint! { i128, u128 } -impl_int_from_uint! { isize, usize } - -macro_rules! impl_nzint { - ($ty:ty, $new:path) => { - impl Distribution<$ty> for Standard { - fn sample(&self, rng: &mut R) -> $ty { - loop { - if let Some(nz) = $new(rng.gen()) { - break nz; - } - } - } - } - } -} - -impl_nzint!(NonZeroU8, NonZeroU8::new); -impl_nzint!(NonZeroU16, NonZeroU16::new); -impl_nzint!(NonZeroU32, NonZeroU32::new); -impl_nzint!(NonZeroU64, NonZeroU64::new); -#[cfg(not(target_os = "emscripten"))] impl_nzint!(NonZeroU128, NonZeroU128::new); -impl_nzint!(NonZeroUsize, NonZeroUsize::new); - -#[cfg(feature="simd_support")] -macro_rules! simd_impl { - ($(($intrinsic:ident, $vec:ty),)+) => {$( - impl Distribution<$intrinsic> for Standard { - #[inline] - fn sample(&self, rng: &mut R) -> $intrinsic { - $intrinsic::from_bits(rng.gen::<$vec>()) - } - } - )+}; - - ($bits:expr,) => {}; - ($bits:expr, $ty:ty, $($ty_more:ty,)*) => { - simd_impl!($bits, $($ty_more,)*); - - impl Distribution<$ty> for Standard { - #[inline] - fn sample(&self, rng: &mut R) -> $ty { - let mut vec: $ty = Default::default(); - unsafe { - let ptr = &mut vec; - let b_ptr = &mut *(ptr as *mut $ty as *mut [u8; $bits/8]); - rng.fill_bytes(b_ptr); - } - vec.to_le() - } - } - }; -} - -#[cfg(feature="simd_support")] -simd_impl!(16, u8x2, i8x2,); -#[cfg(feature="simd_support")] -simd_impl!(32, u8x4, i8x4, u16x2, i16x2,); -#[cfg(feature="simd_support")] -simd_impl!(64, u8x8, i8x8, u16x4, i16x4, u32x2, i32x2,); -#[cfg(feature="simd_support")] -simd_impl!(128, u8x16, i8x16, u16x8, i16x8, u32x4, i32x4, u64x2, i64x2,); -#[cfg(feature="simd_support")] -simd_impl!(256, u8x32, i8x32, u16x16, i16x16, u32x8, i32x8, u64x4, i64x4,); -#[cfg(feature="simd_support")] -simd_impl!(512, u8x64, i8x64, u16x32, i16x32, u32x16, i32x16, u64x8, i64x8,); -#[cfg(all(feature="simd_support", feature="nightly", any(target_arch="x86", target_arch="x86_64")))] -simd_impl!((__m64, u8x8), (__m128i, u8x16), (__m256i, u8x32),); - -#[cfg(test)] -mod tests { - use crate::Rng; - use crate::distributions::{Standard}; - - #[test] - fn test_integers() { - let mut rng = crate::test::rng(806); - - rng.sample::(Standard); - rng.sample::(Standard); - rng.sample::(Standard); - rng.sample::(Standard); - rng.sample::(Standard); - #[cfg(not(target_os = "emscripten"))] - rng.sample::(Standard); - - rng.sample::(Standard); - rng.sample::(Standard); - rng.sample::(Standard); - rng.sample::(Standard); - rng.sample::(Standard); - #[cfg(not(target_os = "emscripten"))] - rng.sample::(Standard); - } -} diff --git a/rand/src/distributions/mod.rs b/rand/src/distributions/mod.rs deleted file mode 100644 index 02ece6f..0000000 --- a/rand/src/distributions/mod.rs +++ /dev/null @@ -1,381 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// Copyright 2013-2017 The Rust Project Developers. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Generating random samples from probability distributions -//! -//! This module is the home of the [`Distribution`] trait and several of its -//! implementations. It is the workhorse behind some of the convenient -//! functionality of the [`Rng`] trait, e.g. [`Rng::gen`], [`Rng::gen_range`] and -//! of course [`Rng::sample`]. -//! -//! Abstractly, a [probability distribution] describes the probability of -//! occurance of each value in its sample space. -//! -//! More concretely, an implementation of `Distribution` for type `X` is an -//! algorithm for choosing values from the sample space (a subset of `T`) -//! according to the distribution `X` represents, using an external source of -//! randomness (an RNG supplied to the `sample` function). -//! -//! A type `X` may implement `Distribution` for multiple types `T`. -//! Any type implementing [`Distribution`] is stateless (i.e. immutable), -//! but it may have internal parameters set at construction time (for example, -//! [`Uniform`] allows specification of its sample space as a range within `T`). -//! -//! -//! # The `Standard` distribution -//! -//! The [`Standard`] distribution is important to mention. This is the -//! distribution used by [`Rng::gen()`] and represents the "default" way to -//! produce a random value for many different types, including most primitive -//! types, tuples, arrays, and a few derived types. See the documentation of -//! [`Standard`] for more details. -//! -//! Implementing `Distribution` for [`Standard`] for user types `T` makes it -//! possible to generate type `T` with [`Rng::gen()`], and by extension also -//! with the [`random()`] function. -//! -//! ## Random characters -//! -//! [`Alphanumeric`] is a simple distribution to sample random letters and -//! numbers of the `char` type; in contrast [`Standard`] may sample any valid -//! `char`. -//! -//! -//! # Uniform numeric ranges -//! -//! The [`Uniform`] distribution is more flexible than [`Standard`], but also -//! more specialised: it supports fewer target types, but allows the sample -//! space to be specified as an arbitrary range within its target type `T`. -//! Both [`Standard`] and [`Uniform`] are in some sense uniform distributions. -//! -//! Values may be sampled from this distribution using [`Rng::gen_range`] or -//! by creating a distribution object with [`Uniform::new`], -//! [`Uniform::new_inclusive`] or `From`. When the range limits are not -//! known at compile time it is typically faster to reuse an existing -//! distribution object than to call [`Rng::gen_range`]. -//! -//! User types `T` may also implement `Distribution` for [`Uniform`], -//! although this is less straightforward than for [`Standard`] (see the -//! documentation in the [`uniform`] module. Doing so enables generation of -//! values of type `T` with [`Rng::gen_range`]. -//! -//! ## Open and half-open ranges -//! -//! There are surprisingly many ways to uniformly generate random floats. A -//! range between 0 and 1 is standard, but the exact bounds (open vs closed) -//! and accuracy differ. In addition to the [`Standard`] distribution Rand offers -//! [`Open01`] and [`OpenClosed01`]. See "Floating point implementation" section of -//! [`Standard`] documentation for more details. -//! -//! # Non-uniform sampling -//! -//! Sampling a simple true/false outcome with a given probability has a name: -//! the [`Bernoulli`] distribution (this is used by [`Rng::gen_bool`]). -//! -//! For weighted sampling from a sequence of discrete values, use the -//! [`weighted`] module. -//! -//! This crate no longer includes other non-uniform distributions; instead -//! it is recommended that you use either [`rand_distr`] or [`statrs`]. -//! -//! -//! [probability distribution]: https://en.wikipedia.org/wiki/Probability_distribution -//! [`rand_distr`]: https://crates.io/crates/rand_distr -//! [`statrs`]: https://crates.io/crates/statrs - -//! [`Alphanumeric`]: distributions::Alphanumeric -//! [`Bernoulli`]: distributions::Bernoulli -//! [`Open01`]: distributions::Open01 -//! [`OpenClosed01`]: distributions::OpenClosed01 -//! [`Standard`]: distributions::Standard -//! [`Uniform`]: distributions::Uniform -//! [`Uniform::new`]: distributions::Uniform::new -//! [`Uniform::new_inclusive`]: distributions::Uniform::new_inclusive -//! [`weighted`]: distributions::weighted -//! [`rand_distr`]: https://crates.io/crates/rand_distr -//! [`statrs`]: https://crates.io/crates/statrs - -use core::iter; -use crate::Rng; - -pub use self::other::Alphanumeric; -#[doc(inline)] pub use self::uniform::Uniform; -pub use self::float::{OpenClosed01, Open01}; -pub use self::bernoulli::{Bernoulli, BernoulliError}; -#[cfg(feature="alloc")] pub use self::weighted::{WeightedIndex, WeightedError}; - -// The following are all deprecated after being moved to rand_distr -#[allow(deprecated)] -#[cfg(feature="std")] pub use self::unit_sphere::UnitSphereSurface; -#[allow(deprecated)] -#[cfg(feature="std")] pub use self::unit_circle::UnitCircle; -#[allow(deprecated)] -#[cfg(feature="std")] pub use self::gamma::{Gamma, ChiSquared, FisherF, - StudentT, Beta}; -#[allow(deprecated)] -#[cfg(feature="std")] pub use self::normal::{Normal, LogNormal, StandardNormal}; -#[allow(deprecated)] -#[cfg(feature="std")] pub use self::exponential::{Exp, Exp1}; -#[allow(deprecated)] -#[cfg(feature="std")] pub use self::pareto::Pareto; -#[allow(deprecated)] -#[cfg(feature="std")] pub use self::poisson::Poisson; -#[allow(deprecated)] -#[cfg(feature="std")] pub use self::binomial::Binomial; -#[allow(deprecated)] -#[cfg(feature="std")] pub use self::cauchy::Cauchy; -#[allow(deprecated)] -#[cfg(feature="std")] pub use self::dirichlet::Dirichlet; -#[allow(deprecated)] -#[cfg(feature="std")] pub use self::triangular::Triangular; -#[allow(deprecated)] -#[cfg(feature="std")] pub use self::weibull::Weibull; - -pub mod uniform; -mod bernoulli; -#[cfg(feature="alloc")] pub mod weighted; -#[cfg(feature="std")] mod unit_sphere; -#[cfg(feature="std")] mod unit_circle; -#[cfg(feature="std")] mod gamma; -#[cfg(feature="std")] mod normal; -#[cfg(feature="std")] mod exponential; -#[cfg(feature="std")] mod pareto; -#[cfg(feature="std")] mod poisson; -#[cfg(feature="std")] mod binomial; -#[cfg(feature="std")] mod cauchy; -#[cfg(feature="std")] mod dirichlet; -#[cfg(feature="std")] mod triangular; -#[cfg(feature="std")] mod weibull; - -mod float; -#[doc(hidden)] pub mod hidden_export { - pub use super::float::IntoFloat; // used by rand_distr -} -mod integer; -mod other; -mod utils; -#[cfg(feature="std")] mod ziggurat_tables; - -/// Types (distributions) that can be used to create a random instance of `T`. -/// -/// It is possible to sample from a distribution through both the -/// `Distribution` and [`Rng`] traits, via `distr.sample(&mut rng)` and -/// `rng.sample(distr)`. They also both offer the [`sample_iter`] method, which -/// produces an iterator that samples from the distribution. -/// -/// All implementations are expected to be immutable; this has the significant -/// advantage of not needing to consider thread safety, and for most -/// distributions efficient state-less sampling algorithms are available. -/// -/// [`sample_iter`]: Distribution::method.sample_iter -pub trait Distribution { - /// Generate a random value of `T`, using `rng` as the source of randomness. - fn sample(&self, rng: &mut R) -> T; - - /// Create an iterator that generates random values of `T`, using `rng` as - /// the source of randomness. - /// - /// Note that this function takes `self` by value. This works since - /// `Distribution` is impl'd for `&D` where `D: Distribution`, - /// however borrowing is not automatic hence `distr.sample_iter(...)` may - /// need to be replaced with `(&distr).sample_iter(...)` to borrow or - /// `(&*distr).sample_iter(...)` to reborrow an existing reference. - /// - /// # Example - /// - /// ``` - /// use rand::thread_rng; - /// use rand::distributions::{Distribution, Alphanumeric, Uniform, Standard}; - /// - /// let rng = thread_rng(); - /// - /// // Vec of 16 x f32: - /// let v: Vec = Standard.sample_iter(rng).take(16).collect(); - /// - /// // String: - /// let s: String = Alphanumeric.sample_iter(rng).take(7).collect(); - /// - /// // Dice-rolling: - /// let die_range = Uniform::new_inclusive(1, 6); - /// let mut roll_die = die_range.sample_iter(rng); - /// while roll_die.next().unwrap() != 6 { - /// println!("Not a 6; rolling again!"); - /// } - /// ``` - fn sample_iter(self, rng: R) -> DistIter - where R: Rng, Self: Sized - { - DistIter { - distr: self, - rng, - phantom: ::core::marker::PhantomData, - } - } -} - -impl<'a, T, D: Distribution> Distribution for &'a D { - fn sample(&self, rng: &mut R) -> T { - (*self).sample(rng) - } -} - - -/// An iterator that generates random values of `T` with distribution `D`, -/// using `R` as the source of randomness. -/// -/// This `struct` is created by the [`sample_iter`] method on [`Distribution`]. -/// See its documentation for more. -/// -/// [`sample_iter`]: Distribution::sample_iter -#[derive(Debug)] -pub struct DistIter { - distr: D, - rng: R, - phantom: ::core::marker::PhantomData, -} - -impl Iterator for DistIter - where D: Distribution, R: Rng -{ - type Item = T; - - #[inline(always)] - fn next(&mut self) -> Option { - // Here, self.rng may be a reference, but we must take &mut anyway. - // Even if sample could take an R: Rng by value, we would need to do this - // since Rng is not copyable and we cannot enforce that this is "reborrowable". - Some(self.distr.sample(&mut self.rng)) - } - - fn size_hint(&self) -> (usize, Option) { - (usize::max_value(), None) - } -} - -impl iter::FusedIterator for DistIter - where D: Distribution, R: Rng {} - -#[cfg(features = "nightly")] -impl iter::TrustedLen for DistIter - where D: Distribution, R: Rng {} - - -/// A generic random value distribution, implemented for many primitive types. -/// Usually generates values with a numerically uniform distribution, and with a -/// range appropriate to the type. -/// -/// ## Provided implementations -/// -/// Assuming the provided `Rng` is well-behaved, these implementations -/// generate values with the following ranges and distributions: -/// -/// * Integers (`i32`, `u32`, `isize`, `usize`, etc.): Uniformly distributed -/// over all values of the type. -/// * `char`: Uniformly distributed over all Unicode scalar values, i.e. all -/// code points in the range `0...0x10_FFFF`, except for the range -/// `0xD800...0xDFFF` (the surrogate code points). This includes -/// unassigned/reserved code points. -/// * `bool`: Generates `false` or `true`, each with probability 0.5. -/// * Floating point types (`f32` and `f64`): Uniformly distributed in the -/// half-open range `[0, 1)`. See notes below. -/// * Wrapping integers (`Wrapping`), besides the type identical to their -/// normal integer variants. -/// -/// The `Standard` distribution also supports generation of the following -/// compound types where all component types are supported: -/// -/// * Tuples (up to 12 elements): each element is generated sequentially. -/// * Arrays (up to 32 elements): each element is generated sequentially; -/// see also [`Rng::fill`] which supports arbitrary array length for integer -/// types and tends to be faster for `u32` and smaller types. -/// * `Option` first generates a `bool`, and if true generates and returns -/// `Some(value)` where `value: T`, otherwise returning `None`. -/// -/// ## Custom implementations -/// -/// The [`Standard`] distribution may be implemented for user types as follows: -/// -/// ``` -/// # #![allow(dead_code)] -/// use rand::Rng; -/// use rand::distributions::{Distribution, Standard}; -/// -/// struct MyF32 { -/// x: f32, -/// } -/// -/// impl Distribution for Standard { -/// fn sample(&self, rng: &mut R) -> MyF32 { -/// MyF32 { x: rng.gen() } -/// } -/// } -/// ``` -/// -/// ## Example usage -/// ``` -/// use rand::prelude::*; -/// use rand::distributions::Standard; -/// -/// let val: f32 = StdRng::from_entropy().sample(Standard); -/// println!("f32 from [0, 1): {}", val); -/// ``` -/// -/// # Floating point implementation -/// The floating point implementations for `Standard` generate a random value in -/// the half-open interval `[0, 1)`, i.e. including 0 but not 1. -/// -/// All values that can be generated are of the form `n * Ξ΅/2`. For `f32` -/// the 23 most significant random bits of a `u32` are used and for `f64` the -/// 53 most significant bits of a `u64` are used. The conversion uses the -/// multiplicative method: `(rng.gen::<$uty>() >> N) as $ty * (Ξ΅/2)`. -/// -/// See also: [`Open01`] which samples from `(0, 1)`, [`OpenClosed01`] which -/// samples from `(0, 1]` and `Rng::gen_range(0, 1)` which also samples from -/// `[0, 1)`. Note that `Open01` and `gen_range` (which uses [`Uniform`]) use -/// transmute-based methods which yield 1 bit less precision but may perform -/// faster on some architectures (on modern Intel CPUs all methods have -/// approximately equal performance). -/// -/// [`Uniform`]: uniform::Uniform -#[derive(Clone, Copy, Debug)] -pub struct Standard; - - -#[cfg(all(test, feature = "std"))] -mod tests { - use crate::Rng; - use super::{Distribution, Uniform}; - - #[test] - fn test_distributions_iter() { - use crate::distributions::Open01; - let mut rng = crate::test::rng(210); - let distr = Open01; - let results: Vec = distr.sample_iter(&mut rng).take(100).collect(); - println!("{:?}", results); - } - - #[test] - fn test_make_an_iter() { - fn ten_dice_rolls_other_than_five<'a, R: Rng>(rng: &'a mut R) -> impl Iterator + 'a { - Uniform::new_inclusive(1, 6) - .sample_iter(rng) - .filter(|x| *x != 5) - .take(10) - } - - let mut rng = crate::test::rng(211); - let mut count = 0; - for val in ten_dice_rolls_other_than_five(&mut rng) { - assert!(val >= 1 && val <= 6 && val != 5); - count += 1; - } - assert_eq!(count, 10); - } -} diff --git a/rand/src/distributions/normal.rs b/rand/src/distributions/normal.rs deleted file mode 100644 index 7808baf..0000000 --- a/rand/src/distributions/normal.rs +++ /dev/null @@ -1,170 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// Copyright 2013 The Rust Project Developers. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The normal and derived distributions. -#![allow(deprecated)] - -use crate::Rng; -use crate::distributions::{ziggurat_tables, Distribution, Open01}; -use crate::distributions::utils::ziggurat; - -/// Samples floating-point numbers according to the normal distribution -/// `N(0, 1)` (a.k.a. a standard normal, or Gaussian). This is equivalent to -/// `Normal::new(0.0, 1.0)` but faster. -/// -/// See `Normal` for the general normal distribution. -/// -/// Implemented via the ZIGNOR variant[^1] of the Ziggurat method. -/// -/// [^1]: Jurgen A. Doornik (2005). [*An Improved Ziggurat Method to -/// Generate Normal Random Samples*]( -/// https://www.doornik.com/research/ziggurat.pdf). -/// Nuffield College, Oxford -#[deprecated(since="0.7.0", note="moved to rand_distr crate")] -#[derive(Clone, Copy, Debug)] -pub struct StandardNormal; - -impl Distribution for StandardNormal { - fn sample(&self, rng: &mut R) -> f64 { - #[inline] - fn pdf(x: f64) -> f64 { - (-x*x/2.0).exp() - } - #[inline] - fn zero_case(rng: &mut R, u: f64) -> f64 { - // compute a random number in the tail by hand - - // strange initial conditions, because the loop is not - // do-while, so the condition should be true on the first - // run, they get overwritten anyway (0 < 1, so these are - // good). - let mut x = 1.0f64; - let mut y = 0.0f64; - - while -2.0 * y < x * x { - let x_: f64 = rng.sample(Open01); - let y_: f64 = rng.sample(Open01); - - x = x_.ln() / ziggurat_tables::ZIG_NORM_R; - y = y_.ln(); - } - - if u < 0.0 { x - ziggurat_tables::ZIG_NORM_R } else { ziggurat_tables::ZIG_NORM_R - x } - } - - ziggurat(rng, true, // this is symmetric - &ziggurat_tables::ZIG_NORM_X, - &ziggurat_tables::ZIG_NORM_F, - pdf, zero_case) - } -} - -/// The normal distribution `N(mean, std_dev**2)`. -/// -/// This uses the ZIGNOR variant of the Ziggurat method, see [`StandardNormal`] -/// for more details. -/// -/// Note that [`StandardNormal`] is an optimised implementation for mean 0, and -/// standard deviation 1. -/// -/// [`StandardNormal`]: crate::distributions::StandardNormal -#[deprecated(since="0.7.0", note="moved to rand_distr crate")] -#[derive(Clone, Copy, Debug)] -pub struct Normal { - mean: f64, - std_dev: f64, -} - -impl Normal { - /// Construct a new `Normal` distribution with the given mean and - /// standard deviation. - /// - /// # Panics - /// - /// Panics if `std_dev < 0`. - #[inline] - pub fn new(mean: f64, std_dev: f64) -> Normal { - assert!(std_dev >= 0.0, "Normal::new called with `std_dev` < 0"); - Normal { - mean, - std_dev - } - } -} -impl Distribution for Normal { - fn sample(&self, rng: &mut R) -> f64 { - let n = rng.sample(StandardNormal); - self.mean + self.std_dev * n - } -} - - -/// The log-normal distribution `ln N(mean, std_dev**2)`. -/// -/// If `X` is log-normal distributed, then `ln(X)` is `N(mean, std_dev**2)` -/// distributed. -#[deprecated(since="0.7.0", note="moved to rand_distr crate")] -#[derive(Clone, Copy, Debug)] -pub struct LogNormal { - norm: Normal -} - -impl LogNormal { - /// Construct a new `LogNormal` distribution with the given mean - /// and standard deviation. - /// - /// # Panics - /// - /// Panics if `std_dev < 0`. - #[inline] - pub fn new(mean: f64, std_dev: f64) -> LogNormal { - assert!(std_dev >= 0.0, "LogNormal::new called with `std_dev` < 0"); - LogNormal { norm: Normal::new(mean, std_dev) } - } -} -impl Distribution for LogNormal { - fn sample(&self, rng: &mut R) -> f64 { - self.norm.sample(rng).exp() - } -} - -#[cfg(test)] -mod tests { - use crate::distributions::Distribution; - use super::{Normal, LogNormal}; - - #[test] - fn test_normal() { - let norm = Normal::new(10.0, 10.0); - let mut rng = crate::test::rng(210); - for _ in 0..1000 { - norm.sample(&mut rng); - } - } - #[test] - #[should_panic] - fn test_normal_invalid_sd() { - Normal::new(10.0, -1.0); - } - - - #[test] - fn test_log_normal() { - let lnorm = LogNormal::new(10.0, 10.0); - let mut rng = crate::test::rng(211); - for _ in 0..1000 { - lnorm.sample(&mut rng); - } - } - #[test] - #[should_panic] - fn test_log_normal_invalid_sd() { - LogNormal::new(10.0, -1.0); - } -} diff --git a/rand/src/distributions/other.rs b/rand/src/distributions/other.rs deleted file mode 100644 index 6ec0473..0000000 --- a/rand/src/distributions/other.rs +++ /dev/null @@ -1,220 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The implementations of the `Standard` distribution for other built-in types. - -use core::char; -use core::num::Wrapping; - -use crate::Rng; -use crate::distributions::{Distribution, Standard, Uniform}; - -// ----- Sampling distributions ----- - -/// Sample a `char`, uniformly distributed over ASCII letters and numbers: -/// a-z, A-Z and 0-9. -/// -/// # Example -/// -/// ``` -/// use std::iter; -/// use rand::{Rng, thread_rng}; -/// use rand::distributions::Alphanumeric; -/// -/// let mut rng = thread_rng(); -/// let chars: String = iter::repeat(()) -/// .map(|()| rng.sample(Alphanumeric)) -/// .take(7) -/// .collect(); -/// println!("Random chars: {}", chars); -/// ``` -#[derive(Debug)] -pub struct Alphanumeric; - - -// ----- Implementations of distributions ----- - -impl Distribution for Standard { - #[inline] - fn sample(&self, rng: &mut R) -> char { - // A valid `char` is either in the interval `[0, 0xD800)` or - // `(0xDFFF, 0x11_0000)`. All `char`s must therefore be in - // `[0, 0x11_0000)` but not in the "gap" `[0xD800, 0xDFFF]` which is - // reserved for surrogates. This is the size of that gap. - const GAP_SIZE: u32 = 0xDFFF - 0xD800 + 1; - - // Uniform::new(0, 0x11_0000 - GAP_SIZE) can also be used but it - // seemed slower. - let range = Uniform::new(GAP_SIZE, 0x11_0000); - - let mut n = range.sample(rng); - if n <= 0xDFFF { - n -= GAP_SIZE; - } - unsafe { char::from_u32_unchecked(n) } - } -} - -impl Distribution for Alphanumeric { - fn sample(&self, rng: &mut R) -> char { - const RANGE: u32 = 26 + 26 + 10; - const GEN_ASCII_STR_CHARSET: &[u8] = - b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\ - abcdefghijklmnopqrstuvwxyz\ - 0123456789"; - // We can pick from 62 characters. This is so close to a power of 2, 64, - // that we can do better than `Uniform`. Use a simple bitshift and - // rejection sampling. We do not use a bitmask, because for small RNGs - // the most significant bits are usually of higher quality. - loop { - let var = rng.next_u32() >> (32 - 6); - if var < RANGE { - return GEN_ASCII_STR_CHARSET[var as usize] as char - } - } - } -} - -impl Distribution for Standard { - #[inline] - fn sample(&self, rng: &mut R) -> bool { - // We can compare against an arbitrary bit of an u32 to get a bool. - // Because the least significant bits of a lower quality RNG can have - // simple patterns, we compare against the most significant bit. This is - // easiest done using a sign test. - (rng.next_u32() as i32) < 0 - } -} - -macro_rules! tuple_impl { - // use variables to indicate the arity of the tuple - ($($tyvar:ident),* ) => { - // the trailing commas are for the 1 tuple - impl< $( $tyvar ),* > - Distribution<( $( $tyvar ),* , )> - for Standard - where $( Standard: Distribution<$tyvar> ),* - { - #[inline] - fn sample(&self, _rng: &mut R) -> ( $( $tyvar ),* , ) { - ( - // use the $tyvar's to get the appropriate number of - // repeats (they're not actually needed) - $( - _rng.gen::<$tyvar>() - ),* - , - ) - } - } - } -} - -impl Distribution<()> for Standard { - #[allow(clippy::unused_unit)] - #[inline] - fn sample(&self, _: &mut R) -> () { () } -} -tuple_impl!{A} -tuple_impl!{A, B} -tuple_impl!{A, B, C} -tuple_impl!{A, B, C, D} -tuple_impl!{A, B, C, D, E} -tuple_impl!{A, B, C, D, E, F} -tuple_impl!{A, B, C, D, E, F, G} -tuple_impl!{A, B, C, D, E, F, G, H} -tuple_impl!{A, B, C, D, E, F, G, H, I} -tuple_impl!{A, B, C, D, E, F, G, H, I, J} -tuple_impl!{A, B, C, D, E, F, G, H, I, J, K} -tuple_impl!{A, B, C, D, E, F, G, H, I, J, K, L} - -macro_rules! array_impl { - // recursive, given at least one type parameter: - {$n:expr, $t:ident, $($ts:ident,)*} => { - array_impl!{($n - 1), $($ts,)*} - - impl Distribution<[T; $n]> for Standard where Standard: Distribution { - #[inline] - fn sample(&self, _rng: &mut R) -> [T; $n] { - [_rng.gen::<$t>(), $(_rng.gen::<$ts>()),*] - } - } - }; - // empty case: - {$n:expr,} => { - impl Distribution<[T; $n]> for Standard { - fn sample(&self, _rng: &mut R) -> [T; $n] { [] } - } - }; -} - -array_impl!{32, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T,} - -impl Distribution> for Standard where Standard: Distribution { - #[inline] - fn sample(&self, rng: &mut R) -> Option { - // UFCS is needed here: https://github.com/rust-lang/rust/issues/24066 - if rng.gen::() { - Some(rng.gen()) - } else { - None - } - } -} - -impl Distribution> for Standard where Standard: Distribution { - #[inline] - fn sample(&self, rng: &mut R) -> Wrapping { - Wrapping(rng.gen()) - } -} - - -#[cfg(test)] -mod tests { - use crate::{Rng, RngCore, Standard}; - use crate::distributions::Alphanumeric; - #[cfg(all(not(feature="std"), feature="alloc"))] use alloc::string::String; - - #[test] - fn test_misc() { - let rng: &mut dyn RngCore = &mut crate::test::rng(820); - - rng.sample::(Standard); - rng.sample::(Standard); - } - - #[cfg(feature="alloc")] - #[test] - fn test_chars() { - use core::iter; - let mut rng = crate::test::rng(805); - - // Test by generating a relatively large number of chars, so we also - // take the rejection sampling path. - let word: String = iter::repeat(()) - .map(|()| rng.gen::()).take(1000).collect(); - assert!(word.len() != 0); - } - - #[test] - fn test_alphanumeric() { - let mut rng = crate::test::rng(806); - - // Test by generating a relatively large number of chars, so we also - // take the rejection sampling path. - let mut incorrect = false; - for _ in 0..100 { - let c = rng.sample(Alphanumeric); - incorrect |= !((c >= '0' && c <= '9') || - (c >= 'A' && c <= 'Z') || - (c >= 'a' && c <= 'z') ); - } - assert!(incorrect == false); - } -} diff --git a/rand/src/distributions/pareto.rs b/rand/src/distributions/pareto.rs deleted file mode 100644 index edc9122..0000000 --- a/rand/src/distributions/pareto.rs +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The Pareto distribution. -#![allow(deprecated)] - -use crate::Rng; -use crate::distributions::{Distribution, OpenClosed01}; - -/// Samples floating-point numbers according to the Pareto distribution -#[deprecated(since="0.7.0", note="moved to rand_distr crate")] -#[derive(Clone, Copy, Debug)] -pub struct Pareto { - scale: f64, - inv_neg_shape: f64, -} - -impl Pareto { - /// Construct a new Pareto distribution with given `scale` and `shape`. - /// - /// In the literature, `scale` is commonly written as xm or k and - /// `shape` is often written as Ξ±. - /// - /// # Panics - /// - /// `scale` and `shape` have to be non-zero and positive. - pub fn new(scale: f64, shape: f64) -> Pareto { - assert!((scale > 0.) & (shape > 0.)); - Pareto { scale, inv_neg_shape: -1.0 / shape } - } -} - -impl Distribution for Pareto { - fn sample(&self, rng: &mut R) -> f64 { - let u: f64 = rng.sample(OpenClosed01); - self.scale * u.powf(self.inv_neg_shape) - } -} - -#[cfg(test)] -mod tests { - use crate::distributions::Distribution; - use super::Pareto; - - #[test] - #[should_panic] - fn invalid() { - Pareto::new(0., 0.); - } - - #[test] - fn sample() { - let scale = 1.0; - let shape = 2.0; - let d = Pareto::new(scale, shape); - let mut rng = crate::test::rng(1); - for _ in 0..1000 { - let r = d.sample(&mut rng); - assert!(r >= scale); - } - } -} diff --git a/rand/src/distributions/poisson.rs b/rand/src/distributions/poisson.rs deleted file mode 100644 index 9fd6e99..0000000 --- a/rand/src/distributions/poisson.rs +++ /dev/null @@ -1,151 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// Copyright 2016-2017 The Rust Project Developers. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The Poisson distribution. -#![allow(deprecated)] - -use crate::Rng; -use crate::distributions::{Distribution, Cauchy}; -use crate::distributions::utils::log_gamma; - -/// The Poisson distribution `Poisson(lambda)`. -/// -/// This distribution has a density function: -/// `f(k) = lambda^k * exp(-lambda) / k!` for `k >= 0`. -#[deprecated(since="0.7.0", note="moved to rand_distr crate")] -#[derive(Clone, Copy, Debug)] -pub struct Poisson { - lambda: f64, - // precalculated values - exp_lambda: f64, - log_lambda: f64, - sqrt_2lambda: f64, - magic_val: f64, -} - -impl Poisson { - /// Construct a new `Poisson` with the given shape parameter - /// `lambda`. Panics if `lambda <= 0`. - pub fn new(lambda: f64) -> Poisson { - assert!(lambda > 0.0, "Poisson::new called with lambda <= 0"); - let log_lambda = lambda.ln(); - Poisson { - lambda, - exp_lambda: (-lambda).exp(), - log_lambda, - sqrt_2lambda: (2.0 * lambda).sqrt(), - magic_val: lambda * log_lambda - log_gamma(1.0 + lambda), - } - } -} - -impl Distribution for Poisson { - fn sample(&self, rng: &mut R) -> u64 { - // using the algorithm from Numerical Recipes in C - - // for low expected values use the Knuth method - if self.lambda < 12.0 { - let mut result = 0; - let mut p = 1.0; - while p > self.exp_lambda { - p *= rng.gen::(); - result += 1; - } - result - 1 - } - // high expected values - rejection method - else { - let mut int_result: u64; - - // we use the Cauchy distribution as the comparison distribution - // f(x) ~ 1/(1+x^2) - let cauchy = Cauchy::new(0.0, 1.0); - - loop { - let mut result; - let mut comp_dev; - - loop { - // draw from the Cauchy distribution - comp_dev = rng.sample(cauchy); - // shift the peak of the comparison ditribution - result = self.sqrt_2lambda * comp_dev + self.lambda; - // repeat the drawing until we are in the range of possible values - if result >= 0.0 { - break; - } - } - // now the result is a random variable greater than 0 with Cauchy distribution - // the result should be an integer value - result = result.floor(); - int_result = result as u64; - - // this is the ratio of the Poisson distribution to the comparison distribution - // the magic value scales the distribution function to a range of approximately 0-1 - // since it is not exact, we multiply the ratio by 0.9 to avoid ratios greater than 1 - // this doesn't change the resulting distribution, only increases the rate of failed drawings - let check = 0.9 * (1.0 + comp_dev * comp_dev) - * (result * self.log_lambda - log_gamma(1.0 + result) - self.magic_val).exp(); - - // check with uniform random value - if below the threshold, we are within the target distribution - if rng.gen::() <= check { - break; - } - } - int_result - } - } -} - -#[cfg(test)] -mod test { - use crate::distributions::Distribution; - use super::Poisson; - - #[test] - #[cfg(not(miri))] // Miri is too slow - fn test_poisson_10() { - let poisson = Poisson::new(10.0); - let mut rng = crate::test::rng(123); - let mut sum = 0; - for _ in 0..1000 { - sum += poisson.sample(&mut rng); - } - let avg = (sum as f64) / 1000.0; - println!("Poisson average: {}", avg); - assert!((avg - 10.0).abs() < 0.5); // not 100% certain, but probable enough - } - - #[test] - #[cfg(not(miri))] // Miri doesn't support transcendental functions - fn test_poisson_15() { - // Take the 'high expected values' path - let poisson = Poisson::new(15.0); - let mut rng = crate::test::rng(123); - let mut sum = 0; - for _ in 0..1000 { - sum += poisson.sample(&mut rng); - } - let avg = (sum as f64) / 1000.0; - println!("Poisson average: {}", avg); - assert!((avg - 15.0).abs() < 0.5); // not 100% certain, but probable enough - } - - #[test] - #[should_panic] - fn test_poisson_invalid_lambda_zero() { - Poisson::new(0.0); - } - - #[test] - #[should_panic] - fn test_poisson_invalid_lambda_neg() { - Poisson::new(-10.0); - } -} diff --git a/rand/src/distributions/triangular.rs b/rand/src/distributions/triangular.rs deleted file mode 100644 index 3e8f8b0..0000000 --- a/rand/src/distributions/triangular.rs +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The triangular distribution. -#![allow(deprecated)] - -use crate::Rng; -use crate::distributions::{Distribution, Standard}; - -/// The triangular distribution. -#[deprecated(since="0.7.0", note="moved to rand_distr crate")] -#[derive(Clone, Copy, Debug)] -pub struct Triangular { - min: f64, - max: f64, - mode: f64, -} - -impl Triangular { - /// Construct a new `Triangular` with minimum `min`, maximum `max` and mode - /// `mode`. - /// - /// # Panics - /// - /// If `max < mode`, `mode < max` or `max == min`. - /// - #[inline] - pub fn new(min: f64, max: f64, mode: f64) -> Triangular { - assert!(max >= mode); - assert!(mode >= min); - assert!(max != min); - Triangular { min, max, mode } - } -} - -impl Distribution for Triangular { - #[inline] - fn sample(&self, rng: &mut R) -> f64 { - let f: f64 = rng.sample(Standard); - let diff_mode_min = self.mode - self.min; - let diff_max_min = self.max - self.min; - if f * diff_max_min < diff_mode_min { - self.min + (f * diff_max_min * diff_mode_min).sqrt() - } else { - self.max - ((1. - f) * diff_max_min * (self.max - self.mode)).sqrt() - } - } -} - -#[cfg(test)] -mod test { - use crate::distributions::Distribution; - use super::Triangular; - - #[test] - fn test_new() { - for &(min, max, mode) in &[ - (-1., 1., 0.), (1., 2., 1.), (5., 25., 25.), (1e-5, 1e5, 1e-3), - (0., 1., 0.9), (-4., -0.5, -2.), (-13.039, 8.41, 1.17), - ] { - println!("{} {} {}", min, max, mode); - let _ = Triangular::new(min, max, mode); - } - } - - #[test] - fn test_sample() { - let norm = Triangular::new(0., 1., 0.5); - let mut rng = crate::test::rng(1); - for _ in 0..1000 { - norm.sample(&mut rng); - } - } -} diff --git a/rand/src/distributions/uniform.rs b/rand/src/distributions/uniform.rs deleted file mode 100644 index 8c90f4e..0000000 --- a/rand/src/distributions/uniform.rs +++ /dev/null @@ -1,1270 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// Copyright 2017 The Rust Project Developers. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! A distribution uniformly sampling numbers within a given range. -//! -//! [`Uniform`] is the standard distribution to sample uniformly from a range; -//! e.g. `Uniform::new_inclusive(1, 6)` can sample integers from 1 to 6, like a -//! standard die. [`Rng::gen_range`] supports any type supported by -//! [`Uniform`]. -//! -//! This distribution is provided with support for several primitive types -//! (all integer and floating-point types) as well as [`std::time::Duration`], -//! and supports extension to user-defined types via a type-specific *back-end* -//! implementation. -//! -//! The types [`UniformInt`], [`UniformFloat`] and [`UniformDuration`] are the -//! back-ends supporting sampling from primitive integer and floating-point -//! ranges as well as from [`std::time::Duration`]; these types do not normally -//! need to be used directly (unless implementing a derived back-end). -//! -//! # Example usage -//! -//! ``` -//! use rand::{Rng, thread_rng}; -//! use rand::distributions::Uniform; -//! -//! let mut rng = thread_rng(); -//! let side = Uniform::new(-10.0, 10.0); -//! -//! // sample between 1 and 10 points -//! for _ in 0..rng.gen_range(1, 11) { -//! // sample a point from the square with sides -10 - 10 in two dimensions -//! let (x, y) = (rng.sample(side), rng.sample(side)); -//! println!("Point: {}, {}", x, y); -//! } -//! ``` -//! -//! # Extending `Uniform` to support a custom type -//! -//! To extend [`Uniform`] to support your own types, write a back-end which -//! implements the [`UniformSampler`] trait, then implement the [`SampleUniform`] -//! helper trait to "register" your back-end. See the `MyF32` example below. -//! -//! At a minimum, the back-end needs to store any parameters needed for sampling -//! (e.g. the target range) and implement `new`, `new_inclusive` and `sample`. -//! Those methods should include an assert to check the range is valid (i.e. -//! `low < high`). The example below merely wraps another back-end. -//! -//! The `new`, `new_inclusive` and `sample_single` functions use arguments of -//! type SampleBorrow in order to support passing in values by reference or -//! by value. In the implementation of these functions, you can choose to -//! simply use the reference returned by [`SampleBorrow::borrow`], or you can choose -//! to copy or clone the value, whatever is appropriate for your type. -//! -//! ``` -//! use rand::prelude::*; -//! use rand::distributions::uniform::{Uniform, SampleUniform, -//! UniformSampler, UniformFloat, SampleBorrow}; -//! -//! struct MyF32(f32); -//! -//! #[derive(Clone, Copy, Debug)] -//! struct UniformMyF32 { -//! inner: UniformFloat, -//! } -//! -//! impl UniformSampler for UniformMyF32 { -//! type X = MyF32; -//! fn new(low: B1, high: B2) -> Self -//! where B1: SampleBorrow + Sized, -//! B2: SampleBorrow + Sized -//! { -//! UniformMyF32 { -//! inner: UniformFloat::::new(low.borrow().0, high.borrow().0), -//! } -//! } -//! fn new_inclusive(low: B1, high: B2) -> Self -//! where B1: SampleBorrow + Sized, -//! B2: SampleBorrow + Sized -//! { -//! UniformSampler::new(low, high) -//! } -//! fn sample(&self, rng: &mut R) -> Self::X { -//! MyF32(self.inner.sample(rng)) -//! } -//! } -//! -//! impl SampleUniform for MyF32 { -//! type Sampler = UniformMyF32; -//! } -//! -//! let (low, high) = (MyF32(17.0f32), MyF32(22.0f32)); -//! let uniform = Uniform::new(low, high); -//! let x = uniform.sample(&mut thread_rng()); -//! ``` -//! -//! [`SampleUniform`]: crate::distributions::uniform::SampleUniform -//! [`UniformSampler`]: crate::distributions::uniform::UniformSampler -//! [`UniformInt`]: crate::distributions::uniform::UniformInt -//! [`UniformFloat`]: crate::distributions::uniform::UniformFloat -//! [`UniformDuration`]: crate::distributions::uniform::UniformDuration -//! [`SampleBorrow::borrow`]: crate::distributions::uniform::SampleBorrow::borrow - -#[cfg(feature = "std")] -use std::time::Duration; -#[cfg(not(feature = "std"))] -use core::time::Duration; - -use crate::Rng; -use crate::distributions::Distribution; -use crate::distributions::float::IntoFloat; -use crate::distributions::utils::{WideningMultiply, FloatSIMDUtils, FloatAsSIMD, BoolAsSIMD}; - -#[cfg(not(feature = "std"))] -#[allow(unused_imports)] // rustc doesn't detect that this is actually used -use crate::distributions::utils::Float; - - -#[cfg(feature="simd_support")] -use packed_simd::*; - -/// Sample values uniformly between two bounds. -/// -/// [`Uniform::new`] and [`Uniform::new_inclusive`] construct a uniform -/// distribution sampling from the given range; these functions may do extra -/// work up front to make sampling of multiple values faster. -/// -/// When sampling from a constant range, many calculations can happen at -/// compile-time and all methods should be fast; for floating-point ranges and -/// the full range of integer types this should have comparable performance to -/// the `Standard` distribution. -/// -/// Steps are taken to avoid bias which might be present in naive -/// implementations; for example `rng.gen::() % 170` samples from the range -/// `[0, 169]` but is twice as likely to select numbers less than 85 than other -/// values. Further, the implementations here give more weight to the high-bits -/// generated by the RNG than the low bits, since with some RNGs the low-bits -/// are of lower quality than the high bits. -/// -/// Implementations must sample in `[low, high)` range for -/// `Uniform::new(low, high)`, i.e., excluding `high`. In particular care must -/// be taken to ensure that rounding never results values `< low` or `>= high`. -/// -/// # Example -/// -/// ``` -/// use rand::distributions::{Distribution, Uniform}; -/// -/// fn main() { -/// let between = Uniform::from(10..10000); -/// let mut rng = rand::thread_rng(); -/// let mut sum = 0; -/// for _ in 0..1000 { -/// sum += between.sample(&mut rng); -/// } -/// println!("{}", sum); -/// } -/// ``` -/// -/// [`new`]: Uniform::new -/// [`new_inclusive`]: Uniform::new_inclusive -#[derive(Clone, Copy, Debug)] -pub struct Uniform { - inner: X::Sampler, -} - -impl Uniform { - /// Create a new `Uniform` instance which samples uniformly from the half - /// open range `[low, high)` (excluding `high`). Panics if `low >= high`. - pub fn new(low: B1, high: B2) -> Uniform - where B1: SampleBorrow + Sized, - B2: SampleBorrow + Sized - { - Uniform { inner: X::Sampler::new(low, high) } - } - - /// Create a new `Uniform` instance which samples uniformly from the closed - /// range `[low, high]` (inclusive). Panics if `low > high`. - pub fn new_inclusive(low: B1, high: B2) -> Uniform - where B1: SampleBorrow + Sized, - B2: SampleBorrow + Sized - { - Uniform { inner: X::Sampler::new_inclusive(low, high) } - } -} - -impl Distribution for Uniform { - fn sample(&self, rng: &mut R) -> X { - self.inner.sample(rng) - } -} - -/// Helper trait for creating objects using the correct implementation of -/// [`UniformSampler`] for the sampling type. -/// -/// See the [module documentation] on how to implement [`Uniform`] range -/// sampling for a custom type. -/// -/// [module documentation]: crate::distributions::uniform -pub trait SampleUniform: Sized { - /// The `UniformSampler` implementation supporting type `X`. - type Sampler: UniformSampler; -} - -/// Helper trait handling actual uniform sampling. -/// -/// See the [module documentation] on how to implement [`Uniform`] range -/// sampling for a custom type. -/// -/// Implementation of [`sample_single`] is optional, and is only useful when -/// the implementation can be faster than `Self::new(low, high).sample(rng)`. -/// -/// [module documentation]: crate::distributions::uniform -/// [`sample_single`]: UniformSampler::sample_single -pub trait UniformSampler: Sized { - /// The type sampled by this implementation. - type X; - - /// Construct self, with inclusive lower bound and exclusive upper bound - /// `[low, high)`. - /// - /// Usually users should not call this directly but instead use - /// `Uniform::new`, which asserts that `low < high` before calling this. - fn new(low: B1, high: B2) -> Self - where B1: SampleBorrow + Sized, - B2: SampleBorrow + Sized; - - /// Construct self, with inclusive bounds `[low, high]`. - /// - /// Usually users should not call this directly but instead use - /// `Uniform::new_inclusive`, which asserts that `low <= high` before - /// calling this. - fn new_inclusive(low: B1, high: B2) -> Self - where B1: SampleBorrow + Sized, - B2: SampleBorrow + Sized; - - /// Sample a value. - fn sample(&self, rng: &mut R) -> Self::X; - - /// Sample a single value uniformly from a range with inclusive lower bound - /// and exclusive upper bound `[low, high)`. - /// - /// By default this is implemented using - /// `UniformSampler::new(low, high).sample(rng)`. However, for some types - /// more optimal implementations for single usage may be provided via this - /// method (which is the case for integers and floats). - /// Results may not be identical. - fn sample_single(low: B1, high: B2, rng: &mut R) - -> Self::X - where B1: SampleBorrow + Sized, - B2: SampleBorrow + Sized - { - let uniform: Self = UniformSampler::new(low, high); - uniform.sample(rng) - } -} - -impl From<::core::ops::Range> for Uniform { - fn from(r: ::core::ops::Range) -> Uniform { - Uniform::new(r.start, r.end) - } -} - -impl From<::core::ops::RangeInclusive> for Uniform { - fn from(r: ::core::ops::RangeInclusive) -> Uniform { - Uniform::new_inclusive(r.start(), r.end()) - } -} - -/// Helper trait similar to [`Borrow`] but implemented -/// only for SampleUniform and references to SampleUniform in -/// order to resolve ambiguity issues. -/// -/// [`Borrow`]: std::borrow::Borrow -pub trait SampleBorrow { - /// Immutably borrows from an owned value. See [`Borrow::borrow`] - /// - /// [`Borrow::borrow`]: std::borrow::Borrow::borrow - fn borrow(&self) -> &Borrowed; -} -impl SampleBorrow for Borrowed where Borrowed: SampleUniform { - #[inline(always)] - fn borrow(&self) -> &Borrowed { self } -} -impl<'a, Borrowed> SampleBorrow for &'a Borrowed where Borrowed: SampleUniform { - #[inline(always)] - fn borrow(&self) -> &Borrowed { *self } -} - -//////////////////////////////////////////////////////////////////////////////// - -// What follows are all back-ends. - - -/// The back-end implementing [`UniformSampler`] for integer types. -/// -/// Unless you are implementing [`UniformSampler`] for your own type, this type -/// should not be used directly, use [`Uniform`] instead. -/// -/// # Implementation notes -/// -/// For simplicity, we use the same generic struct `UniformInt` for all -/// integer types `X`. This gives us only one field type, `X`; to store unsigned -/// values of this size, we take use the fact that these conversions are no-ops. -/// -/// For a closed range, the number of possible numbers we should generate is -/// `range = (high - low + 1)`. To avoid bias, we must ensure that the size of -/// our sample space, `zone`, is a multiple of `range`; other values must be -/// rejected (by replacing with a new random sample). -/// -/// As a special case, we use `range = 0` to represent the full range of the -/// result type (i.e. for `new_inclusive($ty::MIN, $ty::MAX)`). -/// -/// The optimum `zone` is the largest product of `range` which fits in our -/// (unsigned) target type. We calculate this by calculating how many numbers we -/// must reject: `reject = (MAX + 1) % range = (MAX - range + 1) % range`. Any (large) -/// product of `range` will suffice, thus in `sample_single` we multiply by a -/// power of 2 via bit-shifting (faster but may cause more rejections). -/// -/// The smallest integer PRNGs generate is `u32`. For 8- and 16-bit outputs we -/// use `u32` for our `zone` and samples (because it's not slower and because -/// it reduces the chance of having to reject a sample). In this case we cannot -/// store `zone` in the target type since it is too large, however we know -/// `ints_to_reject < range <= $unsigned::MAX`. -/// -/// An alternative to using a modulus is widening multiply: After a widening -/// multiply by `range`, the result is in the high word. Then comparing the low -/// word against `zone` makes sure our distribution is uniform. -#[derive(Clone, Copy, Debug)] -pub struct UniformInt { - low: X, - range: X, - z: X, // either ints_to_reject or zone depending on implementation -} - -macro_rules! uniform_int_impl { - ($ty:ty, $unsigned:ident, $u_large:ident) => { - impl SampleUniform for $ty { - type Sampler = UniformInt<$ty>; - } - - impl UniformSampler for UniformInt<$ty> { - // We play free and fast with unsigned vs signed here - // (when $ty is signed), but that's fine, since the - // contract of this macro is for $ty and $unsigned to be - // "bit-equal", so casting between them is a no-op. - - type X = $ty; - - #[inline] // if the range is constant, this helps LLVM to do the - // calculations at compile-time. - fn new(low_b: B1, high_b: B2) -> Self - where B1: SampleBorrow + Sized, - B2: SampleBorrow + Sized - { - let low = *low_b.borrow(); - let high = *high_b.borrow(); - assert!(low < high, "Uniform::new called with `low >= high`"); - UniformSampler::new_inclusive(low, high - 1) - } - - #[inline] // if the range is constant, this helps LLVM to do the - // calculations at compile-time. - fn new_inclusive(low_b: B1, high_b: B2) -> Self - where B1: SampleBorrow + Sized, - B2: SampleBorrow + Sized - { - let low = *low_b.borrow(); - let high = *high_b.borrow(); - assert!(low <= high, - "Uniform::new_inclusive called with `low > high`"); - let unsigned_max = ::core::$u_large::MAX; - - let range = high.wrapping_sub(low).wrapping_add(1) as $unsigned; - let ints_to_reject = - if range > 0 { - let range = $u_large::from(range); - (unsigned_max - range + 1) % range - } else { - 0 - }; - - UniformInt { - low: low, - // These are really $unsigned values, but store as $ty: - range: range as $ty, - z: ints_to_reject as $unsigned as $ty - } - } - - fn sample(&self, rng: &mut R) -> Self::X { - let range = self.range as $unsigned as $u_large; - if range > 0 { - let unsigned_max = ::core::$u_large::MAX; - let zone = unsigned_max - (self.z as $unsigned as $u_large); - loop { - let v: $u_large = rng.gen(); - let (hi, lo) = v.wmul(range); - if lo <= zone { - return self.low.wrapping_add(hi as $ty); - } - } - } else { - // Sample from the entire integer range. - rng.gen() - } - } - - fn sample_single(low_b: B1, high_b: B2, rng: &mut R) - -> Self::X - where B1: SampleBorrow + Sized, - B2: SampleBorrow + Sized - { - let low = *low_b.borrow(); - let high = *high_b.borrow(); - assert!(low < high, - "UniformSampler::sample_single: low >= high"); - let range = high.wrapping_sub(low) as $unsigned as $u_large; - let zone = - if ::core::$unsigned::MAX <= ::core::u16::MAX as $unsigned { - // Using a modulus is faster than the approximation for - // i8 and i16. I suppose we trade the cost of one - // modulus for near-perfect branch prediction. - let unsigned_max: $u_large = ::core::$u_large::MAX; - let ints_to_reject = (unsigned_max - range + 1) % range; - unsigned_max - ints_to_reject - } else { - // conservative but fast approximation. `- 1` is necessary to allow the - // same comparison without bias. - (range << range.leading_zeros()).wrapping_sub(1) - }; - - loop { - let v: $u_large = rng.gen(); - let (hi, lo) = v.wmul(range); - if lo <= zone { - return low.wrapping_add(hi as $ty); - } - } - } - } - } -} - -uniform_int_impl! { i8, u8, u32 } -uniform_int_impl! { i16, u16, u32 } -uniform_int_impl! { i32, u32, u32 } -uniform_int_impl! { i64, u64, u64 } -#[cfg(not(target_os = "emscripten"))] -uniform_int_impl! { i128, u128, u128 } -uniform_int_impl! { isize, usize, usize } -uniform_int_impl! { u8, u8, u32 } -uniform_int_impl! { u16, u16, u32 } -uniform_int_impl! { u32, u32, u32 } -uniform_int_impl! { u64, u64, u64 } -uniform_int_impl! { usize, usize, usize } -#[cfg(not(target_os = "emscripten"))] -uniform_int_impl! { u128, u128, u128 } - -#[cfg(all(feature = "simd_support", feature = "nightly"))] -macro_rules! uniform_simd_int_impl { - ($ty:ident, $unsigned:ident, $u_scalar:ident) => { - // The "pick the largest zone that can fit in an `u32`" optimization - // is less useful here. Multiple lanes complicate things, we don't - // know the PRNG's minimal output size, and casting to a larger vector - // is generally a bad idea for SIMD performance. The user can still - // implement it manually. - - // TODO: look into `Uniform::::new(0u32, 100)` functionality - // perhaps `impl SampleUniform for $u_scalar`? - impl SampleUniform for $ty { - type Sampler = UniformInt<$ty>; - } - - impl UniformSampler for UniformInt<$ty> { - type X = $ty; - - #[inline] // if the range is constant, this helps LLVM to do the - // calculations at compile-time. - fn new(low_b: B1, high_b: B2) -> Self - where B1: SampleBorrow + Sized, - B2: SampleBorrow + Sized - { - let low = *low_b.borrow(); - let high = *high_b.borrow(); - assert!(low.lt(high).all(), "Uniform::new called with `low >= high`"); - UniformSampler::new_inclusive(low, high - 1) - } - - #[inline] // if the range is constant, this helps LLVM to do the - // calculations at compile-time. - fn new_inclusive(low_b: B1, high_b: B2) -> Self - where B1: SampleBorrow + Sized, - B2: SampleBorrow + Sized - { - let low = *low_b.borrow(); - let high = *high_b.borrow(); - assert!(low.le(high).all(), - "Uniform::new_inclusive called with `low > high`"); - let unsigned_max = ::core::$u_scalar::MAX; - - // NOTE: these may need to be replaced with explicitly - // wrapping operations if `packed_simd` changes - let range: $unsigned = ((high - low) + 1).cast(); - // `% 0` will panic at runtime. - let not_full_range = range.gt($unsigned::splat(0)); - // replacing 0 with `unsigned_max` allows a faster `select` - // with bitwise OR - let modulo = not_full_range.select(range, $unsigned::splat(unsigned_max)); - // wrapping addition - let ints_to_reject = (unsigned_max - range + 1) % modulo; - // When `range` is 0, `lo` of `v.wmul(range)` will always be - // zero which means only one sample is needed. - let zone = unsigned_max - ints_to_reject; - - UniformInt { - low: low, - // These are really $unsigned values, but store as $ty: - range: range.cast(), - z: zone.cast(), - } - } - - fn sample(&self, rng: &mut R) -> Self::X { - let range: $unsigned = self.range.cast(); - let zone: $unsigned = self.z.cast(); - - // This might seem very slow, generating a whole new - // SIMD vector for every sample rejection. For most uses - // though, the chance of rejection is small and provides good - // general performance. With multiple lanes, that chance is - // multiplied. To mitigate this, we replace only the lanes of - // the vector which fail, iteratively reducing the chance of - // rejection. The replacement method does however add a little - // overhead. Benchmarking or calculating probabilities might - // reveal contexts where this replacement method is slower. - let mut v: $unsigned = rng.gen(); - loop { - let (hi, lo) = v.wmul(range); - let mask = lo.le(zone); - if mask.all() { - let hi: $ty = hi.cast(); - // wrapping addition - let result = self.low + hi; - // `select` here compiles to a blend operation - // When `range.eq(0).none()` the compare and blend - // operations are avoided. - let v: $ty = v.cast(); - return range.gt($unsigned::splat(0)).select(result, v); - } - // Replace only the failing lanes - v = mask.select(v, rng.gen()); - } - } - } - }; - - // bulk implementation - ($(($unsigned:ident, $signed:ident),)+ $u_scalar:ident) => { - $( - uniform_simd_int_impl!($unsigned, $unsigned, $u_scalar); - uniform_simd_int_impl!($signed, $unsigned, $u_scalar); - )+ - }; -} - -#[cfg(all(feature = "simd_support", feature = "nightly"))] -uniform_simd_int_impl! { - (u64x2, i64x2), - (u64x4, i64x4), - (u64x8, i64x8), - u64 -} - -#[cfg(all(feature = "simd_support", feature = "nightly"))] -uniform_simd_int_impl! { - (u32x2, i32x2), - (u32x4, i32x4), - (u32x8, i32x8), - (u32x16, i32x16), - u32 -} - -#[cfg(all(feature = "simd_support", feature = "nightly"))] -uniform_simd_int_impl! { - (u16x2, i16x2), - (u16x4, i16x4), - (u16x8, i16x8), - (u16x16, i16x16), - (u16x32, i16x32), - u16 -} - -#[cfg(all(feature = "simd_support", feature = "nightly"))] -uniform_simd_int_impl! { - (u8x2, i8x2), - (u8x4, i8x4), - (u8x8, i8x8), - (u8x16, i8x16), - (u8x32, i8x32), - (u8x64, i8x64), - u8 -} - - -/// The back-end implementing [`UniformSampler`] for floating-point types. -/// -/// Unless you are implementing [`UniformSampler`] for your own type, this type -/// should not be used directly, use [`Uniform`] instead. -/// -/// # Implementation notes -/// -/// Instead of generating a float in the `[0, 1)` range using [`Standard`], the -/// `UniformFloat` implementation converts the output of an PRNG itself. This -/// way one or two steps can be optimized out. -/// -/// The floats are first converted to a value in the `[1, 2)` interval using a -/// transmute-based method, and then mapped to the expected range with a -/// multiply and addition. Values produced this way have what equals 22 bits of -/// random digits for an `f32`, and 52 for an `f64`. -/// -/// [`new`]: UniformSampler::new -/// [`new_inclusive`]: UniformSampler::new_inclusive -/// [`Standard`]: crate::distributions::Standard -#[derive(Clone, Copy, Debug)] -pub struct UniformFloat { - low: X, - scale: X, -} - -macro_rules! uniform_float_impl { - ($ty:ty, $uty:ident, $f_scalar:ident, $u_scalar:ident, $bits_to_discard:expr) => { - impl SampleUniform for $ty { - type Sampler = UniformFloat<$ty>; - } - - impl UniformSampler for UniformFloat<$ty> { - type X = $ty; - - fn new(low_b: B1, high_b: B2) -> Self - where B1: SampleBorrow + Sized, - B2: SampleBorrow + Sized - { - let low = *low_b.borrow(); - let high = *high_b.borrow(); - assert!(low.all_lt(high), - "Uniform::new called with `low >= high`"); - assert!(low.all_finite() && high.all_finite(), - "Uniform::new called with non-finite boundaries"); - let max_rand = <$ty>::splat((::core::$u_scalar::MAX >> $bits_to_discard) - .into_float_with_exponent(0) - 1.0); - - let mut scale = high - low; - - loop { - let mask = (scale * max_rand + low).ge_mask(high); - if mask.none() { - break; - } - scale = scale.decrease_masked(mask); - } - - debug_assert!(<$ty>::splat(0.0).all_le(scale)); - - UniformFloat { low, scale } - } - - fn new_inclusive(low_b: B1, high_b: B2) -> Self - where B1: SampleBorrow + Sized, - B2: SampleBorrow + Sized - { - let low = *low_b.borrow(); - let high = *high_b.borrow(); - assert!(low.all_le(high), - "Uniform::new_inclusive called with `low > high`"); - assert!(low.all_finite() && high.all_finite(), - "Uniform::new_inclusive called with non-finite boundaries"); - let max_rand = <$ty>::splat((::core::$u_scalar::MAX >> $bits_to_discard) - .into_float_with_exponent(0) - 1.0); - - let mut scale = (high - low) / max_rand; - - loop { - let mask = (scale * max_rand + low).gt_mask(high); - if mask.none() { - break; - } - scale = scale.decrease_masked(mask); - } - - debug_assert!(<$ty>::splat(0.0).all_le(scale)); - - UniformFloat { low, scale } - } - - fn sample(&self, rng: &mut R) -> Self::X { - // Generate a value in the range [1, 2) - let value1_2 = (rng.gen::<$uty>() >> $bits_to_discard) - .into_float_with_exponent(0); - - // Get a value in the range [0, 1) in order to avoid - // overflowing into infinity when multiplying with scale - let value0_1 = value1_2 - 1.0; - - // We don't use `f64::mul_add`, because it is not available with - // `no_std`. Furthermore, it is slower for some targets (but - // faster for others). However, the order of multiplication and - // addition is important, because on some platforms (e.g. ARM) - // it will be optimized to a single (non-FMA) instruction. - value0_1 * self.scale + self.low - } - - #[inline] - fn sample_single(low_b: B1, high_b: B2, rng: &mut R) - -> Self::X - where B1: SampleBorrow + Sized, - B2: SampleBorrow + Sized - { - let low = *low_b.borrow(); - let high = *high_b.borrow(); - assert!(low.all_lt(high), - "UniformSampler::sample_single: low >= high"); - let mut scale = high - low; - - loop { - // Generate a value in the range [1, 2) - let value1_2 = (rng.gen::<$uty>() >> $bits_to_discard) - .into_float_with_exponent(0); - - // Get a value in the range [0, 1) in order to avoid - // overflowing into infinity when multiplying with scale - let value0_1 = value1_2 - 1.0; - - // Doing multiply before addition allows some architectures - // to use a single instruction. - let res = value0_1 * scale + low; - - debug_assert!(low.all_le(res) || !scale.all_finite()); - if res.all_lt(high) { - return res; - } - - // This handles a number of edge cases. - // * `low` or `high` is NaN. In this case `scale` and - // `res` are going to end up as NaN. - // * `low` is negative infinity and `high` is finite. - // `scale` is going to be infinite and `res` will be - // NaN. - // * `high` is positive infinity and `low` is finite. - // `scale` is going to be infinite and `res` will - // be infinite or NaN (if value0_1 is 0). - // * `low` is negative infinity and `high` is positive - // infinity. `scale` will be infinite and `res` will - // be NaN. - // * `low` and `high` are finite, but `high - low` - // overflows to infinite. `scale` will be infinite - // and `res` will be infinite or NaN (if value0_1 is 0). - // So if `high` or `low` are non-finite, we are guaranteed - // to fail the `res < high` check above and end up here. - // - // While we technically should check for non-finite `low` - // and `high` before entering the loop, by doing the checks - // here instead, we allow the common case to avoid these - // checks. But we are still guaranteed that if `low` or - // `high` are non-finite we'll end up here and can do the - // appropriate checks. - // - // Likewise `high - low` overflowing to infinity is also - // rare, so handle it here after the common case. - let mask = !scale.finite_mask(); - if mask.any() { - assert!(low.all_finite() && high.all_finite(), - "Uniform::sample_single: low and high must be finite"); - scale = scale.decrease_masked(mask); - } - } - } - } - } -} - -uniform_float_impl! { f32, u32, f32, u32, 32 - 23 } -uniform_float_impl! { f64, u64, f64, u64, 64 - 52 } - -#[cfg(feature="simd_support")] -uniform_float_impl! { f32x2, u32x2, f32, u32, 32 - 23 } -#[cfg(feature="simd_support")] -uniform_float_impl! { f32x4, u32x4, f32, u32, 32 - 23 } -#[cfg(feature="simd_support")] -uniform_float_impl! { f32x8, u32x8, f32, u32, 32 - 23 } -#[cfg(feature="simd_support")] -uniform_float_impl! { f32x16, u32x16, f32, u32, 32 - 23 } - -#[cfg(feature="simd_support")] -uniform_float_impl! { f64x2, u64x2, f64, u64, 64 - 52 } -#[cfg(feature="simd_support")] -uniform_float_impl! { f64x4, u64x4, f64, u64, 64 - 52 } -#[cfg(feature="simd_support")] -uniform_float_impl! { f64x8, u64x8, f64, u64, 64 - 52 } - - - -/// The back-end implementing [`UniformSampler`] for `Duration`. -/// -/// Unless you are implementing [`UniformSampler`] for your own types, this type -/// should not be used directly, use [`Uniform`] instead. -#[derive(Clone, Copy, Debug)] -pub struct UniformDuration { - mode: UniformDurationMode, - offset: u32, -} - -#[derive(Debug, Copy, Clone)] -enum UniformDurationMode { - Small { - secs: u64, - nanos: Uniform, - }, - Medium { - nanos: Uniform, - }, - Large { - max_secs: u64, - max_nanos: u32, - secs: Uniform, - } -} - -impl SampleUniform for Duration { - type Sampler = UniformDuration; -} - -impl UniformSampler for UniformDuration { - type X = Duration; - - #[inline] - fn new(low_b: B1, high_b: B2) -> Self - where B1: SampleBorrow + Sized, - B2: SampleBorrow + Sized - { - let low = *low_b.borrow(); - let high = *high_b.borrow(); - assert!(low < high, "Uniform::new called with `low >= high`"); - UniformDuration::new_inclusive(low, high - Duration::new(0, 1)) - } - - #[inline] - fn new_inclusive(low_b: B1, high_b: B2) -> Self - where B1: SampleBorrow + Sized, - B2: SampleBorrow + Sized - { - let low = *low_b.borrow(); - let high = *high_b.borrow(); - assert!(low <= high, "Uniform::new_inclusive called with `low > high`"); - - let low_s = low.as_secs(); - let low_n = low.subsec_nanos(); - let mut high_s = high.as_secs(); - let mut high_n = high.subsec_nanos(); - - if high_n < low_n { - high_s -= 1; - high_n += 1_000_000_000; - } - - let mode = if low_s == high_s { - UniformDurationMode::Small { - secs: low_s, - nanos: Uniform::new_inclusive(low_n, high_n), - } - } else { - let max = high_s - .checked_mul(1_000_000_000) - .and_then(|n| n.checked_add(u64::from(high_n))); - - if let Some(higher_bound) = max { - let lower_bound = low_s * 1_000_000_000 + u64::from(low_n); - UniformDurationMode::Medium { - nanos: Uniform::new_inclusive(lower_bound, higher_bound), - } - } else { - // An offset is applied to simplify generation of nanoseconds - let max_nanos = high_n - low_n; - UniformDurationMode::Large { - max_secs: high_s, - max_nanos, - secs: Uniform::new_inclusive(low_s, high_s), - } - } - }; - UniformDuration { - mode, - offset: low_n, - } - } - - #[inline] - fn sample(&self, rng: &mut R) -> Duration { - match self.mode { - UniformDurationMode::Small { secs, nanos } => { - let n = nanos.sample(rng); - Duration::new(secs, n) - } - UniformDurationMode::Medium { nanos } => { - let nanos = nanos.sample(rng); - Duration::new(nanos / 1_000_000_000, (nanos % 1_000_000_000) as u32) - } - UniformDurationMode::Large { max_secs, max_nanos, secs } => { - // constant folding means this is at least as fast as `gen_range` - let nano_range = Uniform::new(0, 1_000_000_000); - loop { - let s = secs.sample(rng); - let n = nano_range.sample(rng); - if !(s == max_secs && n > max_nanos) { - let sum = n + self.offset; - break Duration::new(s, sum); - } - } - } - } - } -} - -#[cfg(test)] -mod tests { - use crate::Rng; - use crate::rngs::mock::StepRng; - use crate::distributions::uniform::Uniform; - use crate::distributions::utils::FloatAsSIMD; - #[cfg(feature="simd_support")] use packed_simd::*; - - #[should_panic] - #[test] - fn test_uniform_bad_limits_equal_int() { - Uniform::new(10, 10); - } - - #[test] - fn test_uniform_good_limits_equal_int() { - let mut rng = crate::test::rng(804); - let dist = Uniform::new_inclusive(10, 10); - for _ in 0..20 { - assert_eq!(rng.sample(dist), 10); - } - } - - #[should_panic] - #[test] - fn test_uniform_bad_limits_flipped_int() { - Uniform::new(10, 5); - } - - #[test] - #[cfg(not(miri))] // Miri is too slow - fn test_integers() { - use core::{i8, i16, i32, i64, isize}; - use core::{u8, u16, u32, u64, usize}; - #[cfg(not(target_os = "emscripten"))] - use core::{i128, u128}; - - let mut rng = crate::test::rng(251); - macro_rules! t { - ($ty:ident, $v:expr, $le:expr, $lt:expr) => {{ - for &(low, high) in $v.iter() { - let my_uniform = Uniform::new(low, high); - for _ in 0..1000 { - let v: $ty = rng.sample(my_uniform); - assert!($le(low, v) && $lt(v, high)); - } - - let my_uniform = Uniform::new_inclusive(low, high); - for _ in 0..1000 { - let v: $ty = rng.sample(my_uniform); - assert!($le(low, v) && $le(v, high)); - } - - let my_uniform = Uniform::new(&low, high); - for _ in 0..1000 { - let v: $ty = rng.sample(my_uniform); - assert!($le(low, v) && $lt(v, high)); - } - - let my_uniform = Uniform::new_inclusive(&low, &high); - for _ in 0..1000 { - let v: $ty = rng.sample(my_uniform); - assert!($le(low, v) && $le(v, high)); - } - - for _ in 0..1000 { - let v: $ty = rng.gen_range(low, high); - assert!($le(low, v) && $lt(v, high)); - } - } - }}; - - // scalar bulk - ($($ty:ident),*) => {{ - $(t!( - $ty, - [(0, 10), (10, 127), ($ty::MIN, $ty::MAX)], - |x, y| x <= y, - |x, y| x < y - );)* - }}; - - // simd bulk - ($($ty:ident),* => $scalar:ident) => {{ - $(t!( - $ty, - [ - ($ty::splat(0), $ty::splat(10)), - ($ty::splat(10), $ty::splat(127)), - ($ty::splat($scalar::MIN), $ty::splat($scalar::MAX)), - ], - |x: $ty, y| x.le(y).all(), - |x: $ty, y| x.lt(y).all() - );)* - }}; - } - t!(i8, i16, i32, i64, isize, - u8, u16, u32, u64, usize); - #[cfg(not(target_os = "emscripten"))] - t!(i128, u128); - - #[cfg(all(feature = "simd_support", feature = "nightly"))] - { - t!(u8x2, u8x4, u8x8, u8x16, u8x32, u8x64 => u8); - t!(i8x2, i8x4, i8x8, i8x16, i8x32, i8x64 => i8); - t!(u16x2, u16x4, u16x8, u16x16, u16x32 => u16); - t!(i16x2, i16x4, i16x8, i16x16, i16x32 => i16); - t!(u32x2, u32x4, u32x8, u32x16 => u32); - t!(i32x2, i32x4, i32x8, i32x16 => i32); - t!(u64x2, u64x4, u64x8 => u64); - t!(i64x2, i64x4, i64x8 => i64); - } - } - - #[test] - #[cfg(not(miri))] // Miri is too slow - fn test_floats() { - let mut rng = crate::test::rng(252); - let mut zero_rng = StepRng::new(0, 0); - let mut max_rng = StepRng::new(0xffff_ffff_ffff_ffff, 0); - macro_rules! t { - ($ty:ty, $f_scalar:ident, $bits_shifted:expr) => {{ - let v: &[($f_scalar, $f_scalar)]= - &[(0.0, 100.0), - (-1e35, -1e25), - (1e-35, 1e-25), - (-1e35, 1e35), - (<$f_scalar>::from_bits(0), <$f_scalar>::from_bits(3)), - (-<$f_scalar>::from_bits(10), -<$f_scalar>::from_bits(1)), - (-<$f_scalar>::from_bits(5), 0.0), - (-<$f_scalar>::from_bits(7), -0.0), - (10.0, ::core::$f_scalar::MAX), - (-100.0, ::core::$f_scalar::MAX), - (-::core::$f_scalar::MAX / 5.0, ::core::$f_scalar::MAX), - (-::core::$f_scalar::MAX, ::core::$f_scalar::MAX / 5.0), - (-::core::$f_scalar::MAX * 0.8, ::core::$f_scalar::MAX * 0.7), - (-::core::$f_scalar::MAX, ::core::$f_scalar::MAX), - ]; - for &(low_scalar, high_scalar) in v.iter() { - for lane in 0..<$ty>::lanes() { - let low = <$ty>::splat(0.0 as $f_scalar).replace(lane, low_scalar); - let high = <$ty>::splat(1.0 as $f_scalar).replace(lane, high_scalar); - let my_uniform = Uniform::new(low, high); - let my_incl_uniform = Uniform::new_inclusive(low, high); - for _ in 0..100 { - let v = rng.sample(my_uniform).extract(lane); - assert!(low_scalar <= v && v < high_scalar); - let v = rng.sample(my_incl_uniform).extract(lane); - assert!(low_scalar <= v && v <= high_scalar); - let v = rng.gen_range(low, high).extract(lane); - assert!(low_scalar <= v && v < high_scalar); - } - - assert_eq!(rng.sample(Uniform::new_inclusive(low, low)).extract(lane), low_scalar); - - assert_eq!(zero_rng.sample(my_uniform).extract(lane), low_scalar); - assert_eq!(zero_rng.sample(my_incl_uniform).extract(lane), low_scalar); - assert_eq!(zero_rng.gen_range(low, high).extract(lane), low_scalar); - assert!(max_rng.sample(my_uniform).extract(lane) < high_scalar); - assert!(max_rng.sample(my_incl_uniform).extract(lane) <= high_scalar); - - // Don't run this test for really tiny differences between high and low - // since for those rounding might result in selecting high for a very - // long time. - if (high_scalar - low_scalar) > 0.0001 { - let mut lowering_max_rng = - StepRng::new(0xffff_ffff_ffff_ffff, - (-1i64 << $bits_shifted) as u64); - assert!(lowering_max_rng.gen_range(low, high).extract(lane) < high_scalar); - } - } - } - - assert_eq!(rng.sample(Uniform::new_inclusive(::core::$f_scalar::MAX, - ::core::$f_scalar::MAX)), - ::core::$f_scalar::MAX); - assert_eq!(rng.sample(Uniform::new_inclusive(-::core::$f_scalar::MAX, - -::core::$f_scalar::MAX)), - -::core::$f_scalar::MAX); - }} - } - - t!(f32, f32, 32 - 23); - t!(f64, f64, 64 - 52); - #[cfg(feature="simd_support")] - { - t!(f32x2, f32, 32 - 23); - t!(f32x4, f32, 32 - 23); - t!(f32x8, f32, 32 - 23); - t!(f32x16, f32, 32 - 23); - t!(f64x2, f64, 64 - 52); - t!(f64x4, f64, 64 - 52); - t!(f64x8, f64, 64 - 52); - } - } - - #[test] - #[cfg(all(feature="std", - not(target_arch = "wasm32"), - not(target_arch = "asmjs")))] - #[cfg(not(miri))] // Miri does not support catching panics - fn test_float_assertions() { - use std::panic::catch_unwind; - use super::SampleUniform; - fn range(low: T, high: T) { - let mut rng = crate::test::rng(253); - rng.gen_range(low, high); - } - - macro_rules! t { - ($ty:ident, $f_scalar:ident) => {{ - let v: &[($f_scalar, $f_scalar)] = - &[(::std::$f_scalar::NAN, 0.0), - (1.0, ::std::$f_scalar::NAN), - (::std::$f_scalar::NAN, ::std::$f_scalar::NAN), - (1.0, 0.5), - (::std::$f_scalar::MAX, -::std::$f_scalar::MAX), - (::std::$f_scalar::INFINITY, ::std::$f_scalar::INFINITY), - (::std::$f_scalar::NEG_INFINITY, ::std::$f_scalar::NEG_INFINITY), - (::std::$f_scalar::NEG_INFINITY, 5.0), - (5.0, ::std::$f_scalar::INFINITY), - (::std::$f_scalar::NAN, ::std::$f_scalar::INFINITY), - (::std::$f_scalar::NEG_INFINITY, ::std::$f_scalar::NAN), - (::std::$f_scalar::NEG_INFINITY, ::std::$f_scalar::INFINITY), - ]; - for &(low_scalar, high_scalar) in v.iter() { - for lane in 0..<$ty>::lanes() { - let low = <$ty>::splat(0.0 as $f_scalar).replace(lane, low_scalar); - let high = <$ty>::splat(1.0 as $f_scalar).replace(lane, high_scalar); - assert!(catch_unwind(|| range(low, high)).is_err()); - assert!(catch_unwind(|| Uniform::new(low, high)).is_err()); - assert!(catch_unwind(|| Uniform::new_inclusive(low, high)).is_err()); - assert!(catch_unwind(|| range(low, low)).is_err()); - assert!(catch_unwind(|| Uniform::new(low, low)).is_err()); - } - } - }} - } - - t!(f32, f32); - t!(f64, f64); - #[cfg(feature="simd_support")] - { - t!(f32x2, f32); - t!(f32x4, f32); - t!(f32x8, f32); - t!(f32x16, f32); - t!(f64x2, f64); - t!(f64x4, f64); - t!(f64x8, f64); - } - } - - - #[test] - #[cfg(not(miri))] // Miri is too slow - fn test_durations() { - #[cfg(feature = "std")] - use std::time::Duration; - #[cfg(not(feature = "std"))] - use core::time::Duration; - - let mut rng = crate::test::rng(253); - - let v = &[(Duration::new(10, 50000), Duration::new(100, 1234)), - (Duration::new(0, 100), Duration::new(1, 50)), - (Duration::new(0, 0), Duration::new(u64::max_value(), 999_999_999))]; - for &(low, high) in v.iter() { - let my_uniform = Uniform::new(low, high); - for _ in 0..1000 { - let v = rng.sample(my_uniform); - assert!(low <= v && v < high); - } - } - } - - #[test] - fn test_custom_uniform() { - use crate::distributions::uniform::{UniformSampler, UniformFloat, SampleUniform, SampleBorrow}; - #[derive(Clone, Copy, PartialEq, PartialOrd)] - struct MyF32 { - x: f32, - } - #[derive(Clone, Copy, Debug)] - struct UniformMyF32 { - inner: UniformFloat, - } - impl UniformSampler for UniformMyF32 { - type X = MyF32; - fn new(low: B1, high: B2) -> Self - where B1: SampleBorrow + Sized, - B2: SampleBorrow + Sized - { - UniformMyF32 { - inner: UniformFloat::::new(low.borrow().x, high.borrow().x), - } - } - fn new_inclusive(low: B1, high: B2) -> Self - where B1: SampleBorrow + Sized, - B2: SampleBorrow + Sized - { - UniformSampler::new(low, high) - } - fn sample(&self, rng: &mut R) -> Self::X { - MyF32 { x: self.inner.sample(rng) } - } - } - impl SampleUniform for MyF32 { - type Sampler = UniformMyF32; - } - - let (low, high) = (MyF32{ x: 17.0f32 }, MyF32{ x: 22.0f32 }); - let uniform = Uniform::new(low, high); - let mut rng = crate::test::rng(804); - for _ in 0..100 { - let x: MyF32 = rng.sample(uniform); - assert!(low <= x && x < high); - } - } - - #[test] - fn test_uniform_from_std_range() { - let r = Uniform::from(2u32..7); - assert_eq!(r.inner.low, 2); - assert_eq!(r.inner.range, 5); - let r = Uniform::from(2.0f64..7.0); - assert_eq!(r.inner.low, 2.0); - assert_eq!(r.inner.scale, 5.0); - } - - #[test] - fn test_uniform_from_std_range_inclusive() { - let r = Uniform::from(2u32..=6); - assert_eq!(r.inner.low, 2); - assert_eq!(r.inner.range, 5); - let r = Uniform::from(2.0f64..=7.0); - assert_eq!(r.inner.low, 2.0); - assert!(r.inner.scale > 5.0); - assert!(r.inner.scale < 5.0 + 1e-14); - } -} diff --git a/rand/src/distributions/unit_circle.rs b/rand/src/distributions/unit_circle.rs deleted file mode 100644 index 56e75b6..0000000 --- a/rand/src/distributions/unit_circle.rs +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#![allow(deprecated)] -#![allow(clippy::all)] - -use crate::Rng; -use crate::distributions::{Distribution, Uniform}; - -/// Samples uniformly from the edge of the unit circle in two dimensions. -/// -/// Implemented via a method by von Neumann[^1]. -/// -/// [^1]: von Neumann, J. (1951) [*Various Techniques Used in Connection with -/// Random Digits.*](https://mcnp.lanl.gov/pdf_files/nbs_vonneumann.pdf) -/// NBS Appl. Math. Ser., No. 12. Washington, DC: U.S. Government Printing -/// Office, pp. 36-38. -#[deprecated(since="0.7.0", note="moved to rand_distr crate")] -#[derive(Clone, Copy, Debug)] -pub struct UnitCircle; - -impl UnitCircle { - /// Construct a new `UnitCircle` distribution. - #[inline] - pub fn new() -> UnitCircle { - UnitCircle - } -} - -impl Distribution<[f64; 2]> for UnitCircle { - #[inline] - fn sample(&self, rng: &mut R) -> [f64; 2] { - let uniform = Uniform::new(-1., 1.); - let mut x1; - let mut x2; - let mut sum; - loop { - x1 = uniform.sample(rng); - x2 = uniform.sample(rng); - sum = x1*x1 + x2*x2; - if sum < 1. { - break; - } - } - let diff = x1*x1 - x2*x2; - [diff / sum, 2.*x1*x2 / sum] - } -} - -#[cfg(test)] -mod tests { - use crate::distributions::Distribution; - use super::UnitCircle; - - /// Assert that two numbers are almost equal to each other. - /// - /// On panic, this macro will print the values of the expressions with their - /// debug representations. - macro_rules! assert_almost_eq { - ($a:expr, $b:expr, $prec:expr) => ( - let diff = ($a - $b).abs(); - if diff > $prec { - panic!(format!( - "assertion failed: `abs(left - right) = {:.1e} < {:e}`, \ - (left: `{}`, right: `{}`)", - diff, $prec, $a, $b)); - } - ); - } - - #[test] - fn norm() { - let mut rng = crate::test::rng(1); - let dist = UnitCircle::new(); - for _ in 0..1000 { - let x = dist.sample(&mut rng); - assert_almost_eq!(x[0]*x[0] + x[1]*x[1], 1., 1e-15); - } - } - - #[test] - fn value_stability() { - let mut rng = crate::test::rng(2); - let expected = [ - [-0.9965658683520504, -0.08280380447614634], - [-0.9790853270389644, -0.20345004884984505], - [-0.8449189758898707, 0.5348943112253227], - ]; - let samples = [ - UnitCircle.sample(&mut rng), - UnitCircle.sample(&mut rng), - UnitCircle.sample(&mut rng), - ]; - assert_eq!(samples, expected); - } -} diff --git a/rand/src/distributions/unit_sphere.rs b/rand/src/distributions/unit_sphere.rs deleted file mode 100644 index 188f48c..0000000 --- a/rand/src/distributions/unit_sphere.rs +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#![allow(deprecated)] -#![allow(clippy::all)] - -use crate::Rng; -use crate::distributions::{Distribution, Uniform}; - -/// Samples uniformly from the surface of the unit sphere in three dimensions. -/// -/// Implemented via a method by Marsaglia[^1]. -/// -/// [^1]: Marsaglia, George (1972). [*Choosing a Point from the Surface of a -/// Sphere.*](https://doi.org/10.1214/aoms/1177692644) -/// Ann. Math. Statist. 43, no. 2, 645--646. -#[deprecated(since="0.7.0", note="moved to rand_distr crate")] -#[derive(Clone, Copy, Debug)] -pub struct UnitSphereSurface; - -impl UnitSphereSurface { - /// Construct a new `UnitSphereSurface` distribution. - #[inline] - pub fn new() -> UnitSphereSurface { - UnitSphereSurface - } -} - -impl Distribution<[f64; 3]> for UnitSphereSurface { - #[inline] - fn sample(&self, rng: &mut R) -> [f64; 3] { - let uniform = Uniform::new(-1., 1.); - loop { - let (x1, x2) = (uniform.sample(rng), uniform.sample(rng)); - let sum = x1*x1 + x2*x2; - if sum >= 1. { - continue; - } - let factor = 2. * (1.0_f64 - sum).sqrt(); - return [x1 * factor, x2 * factor, 1. - 2.*sum]; - } - } -} - -#[cfg(test)] -mod tests { - use crate::distributions::Distribution; - use super::UnitSphereSurface; - - /// Assert that two numbers are almost equal to each other. - /// - /// On panic, this macro will print the values of the expressions with their - /// debug representations. - macro_rules! assert_almost_eq { - ($a:expr, $b:expr, $prec:expr) => ( - let diff = ($a - $b).abs(); - if diff > $prec { - panic!(format!( - "assertion failed: `abs(left - right) = {:.1e} < {:e}`, \ - (left: `{}`, right: `{}`)", - diff, $prec, $a, $b)); - } - ); - } - - #[test] - fn norm() { - let mut rng = crate::test::rng(1); - let dist = UnitSphereSurface::new(); - for _ in 0..1000 { - let x = dist.sample(&mut rng); - assert_almost_eq!(x[0]*x[0] + x[1]*x[1] + x[2]*x[2], 1., 1e-15); - } - } - - #[test] - fn value_stability() { - let mut rng = crate::test::rng(2); - let expected = [ - [0.03247542860231647, -0.7830477442152738, 0.6211131755296027], - [-0.09978440840914075, 0.9706650829833128, -0.21875184231323952], - [0.2735582468624679, 0.9435374242279655, -0.1868234852870203], - ]; - let samples = [ - UnitSphereSurface.sample(&mut rng), - UnitSphereSurface.sample(&mut rng), - UnitSphereSurface.sample(&mut rng), - ]; - assert_eq!(samples, expected); - } -} diff --git a/rand/src/distributions/utils.rs b/rand/src/distributions/utils.rs deleted file mode 100644 index 3af4e86..0000000 --- a/rand/src/distributions/utils.rs +++ /dev/null @@ -1,488 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Math helper functions - -#[cfg(feature="simd_support")] -use packed_simd::*; -#[cfg(feature="std")] -use crate::distributions::ziggurat_tables; -#[cfg(feature="std")] -use crate::Rng; - - -pub trait WideningMultiply { - type Output; - - fn wmul(self, x: RHS) -> Self::Output; -} - -macro_rules! wmul_impl { - ($ty:ty, $wide:ty, $shift:expr) => { - impl WideningMultiply for $ty { - type Output = ($ty, $ty); - - #[inline(always)] - fn wmul(self, x: $ty) -> Self::Output { - let tmp = (self as $wide) * (x as $wide); - ((tmp >> $shift) as $ty, tmp as $ty) - } - } - }; - - // simd bulk implementation - ($(($ty:ident, $wide:ident),)+, $shift:expr) => { - $( - impl WideningMultiply for $ty { - type Output = ($ty, $ty); - - #[inline(always)] - fn wmul(self, x: $ty) -> Self::Output { - // For supported vectors, this should compile to a couple - // supported multiply & swizzle instructions (no actual - // casting). - // TODO: optimize - let y: $wide = self.cast(); - let x: $wide = x.cast(); - let tmp = y * x; - let hi: $ty = (tmp >> $shift).cast(); - let lo: $ty = tmp.cast(); - (hi, lo) - } - } - )+ - }; -} -wmul_impl! { u8, u16, 8 } -wmul_impl! { u16, u32, 16 } -wmul_impl! { u32, u64, 32 } -#[cfg(not(target_os = "emscripten"))] -wmul_impl! { u64, u128, 64 } - -// This code is a translation of the __mulddi3 function in LLVM's -// compiler-rt. It is an optimised variant of the common method -// `(a + b) * (c + d) = ac + ad + bc + bd`. -// -// For some reason LLVM can optimise the C version very well, but -// keeps shuffling registers in this Rust translation. -macro_rules! wmul_impl_large { - ($ty:ty, $half:expr) => { - impl WideningMultiply for $ty { - type Output = ($ty, $ty); - - #[inline(always)] - fn wmul(self, b: $ty) -> Self::Output { - const LOWER_MASK: $ty = !0 >> $half; - let mut low = (self & LOWER_MASK).wrapping_mul(b & LOWER_MASK); - let mut t = low >> $half; - low &= LOWER_MASK; - t += (self >> $half).wrapping_mul(b & LOWER_MASK); - low += (t & LOWER_MASK) << $half; - let mut high = t >> $half; - t = low >> $half; - low &= LOWER_MASK; - t += (b >> $half).wrapping_mul(self & LOWER_MASK); - low += (t & LOWER_MASK) << $half; - high += t >> $half; - high += (self >> $half).wrapping_mul(b >> $half); - - (high, low) - } - } - }; - - // simd bulk implementation - (($($ty:ty,)+) $scalar:ty, $half:expr) => { - $( - impl WideningMultiply for $ty { - type Output = ($ty, $ty); - - #[inline(always)] - fn wmul(self, b: $ty) -> Self::Output { - // needs wrapping multiplication - const LOWER_MASK: $scalar = !0 >> $half; - let mut low = (self & LOWER_MASK) * (b & LOWER_MASK); - let mut t = low >> $half; - low &= LOWER_MASK; - t += (self >> $half) * (b & LOWER_MASK); - low += (t & LOWER_MASK) << $half; - let mut high = t >> $half; - t = low >> $half; - low &= LOWER_MASK; - t += (b >> $half) * (self & LOWER_MASK); - low += (t & LOWER_MASK) << $half; - high += t >> $half; - high += (self >> $half) * (b >> $half); - - (high, low) - } - } - )+ - }; -} -#[cfg(target_os = "emscripten")] -wmul_impl_large! { u64, 32 } -#[cfg(not(target_os = "emscripten"))] -wmul_impl_large! { u128, 64 } - -macro_rules! wmul_impl_usize { - ($ty:ty) => { - impl WideningMultiply for usize { - type Output = (usize, usize); - - #[inline(always)] - fn wmul(self, x: usize) -> Self::Output { - let (high, low) = (self as $ty).wmul(x as $ty); - (high as usize, low as usize) - } - } - } -} -#[cfg(target_pointer_width = "32")] -wmul_impl_usize! { u32 } -#[cfg(target_pointer_width = "64")] -wmul_impl_usize! { u64 } - -#[cfg(all(feature = "simd_support", feature = "nightly"))] -mod simd_wmul { - #[cfg(target_arch = "x86")] - use core::arch::x86::*; - #[cfg(target_arch = "x86_64")] - use core::arch::x86_64::*; - use super::*; - - wmul_impl! { - (u8x2, u16x2), - (u8x4, u16x4), - (u8x8, u16x8), - (u8x16, u16x16), - (u8x32, u16x32),, - 8 - } - - wmul_impl! { (u16x2, u32x2),, 16 } - #[cfg(not(target_feature = "sse2"))] - wmul_impl! { (u16x4, u32x4),, 16 } - #[cfg(not(target_feature = "sse4.2"))] - wmul_impl! { (u16x8, u32x8),, 16 } - #[cfg(not(target_feature = "avx2"))] - wmul_impl! { (u16x16, u32x16),, 16 } - - // 16-bit lane widths allow use of the x86 `mulhi` instructions, which - // means `wmul` can be implemented with only two instructions. - #[allow(unused_macros)] - macro_rules! wmul_impl_16 { - ($ty:ident, $intrinsic:ident, $mulhi:ident, $mullo:ident) => { - impl WideningMultiply for $ty { - type Output = ($ty, $ty); - - #[inline(always)] - fn wmul(self, x: $ty) -> Self::Output { - let b = $intrinsic::from_bits(x); - let a = $intrinsic::from_bits(self); - let hi = $ty::from_bits(unsafe { $mulhi(a, b) }); - let lo = $ty::from_bits(unsafe { $mullo(a, b) }); - (hi, lo) - } - } - }; - } - - #[cfg(target_feature = "sse2")] - wmul_impl_16! { u16x4, __m64, _mm_mulhi_pu16, _mm_mullo_pi16 } - #[cfg(target_feature = "sse4.2")] - wmul_impl_16! { u16x8, __m128i, _mm_mulhi_epu16, _mm_mullo_epi16 } - #[cfg(target_feature = "avx2")] - wmul_impl_16! { u16x16, __m256i, _mm256_mulhi_epu16, _mm256_mullo_epi16 } - // FIXME: there are no `__m512i` types in stdsimd yet, so `wmul::` - // cannot use the same implementation. - - wmul_impl! { - (u32x2, u64x2), - (u32x4, u64x4), - (u32x8, u64x8),, - 32 - } - - // TODO: optimize, this seems to seriously slow things down - wmul_impl_large! { (u8x64,) u8, 4 } - wmul_impl_large! { (u16x32,) u16, 8 } - wmul_impl_large! { (u32x16,) u32, 16 } - wmul_impl_large! { (u64x2, u64x4, u64x8,) u64, 32 } -} -#[cfg(all(feature = "simd_support", feature = "nightly"))] -pub use self::simd_wmul::*; - - -/// Helper trait when dealing with scalar and SIMD floating point types. -pub(crate) trait FloatSIMDUtils { - // `PartialOrd` for vectors compares lexicographically. We want to compare all - // the individual SIMD lanes instead, and get the combined result over all - // lanes. This is possible using something like `a.lt(b).all()`, but we - // implement it as a trait so we can write the same code for `f32` and `f64`. - // Only the comparison functions we need are implemented. - fn all_lt(self, other: Self) -> bool; - fn all_le(self, other: Self) -> bool; - fn all_finite(self) -> bool; - - type Mask; - fn finite_mask(self) -> Self::Mask; - fn gt_mask(self, other: Self) -> Self::Mask; - fn ge_mask(self, other: Self) -> Self::Mask; - - // Decrease all lanes where the mask is `true` to the next lower value - // representable by the floating-point type. At least one of the lanes - // must be set. - fn decrease_masked(self, mask: Self::Mask) -> Self; - - // Convert from int value. Conversion is done while retaining the numerical - // value, not by retaining the binary representation. - type UInt; - fn cast_from_int(i: Self::UInt) -> Self; -} - -/// Implement functions available in std builds but missing from core primitives -#[cfg(not(std))] -pub(crate) trait Float : Sized { - fn is_nan(self) -> bool; - fn is_infinite(self) -> bool; - fn is_finite(self) -> bool; -} - -/// Implement functions on f32/f64 to give them APIs similar to SIMD types -pub(crate) trait FloatAsSIMD : Sized { - #[inline(always)] - fn lanes() -> usize { 1 } - #[inline(always)] - fn splat(scalar: Self) -> Self { scalar } - #[inline(always)] - fn extract(self, index: usize) -> Self { debug_assert_eq!(index, 0); self } - #[inline(always)] - fn replace(self, index: usize, new_value: Self) -> Self { debug_assert_eq!(index, 0); new_value } -} - -pub(crate) trait BoolAsSIMD : Sized { - fn any(self) -> bool; - fn all(self) -> bool; - fn none(self) -> bool; -} - -impl BoolAsSIMD for bool { - #[inline(always)] - fn any(self) -> bool { self } - #[inline(always)] - fn all(self) -> bool { self } - #[inline(always)] - fn none(self) -> bool { !self } -} - -macro_rules! scalar_float_impl { - ($ty:ident, $uty:ident) => { - #[cfg(not(std))] - impl Float for $ty { - #[inline] - fn is_nan(self) -> bool { - self != self - } - - #[inline] - fn is_infinite(self) -> bool { - self == ::core::$ty::INFINITY || self == ::core::$ty::NEG_INFINITY - } - - #[inline] - fn is_finite(self) -> bool { - !(self.is_nan() || self.is_infinite()) - } - } - - impl FloatSIMDUtils for $ty { - type Mask = bool; - #[inline(always)] - fn all_lt(self, other: Self) -> bool { self < other } - #[inline(always)] - fn all_le(self, other: Self) -> bool { self <= other } - #[inline(always)] - fn all_finite(self) -> bool { self.is_finite() } - #[inline(always)] - fn finite_mask(self) -> Self::Mask { self.is_finite() } - #[inline(always)] - fn gt_mask(self, other: Self) -> Self::Mask { self > other } - #[inline(always)] - fn ge_mask(self, other: Self) -> Self::Mask { self >= other } - #[inline(always)] - fn decrease_masked(self, mask: Self::Mask) -> Self { - debug_assert!(mask, "At least one lane must be set"); - <$ty>::from_bits(self.to_bits() - 1) - } - type UInt = $uty; - fn cast_from_int(i: Self::UInt) -> Self { i as $ty } - } - - impl FloatAsSIMD for $ty {} - } -} - -scalar_float_impl!(f32, u32); -scalar_float_impl!(f64, u64); - - -#[cfg(feature="simd_support")] -macro_rules! simd_impl { - ($ty:ident, $f_scalar:ident, $mty:ident, $uty:ident) => { - impl FloatSIMDUtils for $ty { - type Mask = $mty; - #[inline(always)] - fn all_lt(self, other: Self) -> bool { self.lt(other).all() } - #[inline(always)] - fn all_le(self, other: Self) -> bool { self.le(other).all() } - #[inline(always)] - fn all_finite(self) -> bool { self.finite_mask().all() } - #[inline(always)] - fn finite_mask(self) -> Self::Mask { - // This can possibly be done faster by checking bit patterns - let neg_inf = $ty::splat(::core::$f_scalar::NEG_INFINITY); - let pos_inf = $ty::splat(::core::$f_scalar::INFINITY); - self.gt(neg_inf) & self.lt(pos_inf) - } - #[inline(always)] - fn gt_mask(self, other: Self) -> Self::Mask { self.gt(other) } - #[inline(always)] - fn ge_mask(self, other: Self) -> Self::Mask { self.ge(other) } - #[inline(always)] - fn decrease_masked(self, mask: Self::Mask) -> Self { - // Casting a mask into ints will produce all bits set for - // true, and 0 for false. Adding that to the binary - // representation of a float means subtracting one from - // the binary representation, resulting in the next lower - // value representable by $ty. This works even when the - // current value is infinity. - debug_assert!(mask.any(), "At least one lane must be set"); - <$ty>::from_bits(<$uty>::from_bits(self) + <$uty>::from_bits(mask)) - } - type UInt = $uty; - #[inline] - fn cast_from_int(i: Self::UInt) -> Self { i.cast() } - } - } -} - -#[cfg(feature="simd_support")] simd_impl! { f32x2, f32, m32x2, u32x2 } -#[cfg(feature="simd_support")] simd_impl! { f32x4, f32, m32x4, u32x4 } -#[cfg(feature="simd_support")] simd_impl! { f32x8, f32, m32x8, u32x8 } -#[cfg(feature="simd_support")] simd_impl! { f32x16, f32, m32x16, u32x16 } -#[cfg(feature="simd_support")] simd_impl! { f64x2, f64, m64x2, u64x2 } -#[cfg(feature="simd_support")] simd_impl! { f64x4, f64, m64x4, u64x4 } -#[cfg(feature="simd_support")] simd_impl! { f64x8, f64, m64x8, u64x8 } - -/// Calculates ln(gamma(x)) (natural logarithm of the gamma -/// function) using the Lanczos approximation. -/// -/// The approximation expresses the gamma function as: -/// `gamma(z+1) = sqrt(2*pi)*(z+g+0.5)^(z+0.5)*exp(-z-g-0.5)*Ag(z)` -/// `g` is an arbitrary constant; we use the approximation with `g=5`. -/// -/// Noting that `gamma(z+1) = z*gamma(z)` and applying `ln` to both sides: -/// `ln(gamma(z)) = (z+0.5)*ln(z+g+0.5)-(z+g+0.5) + ln(sqrt(2*pi)*Ag(z)/z)` -/// -/// `Ag(z)` is an infinite series with coefficients that can be calculated -/// ahead of time - we use just the first 6 terms, which is good enough -/// for most purposes. -#[cfg(feature="std")] -pub fn log_gamma(x: f64) -> f64 { - // precalculated 6 coefficients for the first 6 terms of the series - let coefficients: [f64; 6] = [ - 76.18009172947146, - -86.50532032941677, - 24.01409824083091, - -1.231739572450155, - 0.1208650973866179e-2, - -0.5395239384953e-5, - ]; - - // (x+0.5)*ln(x+g+0.5)-(x+g+0.5) - let tmp = x + 5.5; - let log = (x + 0.5) * tmp.ln() - tmp; - - // the first few terms of the series for Ag(x) - let mut a = 1.000000000190015; - let mut denom = x; - for coeff in &coefficients { - denom += 1.0; - a += coeff / denom; - } - - // get everything together - // a is Ag(x) - // 2.5066... is sqrt(2pi) - log + (2.5066282746310005 * a / x).ln() -} - -/// Sample a random number using the Ziggurat method (specifically the -/// ZIGNOR variant from Doornik 2005). Most of the arguments are -/// directly from the paper: -/// -/// * `rng`: source of randomness -/// * `symmetric`: whether this is a symmetric distribution, or one-sided with P(x < 0) = 0. -/// * `X`: the $x_i$ abscissae. -/// * `F`: precomputed values of the PDF at the $x_i$, (i.e. $f(x_i)$) -/// * `F_DIFF`: precomputed values of $f(x_i) - f(x_{i+1})$ -/// * `pdf`: the probability density function -/// * `zero_case`: manual sampling from the tail when we chose the -/// bottom box (i.e. i == 0) - -// the perf improvement (25-50%) is definitely worth the extra code -// size from force-inlining. -#[cfg(feature="std")] -#[inline(always)] -pub fn ziggurat( - rng: &mut R, - symmetric: bool, - x_tab: ziggurat_tables::ZigTable, - f_tab: ziggurat_tables::ZigTable, - mut pdf: P, - mut zero_case: Z) - -> f64 where P: FnMut(f64) -> f64, Z: FnMut(&mut R, f64) -> f64 { - use crate::distributions::float::IntoFloat; - loop { - // As an optimisation we re-implement the conversion to a f64. - // From the remaining 12 most significant bits we use 8 to construct `i`. - // This saves us generating a whole extra random number, while the added - // precision of using 64 bits for f64 does not buy us much. - let bits = rng.next_u64(); - let i = bits as usize & 0xff; - - let u = if symmetric { - // Convert to a value in the range [2,4) and substract to get [-1,1) - // We can't convert to an open range directly, that would require - // substracting `3.0 - EPSILON`, which is not representable. - // It is possible with an extra step, but an open range does not - // seem neccesary for the ziggurat algorithm anyway. - (bits >> 12).into_float_with_exponent(1) - 3.0 - } else { - // Convert to a value in the range [1,2) and substract to get (0,1) - (bits >> 12).into_float_with_exponent(0) - - (1.0 - ::core::f64::EPSILON / 2.0) - }; - let x = u * x_tab[i]; - - let test_x = if symmetric { x.abs() } else {x}; - - // algebraically equivalent to |u| < x_tab[i+1]/x_tab[i] (or u < x_tab[i+1]/x_tab[i]) - if test_x < x_tab[i + 1] { - return x; - } - if i == 0 { - return zero_case(rng, u); - } - // algebraically equivalent to f1 + DRanU()*(f0 - f1) < 1 - if f_tab[i + 1] + (f_tab[i] - f_tab[i + 1]) * rng.gen::() < pdf(x) { - return x; - } - } -} diff --git a/rand/src/distributions/weibull.rs b/rand/src/distributions/weibull.rs deleted file mode 100644 index 483714f..0000000 --- a/rand/src/distributions/weibull.rs +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The Weibull distribution. -#![allow(deprecated)] - -use crate::Rng; -use crate::distributions::{Distribution, OpenClosed01}; - -/// Samples floating-point numbers according to the Weibull distribution -#[deprecated(since="0.7.0", note="moved to rand_distr crate")] -#[derive(Clone, Copy, Debug)] -pub struct Weibull { - inv_shape: f64, - scale: f64, -} - -impl Weibull { - /// Construct a new `Weibull` distribution with given `scale` and `shape`. - /// - /// # Panics - /// - /// `scale` and `shape` have to be non-zero and positive. - pub fn new(scale: f64, shape: f64) -> Weibull { - assert!((scale > 0.) & (shape > 0.)); - Weibull { inv_shape: 1./shape, scale } - } -} - -impl Distribution for Weibull { - fn sample(&self, rng: &mut R) -> f64 { - let x: f64 = rng.sample(OpenClosed01); - self.scale * (-x.ln()).powf(self.inv_shape) - } -} - -#[cfg(test)] -mod tests { - use crate::distributions::Distribution; - use super::Weibull; - - #[test] - #[should_panic] - fn invalid() { - Weibull::new(0., 0.); - } - - #[test] - fn sample() { - let scale = 1.0; - let shape = 2.0; - let d = Weibull::new(scale, shape); - let mut rng = crate::test::rng(1); - for _ in 0..1000 { - let r = d.sample(&mut rng); - assert!(r >= 0.); - } - } -} diff --git a/rand/src/distributions/weighted/alias_method.rs b/rand/src/distributions/weighted/alias_method.rs deleted file mode 100644 index bdd4ba0..0000000 --- a/rand/src/distributions/weighted/alias_method.rs +++ /dev/null @@ -1,499 +0,0 @@ -//! This module contains an implementation of alias method for sampling random -//! indices with probabilities proportional to a collection of weights. - -use super::WeightedError; -#[cfg(not(feature = "std"))] -use crate::alloc::vec::Vec; -#[cfg(not(feature = "std"))] -use crate::alloc::vec; -use core::fmt; -use core::iter::Sum; -use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign}; -use crate::distributions::uniform::SampleUniform; -use crate::distributions::Distribution; -use crate::distributions::Uniform; -use crate::Rng; - -/// A distribution using weighted sampling to pick a discretely selected item. -/// -/// Sampling a [`WeightedIndex`] distribution returns the index of a randomly -/// selected element from the vector used to create the [`WeightedIndex`]. -/// The chance of a given element being picked is proportional to the value of -/// the element. The weights can have any type `W` for which a implementation of -/// [`Weight`] exists. -/// -/// # Performance -/// -/// Given that `n` is the number of items in the vector used to create an -/// [`WeightedIndex`], [`WeightedIndex`] will require `O(n)` amount of -/// memory. More specifically it takes up some constant amount of memory plus -/// the vector used to create it and a [`Vec`] with capacity `n`. -/// -/// Time complexity for the creation of a [`WeightedIndex`] is `O(n)`. -/// Sampling is `O(1)`, it makes a call to [`Uniform::sample`] and a call -/// to [`Uniform::sample`]. -/// -/// # Example -/// -/// ``` -/// use rand::distributions::weighted::alias_method::WeightedIndex; -/// use rand::prelude::*; -/// -/// let choices = vec!['a', 'b', 'c']; -/// let weights = vec![2, 1, 1]; -/// let dist = WeightedIndex::new(weights).unwrap(); -/// let mut rng = thread_rng(); -/// for _ in 0..100 { -/// // 50% chance to print 'a', 25% chance to print 'b', 25% chance to print 'c' -/// println!("{}", choices[dist.sample(&mut rng)]); -/// } -/// -/// let items = [('a', 0), ('b', 3), ('c', 7)]; -/// let dist2 = WeightedIndex::new(items.iter().map(|item| item.1).collect()).unwrap(); -/// for _ in 0..100 { -/// // 0% chance to print 'a', 30% chance to print 'b', 70% chance to print 'c' -/// println!("{}", items[dist2.sample(&mut rng)].0); -/// } -/// ``` -/// -/// [`WeightedIndex`]: crate::distributions::weighted::alias_method::WeightedIndex -/// [`Weight`]: crate::distributions::weighted::alias_method::Weight -/// [`Vec`]: Vec -/// [`Uniform::sample`]: Distribution::sample -/// [`Uniform::sample`]: Distribution::sample -pub struct WeightedIndex { - aliases: Vec, - no_alias_odds: Vec, - uniform_index: Uniform, - uniform_within_weight_sum: Uniform, -} - -impl WeightedIndex { - /// Creates a new [`WeightedIndex`]. - /// - /// Returns an error if: - /// - The vector is empty. - /// - The vector is longer than `u32::MAX`. - /// - For any weight `w`: `w < 0` or `w > max` where `max = W::MAX / - /// weights.len()`. - /// - The sum of weights is zero. - pub fn new(weights: Vec) -> Result { - let n = weights.len(); - if n == 0 { - return Err(WeightedError::NoItem); - } else if n > ::core::u32::MAX as usize { - return Err(WeightedError::TooMany); - } - let n = n as u32; - - let max_weight_size = W::try_from_u32_lossy(n) - .map(|n| W::MAX / n) - .unwrap_or(W::ZERO); - if !weights - .iter() - .all(|&w| W::ZERO <= w && w <= max_weight_size) - { - return Err(WeightedError::InvalidWeight); - } - - // The sum of weights will represent 100% of no alias odds. - let weight_sum = Weight::sum(weights.as_slice()); - // Prevent floating point overflow due to rounding errors. - let weight_sum = if weight_sum > W::MAX { - W::MAX - } else { - weight_sum - }; - if weight_sum == W::ZERO { - return Err(WeightedError::AllWeightsZero); - } - - // `weight_sum` would have been zero if `try_from_lossy` causes an error here. - let n_converted = W::try_from_u32_lossy(n).unwrap(); - - let mut no_alias_odds = weights; - for odds in no_alias_odds.iter_mut() { - *odds *= n_converted; - // Prevent floating point overflow due to rounding errors. - *odds = if *odds > W::MAX { W::MAX } else { *odds }; - } - - /// This struct is designed to contain three data structures at once, - /// sharing the same memory. More precisely it contains two linked lists - /// and an alias map, which will be the output of this method. To keep - /// the three data structures from getting in each other's way, it must - /// be ensured that a single index is only ever in one of them at the - /// same time. - struct Aliases { - aliases: Vec, - smalls_head: u32, - bigs_head: u32, - } - - impl Aliases { - fn new(size: u32) -> Self { - Aliases { - aliases: vec![0; size as usize], - smalls_head: ::core::u32::MAX, - bigs_head: ::core::u32::MAX, - } - } - - fn push_small(&mut self, idx: u32) { - self.aliases[idx as usize] = self.smalls_head; - self.smalls_head = idx; - } - - fn push_big(&mut self, idx: u32) { - self.aliases[idx as usize] = self.bigs_head; - self.bigs_head = idx; - } - - fn pop_small(&mut self) -> u32 { - let popped = self.smalls_head; - self.smalls_head = self.aliases[popped as usize]; - popped - } - - fn pop_big(&mut self) -> u32 { - let popped = self.bigs_head; - self.bigs_head = self.aliases[popped as usize]; - popped - } - - fn smalls_is_empty(&self) -> bool { - self.smalls_head == ::core::u32::MAX - } - - fn bigs_is_empty(&self) -> bool { - self.bigs_head == ::core::u32::MAX - } - - fn set_alias(&mut self, idx: u32, alias: u32) { - self.aliases[idx as usize] = alias; - } - } - - let mut aliases = Aliases::new(n); - - // Split indices into those with small weights and those with big weights. - for (index, &odds) in no_alias_odds.iter().enumerate() { - if odds < weight_sum { - aliases.push_small(index as u32); - } else { - aliases.push_big(index as u32); - } - } - - // Build the alias map by finding an alias with big weight for each index with - // small weight. - while !aliases.smalls_is_empty() && !aliases.bigs_is_empty() { - let s = aliases.pop_small(); - let b = aliases.pop_big(); - - aliases.set_alias(s, b); - no_alias_odds[b as usize] = no_alias_odds[b as usize] - - weight_sum - + no_alias_odds[s as usize]; - - if no_alias_odds[b as usize] < weight_sum { - aliases.push_small(b); - } else { - aliases.push_big(b); - } - } - - // The remaining indices should have no alias odds of about 100%. This is due to - // numeric accuracy. Otherwise they would be exactly 100%. - while !aliases.smalls_is_empty() { - no_alias_odds[aliases.pop_small() as usize] = weight_sum; - } - while !aliases.bigs_is_empty() { - no_alias_odds[aliases.pop_big() as usize] = weight_sum; - } - - // Prepare distributions for sampling. Creating them beforehand improves - // sampling performance. - let uniform_index = Uniform::new(0, n); - let uniform_within_weight_sum = Uniform::new(W::ZERO, weight_sum); - - Ok(Self { - aliases: aliases.aliases, - no_alias_odds, - uniform_index, - uniform_within_weight_sum, - }) - } -} - -impl Distribution for WeightedIndex { - fn sample(&self, rng: &mut R) -> usize { - let candidate = rng.sample(self.uniform_index); - if rng.sample(&self.uniform_within_weight_sum) < self.no_alias_odds[candidate as usize] { - candidate as usize - } else { - self.aliases[candidate as usize] as usize - } - } -} - -impl fmt::Debug for WeightedIndex -where - W: fmt::Debug, - Uniform: fmt::Debug, -{ - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.debug_struct("WeightedIndex") - .field("aliases", &self.aliases) - .field("no_alias_odds", &self.no_alias_odds) - .field("uniform_index", &self.uniform_index) - .field("uniform_within_weight_sum", &self.uniform_within_weight_sum) - .finish() - } -} - -impl Clone for WeightedIndex -where - Uniform: Clone, -{ - fn clone(&self) -> Self { - Self { - aliases: self.aliases.clone(), - no_alias_odds: self.no_alias_odds.clone(), - uniform_index: self.uniform_index.clone(), - uniform_within_weight_sum: self.uniform_within_weight_sum.clone(), - } - } -} - -/// Trait that must be implemented for weights, that are used with -/// [`WeightedIndex`]. Currently no guarantees on the correctness of -/// [`WeightedIndex`] are given for custom implementations of this trait. -pub trait Weight: - Sized - + Copy - + SampleUniform - + PartialOrd - + Add - + AddAssign - + Sub - + SubAssign - + Mul - + MulAssign - + Div - + DivAssign - + Sum -{ - /// Maximum number representable by `Self`. - const MAX: Self; - - /// Element of `Self` equivalent to 0. - const ZERO: Self; - - /// Produce an instance of `Self` from a `u32` value, or return `None` if - /// out of range. Loss of precision (where `Self` is a floating point type) - /// is acceptable. - fn try_from_u32_lossy(n: u32) -> Option; - - /// Sums all values in slice `values`. - fn sum(values: &[Self]) -> Self { - values.iter().map(|x| *x).sum() - } -} - -macro_rules! impl_weight_for_float { - ($T: ident) => { - impl Weight for $T { - const MAX: Self = ::core::$T::MAX; - const ZERO: Self = 0.0; - - fn try_from_u32_lossy(n: u32) -> Option { - Some(n as $T) - } - - fn sum(values: &[Self]) -> Self { - pairwise_sum(values) - } - } - }; -} - -/// In comparison to naive accumulation, the pairwise sum algorithm reduces -/// rounding errors when there are many floating point values. -fn pairwise_sum(values: &[T]) -> T { - if values.len() <= 32 { - values.iter().map(|x| *x).sum() - } else { - let mid = values.len() / 2; - let (a, b) = values.split_at(mid); - pairwise_sum(a) + pairwise_sum(b) - } -} - -macro_rules! impl_weight_for_int { - ($T: ident) => { - impl Weight for $T { - const MAX: Self = ::core::$T::MAX; - const ZERO: Self = 0; - - fn try_from_u32_lossy(n: u32) -> Option { - let n_converted = n as Self; - if n_converted >= Self::ZERO && n_converted as u32 == n { - Some(n_converted) - } else { - None - } - } - } - }; -} - -impl_weight_for_float!(f64); -impl_weight_for_float!(f32); -impl_weight_for_int!(usize); -#[cfg(not(target_os = "emscripten"))] -impl_weight_for_int!(u128); -impl_weight_for_int!(u64); -impl_weight_for_int!(u32); -impl_weight_for_int!(u16); -impl_weight_for_int!(u8); -impl_weight_for_int!(isize); -#[cfg(not(target_os = "emscripten"))] -impl_weight_for_int!(i128); -impl_weight_for_int!(i64); -impl_weight_for_int!(i32); -impl_weight_for_int!(i16); -impl_weight_for_int!(i8); - -#[cfg(test)] -mod test { - use super::*; - - #[test] - #[cfg(not(miri))] // Miri is too slow - fn test_weighted_index_f32() { - test_weighted_index(f32::into); - - // Floating point special cases - assert_eq!( - WeightedIndex::new(vec![::core::f32::INFINITY]).unwrap_err(), - WeightedError::InvalidWeight - ); - assert_eq!( - WeightedIndex::new(vec![-0_f32]).unwrap_err(), - WeightedError::AllWeightsZero - ); - assert_eq!( - WeightedIndex::new(vec![-1_f32]).unwrap_err(), - WeightedError::InvalidWeight - ); - assert_eq!( - WeightedIndex::new(vec![-::core::f32::INFINITY]).unwrap_err(), - WeightedError::InvalidWeight - ); - assert_eq!( - WeightedIndex::new(vec![::core::f32::NAN]).unwrap_err(), - WeightedError::InvalidWeight - ); - } - - #[cfg(not(target_os = "emscripten"))] - #[test] - #[cfg(not(miri))] // Miri is too slow - fn test_weighted_index_u128() { - test_weighted_index(|x: u128| x as f64); - } - - #[cfg(all(rustc_1_26, not(target_os = "emscripten")))] - #[test] - #[cfg(not(miri))] // Miri is too slow - fn test_weighted_index_i128() { - test_weighted_index(|x: i128| x as f64); - - // Signed integer special cases - assert_eq!( - WeightedIndex::new(vec![-1_i128]).unwrap_err(), - WeightedError::InvalidWeight - ); - assert_eq!( - WeightedIndex::new(vec![::core::i128::MIN]).unwrap_err(), - WeightedError::InvalidWeight - ); - } - - #[test] - #[cfg(not(miri))] // Miri is too slow - fn test_weighted_index_u8() { - test_weighted_index(u8::into); - } - - #[test] - #[cfg(not(miri))] // Miri is too slow - fn test_weighted_index_i8() { - test_weighted_index(i8::into); - - // Signed integer special cases - assert_eq!( - WeightedIndex::new(vec![-1_i8]).unwrap_err(), - WeightedError::InvalidWeight - ); - assert_eq!( - WeightedIndex::new(vec![::core::i8::MIN]).unwrap_err(), - WeightedError::InvalidWeight - ); - } - - fn test_weighted_index f64>(w_to_f64: F) - where - WeightedIndex: fmt::Debug, - { - const NUM_WEIGHTS: u32 = 10; - const ZERO_WEIGHT_INDEX: u32 = 3; - const NUM_SAMPLES: u32 = 15000; - let mut rng = crate::test::rng(0x9c9fa0b0580a7031); - - let weights = { - let mut weights = Vec::with_capacity(NUM_WEIGHTS as usize); - let random_weight_distribution = crate::distributions::Uniform::new_inclusive( - W::ZERO, - W::MAX / W::try_from_u32_lossy(NUM_WEIGHTS).unwrap(), - ); - for _ in 0..NUM_WEIGHTS { - weights.push(rng.sample(&random_weight_distribution)); - } - weights[ZERO_WEIGHT_INDEX as usize] = W::ZERO; - weights - }; - let weight_sum = weights.iter().map(|w| *w).sum::(); - let expected_counts = weights - .iter() - .map(|&w| w_to_f64(w) / w_to_f64(weight_sum) * NUM_SAMPLES as f64) - .collect::>(); - let weight_distribution = WeightedIndex::new(weights).unwrap(); - - let mut counts = vec![0; NUM_WEIGHTS as usize]; - for _ in 0..NUM_SAMPLES { - counts[rng.sample(&weight_distribution)] += 1; - } - - assert_eq!(counts[ZERO_WEIGHT_INDEX as usize], 0); - for (count, expected_count) in counts.into_iter().zip(expected_counts) { - let difference = (count as f64 - expected_count).abs(); - let max_allowed_difference = NUM_SAMPLES as f64 / NUM_WEIGHTS as f64 * 0.1; - assert!(difference <= max_allowed_difference); - } - - assert_eq!( - WeightedIndex::::new(vec![]).unwrap_err(), - WeightedError::NoItem - ); - assert_eq!( - WeightedIndex::new(vec![W::ZERO]).unwrap_err(), - WeightedError::AllWeightsZero - ); - assert_eq!( - WeightedIndex::new(vec![W::MAX, W::MAX]).unwrap_err(), - WeightedError::InvalidWeight - ); - } -} diff --git a/rand/src/distributions/weighted/mod.rs b/rand/src/distributions/weighted/mod.rs deleted file mode 100644 index 2711637..0000000 --- a/rand/src/distributions/weighted/mod.rs +++ /dev/null @@ -1,363 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Weighted index sampling -//! -//! This module provides two implementations for sampling indices: -//! -//! * [`WeightedIndex`] allows `O(log N)` sampling -//! * [`alias_method::WeightedIndex`] allows `O(1)` sampling, but with -//! much greater set-up cost -//! -//! [`alias_method::WeightedIndex`]: alias_method/struct.WeightedIndex.html - -pub mod alias_method; - -use crate::Rng; -use crate::distributions::Distribution; -use crate::distributions::uniform::{UniformSampler, SampleUniform, SampleBorrow}; -use core::cmp::PartialOrd; -use core::fmt; - -// Note that this whole module is only imported if feature="alloc" is enabled. -#[cfg(not(feature="std"))] use crate::alloc::vec::Vec; - -/// A distribution using weighted sampling to pick a discretely selected -/// item. -/// -/// Sampling a `WeightedIndex` distribution returns the index of a randomly -/// selected element from the iterator used when the `WeightedIndex` was -/// created. The chance of a given element being picked is proportional to the -/// value of the element. The weights can use any type `X` for which an -/// implementation of [`Uniform`] exists. -/// -/// # Performance -/// -/// A `WeightedIndex` contains a `Vec` and a [`Uniform`] and so its -/// size is the sum of the size of those objects, possibly plus some alignment. -/// -/// Creating a `WeightedIndex` will allocate enough space to hold `N - 1` -/// weights of type `X`, where `N` is the number of weights. However, since -/// `Vec` doesn't guarantee a particular growth strategy, additional memory -/// might be allocated but not used. Since the `WeightedIndex` object also -/// contains, this might cause additional allocations, though for primitive -/// types, ['Uniform`] doesn't allocate any memory. -/// -/// Time complexity of sampling from `WeightedIndex` is `O(log N)` where -/// `N` is the number of weights. -/// -/// Sampling from `WeightedIndex` will result in a single call to -/// `Uniform::sample` (method of the [`Distribution`] trait), which typically -/// will request a single value from the underlying [`RngCore`], though the -/// exact number depends on the implementaiton of `Uniform::sample`. -/// -/// # Example -/// -/// ``` -/// use rand::prelude::*; -/// use rand::distributions::WeightedIndex; -/// -/// let choices = ['a', 'b', 'c']; -/// let weights = [2, 1, 1]; -/// let dist = WeightedIndex::new(&weights).unwrap(); -/// let mut rng = thread_rng(); -/// for _ in 0..100 { -/// // 50% chance to print 'a', 25% chance to print 'b', 25% chance to print 'c' -/// println!("{}", choices[dist.sample(&mut rng)]); -/// } -/// -/// let items = [('a', 0), ('b', 3), ('c', 7)]; -/// let dist2 = WeightedIndex::new(items.iter().map(|item| item.1)).unwrap(); -/// for _ in 0..100 { -/// // 0% chance to print 'a', 30% chance to print 'b', 70% chance to print 'c' -/// println!("{}", items[dist2.sample(&mut rng)].0); -/// } -/// ``` -/// -/// [`Uniform`]: crate::distributions::uniform::Uniform -/// [`RngCore`]: crate::RngCore -#[derive(Debug, Clone)] -pub struct WeightedIndex { - cumulative_weights: Vec, - total_weight: X, - weight_distribution: X::Sampler, -} - -impl WeightedIndex { - /// Creates a new a `WeightedIndex` [`Distribution`] using the values - /// in `weights`. The weights can use any type `X` for which an - /// implementation of [`Uniform`] exists. - /// - /// Returns an error if the iterator is empty, if any weight is `< 0`, or - /// if its total value is 0. - /// - /// [`Uniform`]: crate::distributions::uniform::Uniform - pub fn new(weights: I) -> Result, WeightedError> - where I: IntoIterator, - I::Item: SampleBorrow, - X: for<'a> ::core::ops::AddAssign<&'a X> + - Clone + - Default { - let mut iter = weights.into_iter(); - let mut total_weight: X = iter.next() - .ok_or(WeightedError::NoItem)? - .borrow() - .clone(); - - let zero = ::default(); - if total_weight < zero { - return Err(WeightedError::InvalidWeight); - } - - let mut weights = Vec::::with_capacity(iter.size_hint().0); - for w in iter { - if *w.borrow() < zero { - return Err(WeightedError::InvalidWeight); - } - weights.push(total_weight.clone()); - total_weight += w.borrow(); - } - - if total_weight == zero { - return Err(WeightedError::AllWeightsZero); - } - let distr = X::Sampler::new(zero, total_weight.clone()); - - Ok(WeightedIndex { cumulative_weights: weights, total_weight, weight_distribution: distr }) - } - - /// Update a subset of weights, without changing the number of weights. - /// - /// `new_weights` must be sorted by the index. - /// - /// Using this method instead of `new` might be more efficient if only a small number of - /// weights is modified. No allocations are performed, unless the weight type `X` uses - /// allocation internally. - /// - /// In case of error, `self` is not modified. - pub fn update_weights(&mut self, new_weights: &[(usize, &X)]) -> Result<(), WeightedError> - where X: for<'a> ::core::ops::AddAssign<&'a X> + - for<'a> ::core::ops::SubAssign<&'a X> + - Clone + - Default { - if new_weights.is_empty() { - return Ok(()); - } - - let zero = ::default(); - - let mut total_weight = self.total_weight.clone(); - - // Check for errors first, so we don't modify `self` in case something - // goes wrong. - let mut prev_i = None; - for &(i, w) in new_weights { - if let Some(old_i) = prev_i { - if old_i >= i { - return Err(WeightedError::InvalidWeight); - } - } - if *w < zero { - return Err(WeightedError::InvalidWeight); - } - if i >= self.cumulative_weights.len() + 1 { - return Err(WeightedError::TooMany); - } - - let mut old_w = if i < self.cumulative_weights.len() { - self.cumulative_weights[i].clone() - } else { - self.total_weight.clone() - }; - if i > 0 { - old_w -= &self.cumulative_weights[i - 1]; - } - - total_weight -= &old_w; - total_weight += w; - prev_i = Some(i); - } - if total_weight == zero { - return Err(WeightedError::AllWeightsZero); - } - - // Update the weights. Because we checked all the preconditions in the - // previous loop, this should never panic. - let mut iter = new_weights.iter(); - - let mut prev_weight = zero.clone(); - let mut next_new_weight = iter.next(); - let &(first_new_index, _) = next_new_weight.unwrap(); - let mut cumulative_weight = if first_new_index > 0 { - self.cumulative_weights[first_new_index - 1].clone() - } else { - zero.clone() - }; - for i in first_new_index..self.cumulative_weights.len() { - match next_new_weight { - Some(&(j, w)) if i == j => { - cumulative_weight += w; - next_new_weight = iter.next(); - }, - _ => { - let mut tmp = self.cumulative_weights[i].clone(); - tmp -= &prev_weight; // We know this is positive. - cumulative_weight += &tmp; - } - } - prev_weight = cumulative_weight.clone(); - core::mem::swap(&mut prev_weight, &mut self.cumulative_weights[i]); - } - - self.total_weight = total_weight; - self.weight_distribution = X::Sampler::new(zero, self.total_weight.clone()); - - Ok(()) - } -} - -impl Distribution for WeightedIndex where - X: SampleUniform + PartialOrd { - fn sample(&self, rng: &mut R) -> usize { - use ::core::cmp::Ordering; - let chosen_weight = self.weight_distribution.sample(rng); - // Find the first item which has a weight *higher* than the chosen weight. - self.cumulative_weights.binary_search_by( - |w| if *w <= chosen_weight { Ordering::Less } else { Ordering::Greater }).unwrap_err() - } -} - -#[cfg(test)] -mod test { - use super::*; - - #[test] - #[cfg(not(miri))] // Miri is too slow - fn test_weightedindex() { - let mut r = crate::test::rng(700); - const N_REPS: u32 = 5000; - let weights = [1u32, 2, 3, 0, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7]; - let total_weight = weights.iter().sum::() as f32; - - let verify = |result: [i32; 14]| { - for (i, count) in result.iter().enumerate() { - let exp = (weights[i] * N_REPS) as f32 / total_weight; - let mut err = (*count as f32 - exp).abs(); - if err != 0.0 { - err /= exp; - } - assert!(err <= 0.25); - } - }; - - // WeightedIndex from vec - let mut chosen = [0i32; 14]; - let distr = WeightedIndex::new(weights.to_vec()).unwrap(); - for _ in 0..N_REPS { - chosen[distr.sample(&mut r)] += 1; - } - verify(chosen); - - // WeightedIndex from slice - chosen = [0i32; 14]; - let distr = WeightedIndex::new(&weights[..]).unwrap(); - for _ in 0..N_REPS { - chosen[distr.sample(&mut r)] += 1; - } - verify(chosen); - - // WeightedIndex from iterator - chosen = [0i32; 14]; - let distr = WeightedIndex::new(weights.iter()).unwrap(); - for _ in 0..N_REPS { - chosen[distr.sample(&mut r)] += 1; - } - verify(chosen); - - for _ in 0..5 { - assert_eq!(WeightedIndex::new(&[0, 1]).unwrap().sample(&mut r), 1); - assert_eq!(WeightedIndex::new(&[1, 0]).unwrap().sample(&mut r), 0); - assert_eq!(WeightedIndex::new(&[0, 0, 0, 0, 10, 0]).unwrap().sample(&mut r), 4); - } - - assert_eq!(WeightedIndex::new(&[10][0..0]).unwrap_err(), WeightedError::NoItem); - assert_eq!(WeightedIndex::new(&[0]).unwrap_err(), WeightedError::AllWeightsZero); - assert_eq!(WeightedIndex::new(&[10, 20, -1, 30]).unwrap_err(), WeightedError::InvalidWeight); - assert_eq!(WeightedIndex::new(&[-10, 20, 1, 30]).unwrap_err(), WeightedError::InvalidWeight); - assert_eq!(WeightedIndex::new(&[-10]).unwrap_err(), WeightedError::InvalidWeight); - } - - #[test] - fn test_update_weights() { - let data = [ - (&[10u32, 2, 3, 4][..], - &[(1, &100), (2, &4)][..], // positive change - &[10, 100, 4, 4][..]), - (&[1u32, 2, 3, 0, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7][..], - &[(2, &1), (5, &1), (13, &100)][..], // negative change and last element - &[1u32, 2, 1, 0, 5, 1, 7, 1, 2, 3, 4, 5, 6, 100][..]), - ]; - - for (weights, update, expected_weights) in data.into_iter() { - let total_weight = weights.iter().sum::(); - let mut distr = WeightedIndex::new(weights.to_vec()).unwrap(); - assert_eq!(distr.total_weight, total_weight); - - distr.update_weights(update).unwrap(); - let expected_total_weight = expected_weights.iter().sum::(); - let expected_distr = WeightedIndex::new(expected_weights.to_vec()).unwrap(); - assert_eq!(distr.total_weight, expected_total_weight); - assert_eq!(distr.total_weight, expected_distr.total_weight); - assert_eq!(distr.cumulative_weights, expected_distr.cumulative_weights); - } - } -} - -/// Error type returned from `WeightedIndex::new`. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum WeightedError { - /// The provided weight collection contains no items. - NoItem, - - /// A weight is either less than zero, greater than the supported maximum or - /// otherwise invalid. - InvalidWeight, - - /// All items in the provided weight collection are zero. - AllWeightsZero, - - /// Too many weights are provided (length greater than `u32::MAX`) - TooMany, -} - -impl WeightedError { - fn msg(&self) -> &str { - match *self { - WeightedError::NoItem => "No weights provided.", - WeightedError::InvalidWeight => "A weight is invalid.", - WeightedError::AllWeightsZero => "All weights are zero.", - WeightedError::TooMany => "Too many weights (hit u32::MAX)", - } - } -} - -#[cfg(feature="std")] -impl ::std::error::Error for WeightedError { - fn description(&self) -> &str { - self.msg() - } - fn cause(&self) -> Option<&dyn (::std::error::Error)> { - None - } -} - -impl fmt::Display for WeightedError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self.msg()) - } -} diff --git a/rand/src/distributions/ziggurat_tables.rs b/rand/src/distributions/ziggurat_tables.rs deleted file mode 100644 index ca1ce30..0000000 --- a/rand/src/distributions/ziggurat_tables.rs +++ /dev/null @@ -1,279 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// Copyright 2013 The Rust Project Developers. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -// Tables for distributions which are sampled using the ziggurat -// algorithm. Autogenerated by `ziggurat_tables.py`. - -pub type ZigTable = &'static [f64; 257]; -pub const ZIG_NORM_R: f64 = 3.654152885361008796; -pub static ZIG_NORM_X: [f64; 257] = - [3.910757959537090045, 3.654152885361008796, 3.449278298560964462, 3.320244733839166074, - 3.224575052047029100, 3.147889289517149969, 3.083526132001233044, 3.027837791768635434, - 2.978603279880844834, 2.934366867207854224, 2.894121053612348060, 2.857138730872132548, - 2.822877396825325125, 2.790921174000785765, 2.760944005278822555, 2.732685359042827056, - 2.705933656121858100, 2.680514643284522158, 2.656283037575502437, 2.633116393630324570, - 2.610910518487548515, 2.589575986706995181, 2.569035452680536569, 2.549221550323460761, - 2.530075232158516929, 2.511544441625342294, 2.493583041269680667, 2.476149939669143318, - 2.459208374333311298, 2.442725318198956774, 2.426670984935725972, 2.411018413899685520, - 2.395743119780480601, 2.380822795170626005, 2.366237056715818632, 2.351967227377659952, - 2.337996148795031370, 2.324308018869623016, 2.310888250599850036, 2.297723348901329565, - 2.284800802722946056, 2.272108990226823888, 2.259637095172217780, 2.247375032945807760, - 2.235313384928327984, 2.223443340090905718, 2.211756642882544366, 2.200245546609647995, - 2.188902771624720689, 2.177721467738641614, 2.166695180352645966, 2.155817819875063268, - 2.145083634046203613, 2.134487182844320152, 2.124023315687815661, 2.113687150684933957, - 2.103474055713146829, 2.093379631137050279, 2.083399693996551783, 2.073530263516978778, - 2.063767547809956415, 2.054107931648864849, 2.044547965215732788, 2.035084353727808715, - 2.025713947862032960, 2.016433734904371722, 2.007240830558684852, 1.998132471356564244, - 1.989106007615571325, 1.980158896898598364, 1.971288697931769640, 1.962493064942461896, - 1.953769742382734043, 1.945116560006753925, 1.936531428273758904, 1.928012334050718257, - 1.919557336591228847, 1.911164563769282232, 1.902832208548446369, 1.894558525668710081, - 1.886341828534776388, 1.878180486290977669, 1.870072921069236838, 1.862017605397632281, - 1.854013059758148119, 1.846057850283119750, 1.838150586580728607, 1.830289919680666566, - 1.822474540091783224, 1.814703175964167636, 1.806974591348693426, 1.799287584547580199, - 1.791640986550010028, 1.784033659547276329, 1.776464495522344977, 1.768932414909077933, - 1.761436365316706665, 1.753975320315455111, 1.746548278279492994, 1.739154261283669012, - 1.731792314050707216, 1.724461502945775715, 1.717160915015540690, 1.709889657069006086, - 1.702646854797613907, 1.695431651932238548, 1.688243209434858727, 1.681080704722823338, - 1.673943330923760353, 1.666830296159286684, 1.659740822855789499, 1.652674147080648526, - 1.645629517902360339, 1.638606196773111146, 1.631603456932422036, 1.624620582830568427, - 1.617656869570534228, 1.610711622367333673, 1.603784156023583041, 1.596873794420261339, - 1.589979870021648534, 1.583101723393471438, 1.576238702733332886, 1.569390163412534456, - 1.562555467528439657, 1.555733983466554893, 1.548925085471535512, 1.542128153226347553, - 1.535342571438843118, 1.528567729435024614, 1.521803020758293101, 1.515047842773992404, - 1.508301596278571965, 1.501563685112706548, 1.494833515777718391, 1.488110497054654369, - 1.481394039625375747, 1.474683555695025516, 1.467978458615230908, 1.461278162507407830, - 1.454582081885523293, 1.447889631277669675, 1.441200224845798017, 1.434513276002946425, - 1.427828197027290358, 1.421144398672323117, 1.414461289772464658, 1.407778276843371534, - 1.401094763676202559, 1.394410150925071257, 1.387723835686884621, 1.381035211072741964, - 1.374343665770030531, 1.367648583594317957, 1.360949343030101844, 1.354245316759430606, - 1.347535871177359290, 1.340820365893152122, 1.334098153216083604, 1.327368577624624679, - 1.320630975217730096, 1.313884673146868964, 1.307128989027353860, 1.300363230327433728, - 1.293586693733517645, 1.286798664489786415, 1.279998415710333237, 1.273185207661843732, - 1.266358287014688333, 1.259516886060144225, 1.252660221891297887, 1.245787495544997903, - 1.238897891102027415, 1.231990574742445110, 1.225064693752808020, 1.218119375481726552, - 1.211153726239911244, 1.204166830140560140, 1.197157747875585931, 1.190125515422801650, - 1.183069142678760732, 1.175987612011489825, 1.168879876726833800, 1.161744859441574240, - 1.154581450355851802, 1.147388505416733873, 1.140164844363995789, 1.132909248648336975, - 1.125620459211294389, 1.118297174115062909, 1.110938046009249502, 1.103541679420268151, - 1.096106627847603487, 1.088631390649514197, 1.081114409698889389, 1.073554065787871714, - 1.065948674757506653, 1.058296483326006454, 1.050595664586207123, 1.042844313139370538, - 1.035040439828605274, 1.027181966030751292, 1.019266717460529215, 1.011292417434978441, - 1.003256679539591412, 0.995156999629943084, 0.986990747093846266, 0.978755155288937750, - 0.970447311058864615, 0.962064143217605250, 0.953602409875572654, 0.945058684462571130, - 0.936429340280896860, 0.927710533396234771, 0.918898183643734989, 0.909987953490768997, - 0.900975224455174528, 0.891855070726792376, 0.882622229578910122, 0.873271068082494550, - 0.863795545546826915, 0.854189171001560554, 0.844444954902423661, 0.834555354079518752, - 0.824512208745288633, 0.814306670128064347, 0.803929116982664893, 0.793369058833152785, - 0.782615023299588763, 0.771654424216739354, 0.760473406422083165, 0.749056662009581653, - 0.737387211425838629, 0.725446140901303549, 0.713212285182022732, 0.700661841097584448, - 0.687767892786257717, 0.674499822827436479, 0.660822574234205984, 0.646695714884388928, - 0.632072236375024632, 0.616896989996235545, 0.601104617743940417, 0.584616766093722262, - 0.567338257040473026, 0.549151702313026790, 0.529909720646495108, 0.509423329585933393, - 0.487443966121754335, 0.463634336771763245, 0.437518402186662658, 0.408389134588000746, - 0.375121332850465727, 0.335737519180459465, 0.286174591747260509, 0.215241895913273806, - 0.000000000000000000]; -pub static ZIG_NORM_F: [f64; 257] = - [0.000477467764586655, 0.001260285930498598, 0.002609072746106363, 0.004037972593371872, - 0.005522403299264754, 0.007050875471392110, 0.008616582769422917, 0.010214971439731100, - 0.011842757857943104, 0.013497450601780807, 0.015177088307982072, 0.016880083152595839, - 0.018605121275783350, 0.020351096230109354, 0.022117062707379922, 0.023902203305873237, - 0.025705804008632656, 0.027527235669693315, 0.029365939758230111, 0.031221417192023690, - 0.033093219458688698, 0.034980941461833073, 0.036884215688691151, 0.038802707404656918, - 0.040736110656078753, 0.042684144916619378, 0.044646552251446536, 0.046623094902089664, - 0.048613553216035145, 0.050617723861121788, 0.052635418276973649, 0.054666461325077916, - 0.056710690106399467, 0.058767952921137984, 0.060838108349751806, 0.062921024437977854, - 0.065016577971470438, 0.067124653828023989, 0.069245144397250269, 0.071377949059141965, - 0.073522973714240991, 0.075680130359194964, 0.077849336702372207, 0.080030515814947509, - 0.082223595813495684, 0.084428509570654661, 0.086645194450867782, 0.088873592068594229, - 0.091113648066700734, 0.093365311913026619, 0.095628536713353335, 0.097903279039215627, - 0.100189498769172020, 0.102487158942306270, 0.104796225622867056, 0.107116667775072880, - 0.109448457147210021, 0.111791568164245583, 0.114145977828255210, 0.116511665626037014, - 0.118888613443345698, 0.121276805485235437, 0.123676228202051403, 0.126086870220650349, - 0.128508722280473636, 0.130941777174128166, 0.133386029692162844, 0.135841476571757352, - 0.138308116449064322, 0.140785949814968309, 0.143274978974047118, 0.145775208006537926, - 0.148286642733128721, 0.150809290682410169, 0.153343161060837674, 0.155888264725064563, - 0.158444614156520225, 0.161012223438117663, 0.163591108232982951, 0.166181285765110071, - 0.168782774801850333, 0.171395595638155623, 0.174019770082499359, 0.176655321444406654, - 0.179302274523530397, 0.181960655600216487, 0.184630492427504539, 0.187311814224516926, - 0.190004651671193070, 0.192709036904328807, 0.195425003514885592, 0.198152586546538112, - 0.200891822495431333, 0.203642749311121501, 0.206405406398679298, 0.209179834621935651, - 0.211966076307852941, 0.214764175252008499, 0.217574176725178370, 0.220396127481011589, - 0.223230075764789593, 0.226076071323264877, 0.228934165415577484, 0.231804410825248525, - 0.234686861873252689, 0.237581574432173676, 0.240488605941449107, 0.243408015423711988, - 0.246339863502238771, 0.249284212419516704, 0.252241126056943765, 0.255210669955677150, - 0.258192911338648023, 0.261187919133763713, 0.264195763998317568, 0.267216518344631837, - 0.270250256366959984, 0.273297054069675804, 0.276356989296781264, 0.279430141762765316, - 0.282516593084849388, 0.285616426816658109, 0.288729728483353931, 0.291856585618280984, - 0.294997087801162572, 0.298151326697901342, 0.301319396102034120, 0.304501391977896274, - 0.307697412505553769, 0.310907558127563710, 0.314131931597630143, 0.317370638031222396, - 0.320623784958230129, 0.323891482377732021, 0.327173842814958593, 0.330470981380537099, - 0.333783015832108509, 0.337110066638412809, 0.340452257045945450, 0.343809713148291340, - 0.347182563958251478, 0.350570941482881204, 0.353974980801569250, 0.357394820147290515, - 0.360830600991175754, 0.364282468130549597, 0.367750569780596226, 0.371235057669821344, - 0.374736087139491414, 0.378253817247238111, 0.381788410875031348, 0.385340034841733958, - 0.388908860020464597, 0.392495061461010764, 0.396098818517547080, 0.399720314981931668, - 0.403359739222868885, 0.407017284331247953, 0.410693148271983222, 0.414387534042706784, - 0.418100649839684591, 0.421832709231353298, 0.425583931339900579, 0.429354541031341519, - 0.433144769114574058, 0.436954852549929273, 0.440785034667769915, 0.444635565397727750, - 0.448506701509214067, 0.452398706863882505, 0.456311852680773566, 0.460246417814923481, - 0.464202689050278838, 0.468180961407822172, 0.472181538469883255, 0.476204732721683788, - 0.480250865911249714, 0.484320269428911598, 0.488413284707712059, 0.492530263646148658, - 0.496671569054796314, 0.500837575128482149, 0.505028667945828791, 0.509245245998136142, - 0.513487720749743026, 0.517756517232200619, 0.522052074674794864, 0.526374847174186700, - 0.530725304406193921, 0.535103932383019565, 0.539511234259544614, 0.543947731192649941, - 0.548413963257921133, 0.552910490428519918, 0.557437893621486324, 0.561996775817277916, - 0.566587763258951771, 0.571211506738074970, 0.575868682975210544, 0.580559996103683473, - 0.585286179266300333, 0.590047996335791969, 0.594846243770991268, 0.599681752622167719, - 0.604555390700549533, 0.609468064928895381, 0.614420723892076803, 0.619414360609039205, - 0.624450015550274240, 0.629528779928128279, 0.634651799290960050, 0.639820277456438991, - 0.645035480824251883, 0.650298743114294586, 0.655611470583224665, 0.660975147780241357, - 0.666391343912380640, 0.671861719900766374, 0.677388036222513090, 0.682972161648791376, - 0.688616083008527058, 0.694321916130032579, 0.700091918140490099, 0.705928501336797409, - 0.711834248882358467, 0.717811932634901395, 0.723864533472881599, 0.729995264565802437, - 0.736207598131266683, 0.742505296344636245, 0.748892447223726720, 0.755373506511754500, - 0.761953346841546475, 0.768637315803334831, 0.775431304986138326, 0.782341832659861902, - 0.789376143571198563, 0.796542330428254619, 0.803849483176389490, 0.811307874318219935, - 0.818929191609414797, 0.826726833952094231, 0.834716292992930375, 0.842915653118441077, - 0.851346258465123684, 0.860033621203008636, 0.869008688043793165, 0.878309655816146839, - 0.887984660763399880, 0.898095921906304051, 0.908726440060562912, 0.919991505048360247, - 0.932060075968990209, 0.945198953453078028, 0.959879091812415930, 0.977101701282731328, - 1.000000000000000000]; -pub const ZIG_EXP_R: f64 = 7.697117470131050077; -pub static ZIG_EXP_X: [f64; 257] = - [8.697117470131052741, 7.697117470131050077, 6.941033629377212577, 6.478378493832569696, - 6.144164665772472667, 5.882144315795399869, 5.666410167454033697, 5.482890627526062488, - 5.323090505754398016, 5.181487281301500047, 5.054288489981304089, 4.938777085901250530, - 4.832939741025112035, 4.735242996601741083, 4.644491885420085175, 4.559737061707351380, - 4.480211746528421912, 4.405287693473573185, 4.334443680317273007, 4.267242480277365857, - 4.203313713735184365, 4.142340865664051464, 4.084051310408297830, 4.028208544647936762, - 3.974606066673788796, 3.923062500135489739, 3.873417670399509127, 3.825529418522336744, - 3.779270992411667862, 3.734528894039797375, 3.691201090237418825, 3.649195515760853770, - 3.608428813128909507, 3.568825265648337020, 3.530315889129343354, 3.492837654774059608, - 3.456332821132760191, 3.420748357251119920, 3.386035442460300970, 3.352149030900109405, - 3.319047470970748037, 3.286692171599068679, 3.255047308570449882, 3.224079565286264160, - 3.193757903212240290, 3.164053358025972873, 3.134938858084440394, 3.106389062339824481, - 3.078380215254090224, 3.050890016615455114, 3.023897504455676621, 2.997382949516130601, - 2.971327759921089662, 2.945714394895045718, 2.920526286512740821, 2.895747768600141825, - 2.871364012015536371, 2.847360965635188812, 2.823725302450035279, 2.800444370250737780, - 2.777506146439756574, 2.754899196562344610, 2.732612636194700073, 2.710636095867928752, - 2.688959688741803689, 2.667573980773266573, 2.646469963151809157, 2.625639026797788489, - 2.605072938740835564, 2.584763820214140750, 2.564704126316905253, 2.544886627111869970, - 2.525304390037828028, 2.505950763528594027, 2.486819361740209455, 2.467904050297364815, - 2.449198932978249754, 2.430698339264419694, 2.412396812688870629, 2.394289099921457886, - 2.376370140536140596, 2.358635057409337321, 2.341079147703034380, 2.323697874390196372, - 2.306486858283579799, 2.289441870532269441, 2.272558825553154804, 2.255833774367219213, - 2.239262898312909034, 2.222842503111036816, 2.206569013257663858, 2.190438966723220027, - 2.174449009937774679, 2.158595893043885994, 2.142876465399842001, 2.127287671317368289, - 2.111826546019042183, 2.096490211801715020, 2.081275874393225145, 2.066180819490575526, - 2.051202409468584786, 2.036338080248769611, 2.021585338318926173, 2.006941757894518563, - 1.992404978213576650, 1.977972700957360441, 1.963642687789548313, 1.949412758007184943, - 1.935280786297051359, 1.921244700591528076, 1.907302480018387536, 1.893452152939308242, - 1.879691795072211180, 1.866019527692827973, 1.852433515911175554, 1.838931967018879954, - 1.825513128903519799, 1.812175288526390649, 1.798916770460290859, 1.785735935484126014, - 1.772631179231305643, 1.759600930889074766, 1.746643651946074405, 1.733757834985571566, - 1.720942002521935299, 1.708194705878057773, 1.695514524101537912, 1.682900062917553896, - 1.670349953716452118, 1.657862852574172763, 1.645437439303723659, 1.633072416535991334, - 1.620766508828257901, 1.608518461798858379, 1.596327041286483395, 1.584191032532688892, - 1.572109239386229707, 1.560080483527888084, 1.548103603714513499, 1.536177455041032092, - 1.524300908219226258, 1.512472848872117082, 1.500692176842816750, 1.488957805516746058, - 1.477268661156133867, 1.465623682245745352, 1.454021818848793446, 1.442462031972012504, - 1.430943292938879674, 1.419464582769983219, 1.408024891569535697, 1.396623217917042137, - 1.385258568263121992, 1.373929956328490576, 1.362636402505086775, 1.351376933258335189, - 1.340150580529504643, 1.328956381137116560, 1.317793376176324749, 1.306660610415174117, - 1.295557131686601027, 1.284481990275012642, 1.273434238296241139, 1.262412929069615330, - 1.251417116480852521, 1.240445854334406572, 1.229498195693849105, 1.218573192208790124, - 1.207669893426761121, 1.196787346088403092, 1.185924593404202199, 1.175080674310911677, - 1.164254622705678921, 1.153445466655774743, 1.142652227581672841, 1.131873919411078511, - 1.121109547701330200, 1.110358108727411031, 1.099618588532597308, 1.088889961938546813, - 1.078171191511372307, 1.067461226479967662, 1.056759001602551429, 1.046063435977044209, - 1.035373431790528542, 1.024687873002617211, 1.014005623957096480, 1.003325527915696735, - 0.992646405507275897, 0.981967053085062602, 0.971286240983903260, 0.960602711668666509, - 0.949915177764075969, 0.939222319955262286, 0.928522784747210395, 0.917815182070044311, - 0.907098082715690257, 0.896370015589889935, 0.885629464761751528, 0.874874866291025066, - 0.864104604811004484, 0.853317009842373353, 0.842510351810368485, 0.831682837734273206, - 0.820832606554411814, 0.809957724057418282, 0.799056177355487174, 0.788125868869492430, - 0.777164609759129710, 0.766170112735434672, 0.755139984181982249, 0.744071715500508102, - 0.732962673584365398, 0.721810090308756203, 0.710611050909655040, 0.699362481103231959, - 0.688061132773747808, 0.676703568029522584, 0.665286141392677943, 0.653804979847664947, - 0.642255960424536365, 0.630634684933490286, 0.618936451394876075, 0.607156221620300030, - 0.595288584291502887, 0.583327712748769489, 0.571267316532588332, 0.559100585511540626, - 0.546820125163310577, 0.534417881237165604, 0.521885051592135052, 0.509211982443654398, - 0.496388045518671162, 0.483401491653461857, 0.470239275082169006, 0.456886840931420235, - 0.443327866073552401, 0.429543940225410703, 0.415514169600356364, 0.401214678896277765, - 0.386617977941119573, 0.371692145329917234, 0.356399760258393816, 0.340696481064849122, - 0.324529117016909452, 0.307832954674932158, 0.290527955491230394, 0.272513185478464703, - 0.253658363385912022, 0.233790483059674731, 0.212671510630966620, 0.189958689622431842, - 0.165127622564187282, 0.137304980940012589, 0.104838507565818778, 0.063852163815001570, - 0.000000000000000000]; -pub static ZIG_EXP_F: [f64; 257] = - [0.000167066692307963, 0.000454134353841497, 0.000967269282327174, 0.001536299780301573, - 0.002145967743718907, 0.002788798793574076, 0.003460264777836904, 0.004157295120833797, - 0.004877655983542396, 0.005619642207205489, 0.006381905937319183, 0.007163353183634991, - 0.007963077438017043, 0.008780314985808977, 0.009614413642502212, 0.010464810181029981, - 0.011331013597834600, 0.012212592426255378, 0.013109164931254991, 0.014020391403181943, - 0.014945968011691148, 0.015885621839973156, 0.016839106826039941, 0.017806200410911355, - 0.018786700744696024, 0.019780424338009740, 0.020787204072578114, 0.021806887504283581, - 0.022839335406385240, 0.023884420511558174, 0.024942026419731787, 0.026012046645134221, - 0.027094383780955803, 0.028188948763978646, 0.029295660224637411, 0.030414443910466622, - 0.031545232172893622, 0.032687963508959555, 0.033842582150874358, 0.035009037697397431, - 0.036187284781931443, 0.037377282772959382, 0.038578995503074871, 0.039792391023374139, - 0.041017441380414840, 0.042254122413316254, 0.043502413568888197, 0.044762297732943289, - 0.046033761076175184, 0.047316792913181561, 0.048611385573379504, 0.049917534282706379, - 0.051235237055126281, 0.052564494593071685, 0.053905310196046080, 0.055257689676697030, - 0.056621641283742870, 0.057997175631200659, 0.059384305633420280, 0.060783046445479660, - 0.062193415408541036, 0.063615431999807376, 0.065049117786753805, 0.066494496385339816, - 0.067951593421936643, 0.069420436498728783, 0.070901055162371843, 0.072393480875708752, - 0.073897746992364746, 0.075413888734058410, 0.076941943170480517, 0.078481949201606435, - 0.080033947542319905, 0.081597980709237419, 0.083174093009632397, 0.084762330532368146, - 0.086362741140756927, 0.087975374467270231, 0.089600281910032886, 0.091237516631040197, - 0.092887133556043569, 0.094549189376055873, 0.096223742550432825, 0.097910853311492213, - 0.099610583670637132, 0.101322997425953631, 0.103048160171257702, 0.104786139306570145, - 0.106537004050001632, 0.108300825451033755, 0.110077676405185357, 0.111867631670056283, - 0.113670767882744286, 0.115487163578633506, 0.117316899211555525, 0.119160057175327641, - 0.121016721826674792, 0.122886979509545108, 0.124770918580830933, 0.126668629437510671, - 0.128580204545228199, 0.130505738468330773, 0.132445327901387494, 0.134399071702213602, - 0.136367070926428829, 0.138349428863580176, 0.140346251074862399, 0.142357645432472146, - 0.144383722160634720, 0.146424593878344889, 0.148480375643866735, 0.150551185001039839, - 0.152637142027442801, 0.154738369384468027, 0.156854992369365148, 0.158987138969314129, - 0.161134939917591952, 0.163298528751901734, 0.165478041874935922, 0.167673618617250081, - 0.169885401302527550, 0.172113535315319977, 0.174358169171353411, 0.176619454590494829, - 0.178897546572478278, 0.181192603475496261, 0.183504787097767436, 0.185834262762197083, - 0.188181199404254262, 0.190545769663195363, 0.192928149976771296, 0.195328520679563189, - 0.197747066105098818, 0.200183974691911210, 0.202639439093708962, 0.205113656293837654, - 0.207606827724221982, 0.210119159388988230, 0.212650861992978224, 0.215202151075378628, - 0.217773247148700472, 0.220364375843359439, 0.222975768058120111, 0.225607660116683956, - 0.228260293930716618, 0.230933917169627356, 0.233628783437433291, 0.236345152457059560, - 0.239083290262449094, 0.241843469398877131, 0.244625969131892024, 0.247431075665327543, - 0.250259082368862240, 0.253110290015629402, 0.255985007030415324, 0.258883549749016173, - 0.261806242689362922, 0.264753418835062149, 0.267725419932044739, 0.270722596799059967, - 0.273745309652802915, 0.276793928448517301, 0.279868833236972869, 0.282970414538780746, - 0.286099073737076826, 0.289255223489677693, 0.292439288161892630, 0.295651704281261252, - 0.298892921015581847, 0.302163400675693528, 0.305463619244590256, 0.308794066934560185, - 0.312155248774179606, 0.315547685227128949, 0.318971912844957239, 0.322428484956089223, - 0.325917972393556354, 0.329440964264136438, 0.332998068761809096, 0.336589914028677717, - 0.340217149066780189, 0.343880444704502575, 0.347580494621637148, 0.351318016437483449, - 0.355093752866787626, 0.358908472948750001, 0.362762973354817997, 0.366658079781514379, - 0.370594648435146223, 0.374573567615902381, 0.378595759409581067, 0.382662181496010056, - 0.386773829084137932, 0.390931736984797384, 0.395136981833290435, 0.399390684475231350, - 0.403694012530530555, 0.408048183152032673, 0.412454465997161457, 0.416914186433003209, - 0.421428728997616908, 0.425999541143034677, 0.430628137288459167, 0.435316103215636907, - 0.440065100842354173, 0.444876873414548846, 0.449753251162755330, 0.454696157474615836, - 0.459707615642138023, 0.464789756250426511, 0.469944825283960310, 0.475175193037377708, - 0.480483363930454543, 0.485871987341885248, 0.491343869594032867, 0.496901987241549881, - 0.502549501841348056, 0.508289776410643213, 0.514126393814748894, 0.520063177368233931, - 0.526104213983620062, 0.532253880263043655, 0.538516872002862246, 0.544898237672440056, - 0.551403416540641733, 0.558038282262587892, 0.564809192912400615, 0.571723048664826150, - 0.578787358602845359, 0.586010318477268366, 0.593400901691733762, 0.600968966365232560, - 0.608725382079622346, 0.616682180915207878, 0.624852738703666200, 0.633251994214366398, - 0.641896716427266423, 0.650805833414571433, 0.660000841079000145, 0.669506316731925177, - 0.679350572264765806, 0.689566496117078431, 0.700192655082788606, 0.711274760805076456, - 0.722867659593572465, 0.735038092431424039, 0.747868621985195658, 0.761463388849896838, - 0.775956852040116218, 0.791527636972496285, 0.808421651523009044, 0.826993296643051101, - 0.847785500623990496, 0.871704332381204705, 0.900469929925747703, 0.938143680862176477, - 1.000000000000000000]; diff --git a/rand/src/lib.rs b/rand/src/lib.rs deleted file mode 100644 index b4167c3..0000000 --- a/rand/src/lib.rs +++ /dev/null @@ -1,720 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// Copyright 2013-2017 The Rust Project Developers. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Utilities for random number generation -//! -//! Rand provides utilities to generate random numbers, to convert them to -//! useful types and distributions, and some randomness-related algorithms. -//! -//! # Quick Start -//! -//! To get you started quickly, the easiest and highest-level way to get -//! a random value is to use [`random()`]; alternatively you can use -//! [`thread_rng()`]. The [`Rng`] trait provides a useful API on all RNGs, while -//! the [`distributions`] and [`seq`] modules provide further -//! functionality on top of RNGs. -//! -//! ``` -//! use rand::prelude::*; -//! -//! if rand::random() { // generates a boolean -//! // Try printing a random unicode code point (probably a bad idea)! -//! println!("char: {}", rand::random::()); -//! } -//! -//! let mut rng = rand::thread_rng(); -//! let y: f64 = rng.gen(); // generates a float between 0 and 1 -//! -//! let mut nums: Vec = (1..100).collect(); -//! nums.shuffle(&mut rng); -//! ``` -//! -//! # The Book -//! -//! For the user guide and futher documentation, please read -//! [The Rust Rand Book](https://rust-random.github.io/book). - - -#![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(not(feature="std"), no_std)] -#![cfg_attr(all(feature="simd_support", feature="nightly"), feature(stdsimd))] - -#![allow(clippy::excessive_precision, clippy::unreadable_literal, clippy::float_cmp)] - -#[cfg(all(feature="alloc", not(feature="std")))] -extern crate alloc; - -#[cfg(feature = "getrandom")] -use getrandom_package as getrandom; - -#[allow(unused)] -macro_rules! trace { ($($x:tt)*) => ( - #[cfg(feature = "log")] { - log::trace!($($x)*) - } -) } -#[allow(unused)] -macro_rules! debug { ($($x:tt)*) => ( - #[cfg(feature = "log")] { - log::debug!($($x)*) - } -) } -#[allow(unused)] -macro_rules! info { ($($x:tt)*) => ( - #[cfg(feature = "log")] { - log::info!($($x)*) - } -) } -#[allow(unused)] -macro_rules! warn { ($($x:tt)*) => ( - #[cfg(feature = "log")] { - log::warn!($($x)*) - } -) } -#[allow(unused)] -macro_rules! error { ($($x:tt)*) => ( - #[cfg(feature = "log")] { - log::error!($($x)*) - } -) } - -// Re-exports from rand_core -pub use rand_core::{RngCore, CryptoRng, SeedableRng, Error}; - -// Public exports -#[cfg(feature="std")] pub use crate::rngs::thread::thread_rng; - -// Public modules -pub mod distributions; -pub mod prelude; -pub mod rngs; -pub mod seq; - - -use core::{mem, slice}; -use core::num::Wrapping; -use crate::distributions::{Distribution, Standard}; -use crate::distributions::uniform::{SampleUniform, UniformSampler, SampleBorrow}; - -/// An automatically-implemented extension trait on [`RngCore`] providing high-level -/// generic methods for sampling values and other convenience methods. -/// -/// This is the primary trait to use when generating random values. -/// -/// # Generic usage -/// -/// The basic pattern is `fn foo(rng: &mut R)`. Some -/// things are worth noting here: -/// -/// - Since `Rng: RngCore` and every `RngCore` implements `Rng`, it makes no -/// difference whether we use `R: Rng` or `R: RngCore`. -/// - The `+ ?Sized` un-bounding allows functions to be called directly on -/// type-erased references; i.e. `foo(r)` where `r: &mut RngCore`. Without -/// this it would be necessary to write `foo(&mut r)`. -/// -/// An alternative pattern is possible: `fn foo(rng: R)`. This has some -/// trade-offs. It allows the argument to be consumed directly without a `&mut` -/// (which is how `from_rng(thread_rng())` works); also it still works directly -/// on references (including type-erased references). Unfortunately within the -/// function `foo` it is not known whether `rng` is a reference type or not, -/// hence many uses of `rng` require an extra reference, either explicitly -/// (`distr.sample(&mut rng)`) or implicitly (`rng.gen()`); one may hope the -/// optimiser can remove redundant references later. -/// -/// Example: -/// -/// ``` -/// # use rand::thread_rng; -/// use rand::Rng; -/// -/// fn foo(rng: &mut R) -> f32 { -/// rng.gen() -/// } -/// -/// # let v = foo(&mut thread_rng()); -/// ``` -pub trait Rng: RngCore { - /// Return a random value supporting the [`Standard`] distribution. - /// - /// # Example - /// - /// ``` - /// use rand::{thread_rng, Rng}; - /// - /// let mut rng = thread_rng(); - /// let x: u32 = rng.gen(); - /// println!("{}", x); - /// println!("{:?}", rng.gen::<(f64, bool)>()); - /// ``` - /// - /// # Arrays and tuples - /// - /// The `rng.gen()` method is able to generate arrays (up to 32 elements) - /// and tuples (up to 12 elements), so long as all element types can be - /// generated. - /// - /// For arrays of integers, especially for those with small element types - /// (< 64 bit), it will likely be faster to instead use [`Rng::fill`]. - /// - /// ``` - /// use rand::{thread_rng, Rng}; - /// - /// let mut rng = thread_rng(); - /// let tuple: (u8, i32, char) = rng.gen(); // arbitrary tuple support - /// - /// let arr1: [f32; 32] = rng.gen(); // array construction - /// let mut arr2 = [0u8; 128]; - /// rng.fill(&mut arr2); // array fill - /// ``` - /// - /// [`Standard`]: distributions::Standard - #[inline] - fn gen(&mut self) -> T - where Standard: Distribution { - Standard.sample(self) - } - - /// Generate a random value in the range [`low`, `high`), i.e. inclusive of - /// `low` and exclusive of `high`. - /// - /// This function is optimised for the case that only a single sample is - /// made from the given range. See also the [`Uniform`] distribution - /// type which may be faster if sampling from the same range repeatedly. - /// - /// # Panics - /// - /// Panics if `low >= high`. - /// - /// # Example - /// - /// ``` - /// use rand::{thread_rng, Rng}; - /// - /// let mut rng = thread_rng(); - /// let n: u32 = rng.gen_range(0, 10); - /// println!("{}", n); - /// let m: f64 = rng.gen_range(-40.0f64, 1.3e5f64); - /// println!("{}", m); - /// ``` - /// - /// [`Uniform`]: distributions::uniform::Uniform - fn gen_range(&mut self, low: B1, high: B2) -> T - where - B1: SampleBorrow + Sized, - B2: SampleBorrow + Sized, - { - T::Sampler::sample_single(low, high, self) - } - - /// Sample a new value, using the given distribution. - /// - /// ### Example - /// - /// ``` - /// use rand::{thread_rng, Rng}; - /// use rand::distributions::Uniform; - /// - /// let mut rng = thread_rng(); - /// let x = rng.sample(Uniform::new(10u32, 15)); - /// // Type annotation requires two types, the type and distribution; the - /// // distribution can be inferred. - /// let y = rng.sample::(Uniform::new(10, 15)); - /// ``` - fn sample>(&mut self, distr: D) -> T { - distr.sample(self) - } - - /// Create an iterator that generates values using the given distribution. - /// - /// Note that this function takes its arguments by value. This works since - /// `(&mut R): Rng where R: Rng` and - /// `(&D): Distribution where D: Distribution`, - /// however borrowing is not automatic hence `rng.sample_iter(...)` may - /// need to be replaced with `(&mut rng).sample_iter(...)`. - /// - /// # Example - /// - /// ``` - /// use rand::{thread_rng, Rng}; - /// use rand::distributions::{Alphanumeric, Uniform, Standard}; - /// - /// let rng = thread_rng(); - /// - /// // Vec of 16 x f32: - /// let v: Vec = rng.sample_iter(Standard).take(16).collect(); - /// - /// // String: - /// let s: String = rng.sample_iter(Alphanumeric).take(7).collect(); - /// - /// // Combined values - /// println!("{:?}", rng.sample_iter(Standard).take(5) - /// .collect::>()); - /// - /// // Dice-rolling: - /// let die_range = Uniform::new_inclusive(1, 6); - /// let mut roll_die = rng.sample_iter(die_range); - /// while roll_die.next().unwrap() != 6 { - /// println!("Not a 6; rolling again!"); - /// } - /// ``` - fn sample_iter(self, distr: D) -> distributions::DistIter - where D: Distribution, Self: Sized { - distr.sample_iter(self) - } - - /// Fill `dest` entirely with random bytes (uniform value distribution), - /// where `dest` is any type supporting [`AsByteSliceMut`], namely slices - /// and arrays over primitive integer types (`i8`, `i16`, `u32`, etc.). - /// - /// On big-endian platforms this performs byte-swapping to ensure - /// portability of results from reproducible generators. - /// - /// This uses [`fill_bytes`] internally which may handle some RNG errors - /// implicitly (e.g. waiting if the OS generator is not ready), but panics - /// on other errors. See also [`try_fill`] which returns errors. - /// - /// # Example - /// - /// ``` - /// use rand::{thread_rng, Rng}; - /// - /// let mut arr = [0i8; 20]; - /// thread_rng().fill(&mut arr[..]); - /// ``` - /// - /// [`fill_bytes`]: RngCore::fill_bytes - /// [`try_fill`]: Rng::try_fill - fn fill(&mut self, dest: &mut T) { - self.fill_bytes(dest.as_byte_slice_mut()); - dest.to_le(); - } - - /// Fill `dest` entirely with random bytes (uniform value distribution), - /// where `dest` is any type supporting [`AsByteSliceMut`], namely slices - /// and arrays over primitive integer types (`i8`, `i16`, `u32`, etc.). - /// - /// On big-endian platforms this performs byte-swapping to ensure - /// portability of results from reproducible generators. - /// - /// This is identical to [`fill`] except that it uses [`try_fill_bytes`] - /// internally and forwards RNG errors. - /// - /// # Example - /// - /// ``` - /// # use rand::Error; - /// use rand::{thread_rng, Rng}; - /// - /// # fn try_inner() -> Result<(), Error> { - /// let mut arr = [0u64; 4]; - /// thread_rng().try_fill(&mut arr[..])?; - /// # Ok(()) - /// # } - /// - /// # try_inner().unwrap() - /// ``` - /// - /// [`try_fill_bytes`]: RngCore::try_fill_bytes - /// [`fill`]: Rng::fill - fn try_fill(&mut self, dest: &mut T) -> Result<(), Error> { - self.try_fill_bytes(dest.as_byte_slice_mut())?; - dest.to_le(); - Ok(()) - } - - /// Return a bool with a probability `p` of being true. - /// - /// See also the [`Bernoulli`] distribution, which may be faster if - /// sampling from the same probability repeatedly. - /// - /// # Example - /// - /// ``` - /// use rand::{thread_rng, Rng}; - /// - /// let mut rng = thread_rng(); - /// println!("{}", rng.gen_bool(1.0 / 3.0)); - /// ``` - /// - /// # Panics - /// - /// If `p < 0` or `p > 1`. - /// - /// [`Bernoulli`]: distributions::bernoulli::Bernoulli - #[inline] - fn gen_bool(&mut self, p: f64) -> bool { - let d = distributions::Bernoulli::new(p).unwrap(); - self.sample(d) - } - - /// Return a bool with a probability of `numerator/denominator` of being - /// true. I.e. `gen_ratio(2, 3)` has chance of 2 in 3, or about 67%, of - /// returning true. If `numerator == denominator`, then the returned value - /// is guaranteed to be `true`. If `numerator == 0`, then the returned - /// value is guaranteed to be `false`. - /// - /// See also the [`Bernoulli`] distribution, which may be faster if - /// sampling from the same `numerator` and `denominator` repeatedly. - /// - /// # Panics - /// - /// If `denominator == 0` or `numerator > denominator`. - /// - /// # Example - /// - /// ``` - /// use rand::{thread_rng, Rng}; - /// - /// let mut rng = thread_rng(); - /// println!("{}", rng.gen_ratio(2, 3)); - /// ``` - /// - /// [`Bernoulli`]: distributions::bernoulli::Bernoulli - #[inline] - fn gen_ratio(&mut self, numerator: u32, denominator: u32) -> bool { - let d = distributions::Bernoulli::from_ratio(numerator, denominator).unwrap(); - self.sample(d) - } -} - -impl Rng for R {} - -/// Trait for casting types to byte slices -/// -/// This is used by the [`Rng::fill`] and [`Rng::try_fill`] methods. -pub trait AsByteSliceMut { - /// Return a mutable reference to self as a byte slice - fn as_byte_slice_mut(&mut self) -> &mut [u8]; - - /// Call `to_le` on each element (i.e. byte-swap on Big Endian platforms). - fn to_le(&mut self); -} - -impl AsByteSliceMut for [u8] { - fn as_byte_slice_mut(&mut self) -> &mut [u8] { - self - } - - fn to_le(&mut self) {} -} - -macro_rules! impl_as_byte_slice { - () => {}; - ($t:ty) => { - impl AsByteSliceMut for [$t] { - fn as_byte_slice_mut(&mut self) -> &mut [u8] { - if self.len() == 0 { - unsafe { - // must not use null pointer - slice::from_raw_parts_mut(0x1 as *mut u8, 0) - } - } else { - unsafe { - slice::from_raw_parts_mut(self.as_mut_ptr() - as *mut u8, - self.len() * mem::size_of::<$t>() - ) - } - } - } - - fn to_le(&mut self) { - for x in self { - *x = x.to_le(); - } - } - } - - impl AsByteSliceMut for [Wrapping<$t>] { - fn as_byte_slice_mut(&mut self) -> &mut [u8] { - if self.len() == 0 { - unsafe { - // must not use null pointer - slice::from_raw_parts_mut(0x1 as *mut u8, 0) - } - } else { - unsafe { - slice::from_raw_parts_mut(self.as_mut_ptr() - as *mut u8, - self.len() * mem::size_of::<$t>() - ) - } - } - } - - fn to_le(&mut self) { - for x in self { - *x = Wrapping(x.0.to_le()); - } - } - } - }; - ($t:ty, $($tt:ty,)*) => { - impl_as_byte_slice!($t); - // TODO: this could replace above impl once Rust #32463 is fixed - // impl_as_byte_slice!(Wrapping<$t>); - impl_as_byte_slice!($($tt,)*); - } -} - -impl_as_byte_slice!(u16, u32, u64, usize,); -#[cfg(not(target_os = "emscripten"))] impl_as_byte_slice!(u128); -impl_as_byte_slice!(i8, i16, i32, i64, isize,); -#[cfg(not(target_os = "emscripten"))] impl_as_byte_slice!(i128); - -macro_rules! impl_as_byte_slice_arrays { - ($n:expr,) => {}; - ($n:expr, $N:ident) => { - impl AsByteSliceMut for [T; $n] where [T]: AsByteSliceMut { - fn as_byte_slice_mut(&mut self) -> &mut [u8] { - self[..].as_byte_slice_mut() - } - - fn to_le(&mut self) { - self[..].to_le() - } - } - }; - ($n:expr, $N:ident, $($NN:ident,)*) => { - impl_as_byte_slice_arrays!($n, $N); - impl_as_byte_slice_arrays!($n - 1, $($NN,)*); - }; - (!div $n:expr,) => {}; - (!div $n:expr, $N:ident, $($NN:ident,)*) => { - impl_as_byte_slice_arrays!($n, $N); - impl_as_byte_slice_arrays!(!div $n / 2, $($NN,)*); - }; -} -impl_as_byte_slice_arrays!(32, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,); -impl_as_byte_slice_arrays!(!div 4096, N,N,N,N,N,N,N,); - -/// Generates a random value using the thread-local random number generator. -/// -/// This is simply a shortcut for `thread_rng().gen()`. See [`thread_rng`] for -/// documentation of the entropy source and [`Standard`] for documentation of -/// distributions and type-specific generation. -/// -/// # Examples -/// -/// ``` -/// let x = rand::random::(); -/// println!("{}", x); -/// -/// let y = rand::random::(); -/// println!("{}", y); -/// -/// if rand::random() { // generates a boolean -/// println!("Better lucky than good!"); -/// } -/// ``` -/// -/// If you're calling `random()` in a loop, caching the generator as in the -/// following example can increase performance. -/// -/// ``` -/// use rand::Rng; -/// -/// let mut v = vec![1, 2, 3]; -/// -/// for x in v.iter_mut() { -/// *x = rand::random() -/// } -/// -/// // can be made faster by caching thread_rng -/// -/// let mut rng = rand::thread_rng(); -/// -/// for x in v.iter_mut() { -/// *x = rng.gen(); -/// } -/// ``` -/// -/// [`Standard`]: distributions::Standard -#[cfg(feature="std")] -#[inline] -pub fn random() -> T -where Standard: Distribution { - thread_rng().gen() -} - -#[cfg(test)] -mod test { - use crate::rngs::mock::StepRng; - use super::*; - #[cfg(all(not(feature="std"), feature="alloc"))] use alloc::boxed::Box; - - /// Construct a deterministic RNG with the given seed - pub fn rng(seed: u64) -> impl RngCore { - // For tests, we want a statistically good, fast, reproducible RNG. - // PCG32 will do fine, and will be easy to embed if we ever need to. - const INC: u64 = 11634580027462260723; - rand_pcg::Pcg32::new(seed, INC) - } - - #[test] - fn test_fill_bytes_default() { - let mut r = StepRng::new(0x11_22_33_44_55_66_77_88, 0); - - // check every remainder mod 8, both in small and big vectors. - let lengths = [0, 1, 2, 3, 4, 5, 6, 7, - 80, 81, 82, 83, 84, 85, 86, 87]; - for &n in lengths.iter() { - let mut buffer = [0u8; 87]; - let v = &mut buffer[0..n]; - r.fill_bytes(v); - - // use this to get nicer error messages. - for (i, &byte) in v.iter().enumerate() { - if byte == 0 { - panic!("byte {} of {} is zero", i, n) - } - } - } - } - - #[test] - fn test_fill() { - let x = 9041086907909331047; // a random u64 - let mut rng = StepRng::new(x, 0); - - // Convert to byte sequence and back to u64; byte-swap twice if BE. - let mut array = [0u64; 2]; - rng.fill(&mut array[..]); - assert_eq!(array, [x, x]); - assert_eq!(rng.next_u64(), x); - - // Convert to bytes then u32 in LE order - let mut array = [0u32; 2]; - rng.fill(&mut array[..]); - assert_eq!(array, [x as u32, (x >> 32) as u32]); - assert_eq!(rng.next_u32(), x as u32); - - // Check equivalence using wrapped arrays - let mut warray = [Wrapping(0u32); 2]; - rng.fill(&mut warray[..]); - assert_eq!(array[0], warray[0].0); - assert_eq!(array[1], warray[1].0); - } - - #[test] - fn test_fill_empty() { - let mut array = [0u32; 0]; - let mut rng = StepRng::new(0, 1); - rng.fill(&mut array); - rng.fill(&mut array[..]); - } - - #[test] - fn test_gen_range() { - let mut r = rng(101); - for _ in 0..1000 { - let a = r.gen_range(-4711, 17); - assert!(a >= -4711 && a < 17); - let a = r.gen_range(-3i8, 42); - assert!(a >= -3i8 && a < 42i8); - let a = r.gen_range(&10u16, 99); - assert!(a >= 10u16 && a < 99u16); - let a = r.gen_range(-100i32, &2000); - assert!(a >= -100i32 && a < 2000i32); - let a = r.gen_range(&12u32, &24u32); - assert!(a >= 12u32 && a < 24u32); - - assert_eq!(r.gen_range(0u32, 1), 0u32); - assert_eq!(r.gen_range(-12i64, -11), -12i64); - assert_eq!(r.gen_range(3_000_000, 3_000_001), 3_000_000); - } - } - - #[test] - #[should_panic] - fn test_gen_range_panic_int() { - let mut r = rng(102); - r.gen_range(5, -2); - } - - #[test] - #[should_panic] - fn test_gen_range_panic_usize() { - let mut r = rng(103); - r.gen_range(5, 2); - } - - #[test] - fn test_gen_bool() { - let mut r = rng(105); - for _ in 0..5 { - assert_eq!(r.gen_bool(0.0), false); - assert_eq!(r.gen_bool(1.0), true); - } - } - - #[test] - fn test_rng_trait_object() { - use crate::distributions::{Distribution, Standard}; - let mut rng = rng(109); - let mut r = &mut rng as &mut dyn RngCore; - r.next_u32(); - r.gen::(); - assert_eq!(r.gen_range(0, 1), 0); - let _c: u8 = Standard.sample(&mut r); - } - - #[test] - #[cfg(feature="alloc")] - fn test_rng_boxed_trait() { - use crate::distributions::{Distribution, Standard}; - let rng = rng(110); - let mut r = Box::new(rng) as Box; - r.next_u32(); - r.gen::(); - assert_eq!(r.gen_range(0, 1), 0); - let _c: u8 = Standard.sample(&mut r); - } - - #[test] - #[cfg(feature="std")] - fn test_random() { - // not sure how to test this aside from just getting some values - let _n : usize = random(); - let _f : f32 = random(); - let _o : Option> = random(); - let _many : ((), - (usize, - isize, - Option<(u32, (bool,))>), - (u8, i8, u16, i16, u32, i32, u64, i64), - (f32, (f64, (f64,)))) = random(); - } - - #[test] - #[cfg(not(miri))] // Miri is too slow - fn test_gen_ratio_average() { - const NUM: u32 = 3; - const DENOM: u32 = 10; - const N: u32 = 100_000; - - let mut sum: u32 = 0; - let mut rng = rng(111); - for _ in 0..N { - if rng.gen_ratio(NUM, DENOM) { - sum += 1; - } - } - // Have Binomial(N, NUM/DENOM) distribution - let expected = (NUM * N) / DENOM; // exact integer - assert!(((sum - expected) as i32).abs() < 500); - } -} diff --git a/rand/src/prelude.rs b/rand/src/prelude.rs deleted file mode 100644 index 3c386e8..0000000 --- a/rand/src/prelude.rs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Convenience re-export of common members -//! -//! Like the standard library's prelude, this module simplifies importing of -//! common items. Unlike the standard prelude, the contents of this module must -//! be imported manually: -//! -//! ``` -//! use rand::prelude::*; -//! # let mut r = StdRng::from_rng(thread_rng()).unwrap(); -//! # let _: f32 = r.gen(); -//! ``` - -#[doc(no_inline)] pub use crate::distributions::Distribution; -#[doc(no_inline)] pub use crate::rngs::StdRng; -#[cfg(feature="small_rng")] -#[doc(no_inline)] pub use crate::rngs::SmallRng; -#[doc(no_inline)] #[cfg(feature="std")] pub use crate::rngs::ThreadRng; -#[doc(no_inline)] pub use crate::{Rng, RngCore, CryptoRng, SeedableRng}; -#[doc(no_inline)] #[cfg(feature="std")] pub use crate::{random, thread_rng}; -#[doc(no_inline)] pub use crate::seq::{SliceRandom, IteratorRandom}; diff --git a/rand/src/rngs/adapter/mod.rs b/rand/src/rngs/adapter/mod.rs deleted file mode 100644 index 659ff26..0000000 --- a/rand/src/rngs/adapter/mod.rs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Wrappers / adapters forming RNGs - -#[cfg(feature="std")] mod read; -mod reseeding; - -#[cfg(feature="std")] pub use self::read::{ReadRng, ReadError}; -pub use self::reseeding::ReseedingRng; diff --git a/rand/src/rngs/adapter/read.rs b/rand/src/rngs/adapter/read.rs deleted file mode 100644 index 901462e..0000000 --- a/rand/src/rngs/adapter/read.rs +++ /dev/null @@ -1,148 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// Copyright 2013 The Rust Project Developers. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! A wrapper around any Read to treat it as an RNG. - -use std::io::Read; -use std::fmt; - -use rand_core::{RngCore, Error, impls}; - - -/// An RNG that reads random bytes straight from any type supporting -/// [`std::io::Read`], for example files. -/// -/// This will work best with an infinite reader, but that is not required. -/// -/// This can be used with `/dev/urandom` on Unix but it is recommended to use -/// [`OsRng`] instead. -/// -/// # Panics -/// -/// `ReadRng` uses [`std::io::Read::read_exact`], which retries on interrupts. -/// All other errors from the underlying reader, including when it does not -/// have enough data, will only be reported through [`try_fill_bytes`]. -/// The other [`RngCore`] methods will panic in case of an error. -/// -/// # Example -/// -/// ``` -/// use rand::Rng; -/// use rand::rngs::adapter::ReadRng; -/// -/// let data = vec![1, 2, 3, 4, 5, 6, 7, 8]; -/// let mut rng = ReadRng::new(&data[..]); -/// println!("{:x}", rng.gen::()); -/// ``` -/// -/// [`OsRng`]: crate::rngs::OsRng -/// [`try_fill_bytes`]: RngCore::try_fill_bytes -#[derive(Debug)] -pub struct ReadRng { - reader: R -} - -impl ReadRng { - /// Create a new `ReadRng` from a `Read`. - pub fn new(r: R) -> ReadRng { - ReadRng { - reader: r - } - } -} - -impl RngCore for ReadRng { - 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]) { - self.try_fill_bytes(dest).unwrap_or_else(|err| - panic!("reading random bytes from Read implementation failed; error: {}", err)); - } - - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - if dest.is_empty() { return Ok(()); } - // Use `std::io::read_exact`, which retries on `ErrorKind::Interrupted`. - self.reader.read_exact(dest).map_err(|e| Error::new(ReadError(e))) - } -} - -/// `ReadRng` error type -#[derive(Debug)] -pub struct ReadError(std::io::Error); - -impl fmt::Display for ReadError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "ReadError: {}", self.0) - } -} - -impl std::error::Error for ReadError { - fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - Some(&self.0) - } -} - - -#[cfg(test)] -mod test { - use super::ReadRng; - use crate::RngCore; - - #[test] - fn test_reader_rng_u64() { - // transmute from the target to avoid endianness concerns. - let v = vec![0u8, 0, 0, 0, 0, 0, 0, 1, - 0 , 0, 0, 0, 0, 0, 0, 2, - 0, 0, 0, 0, 0, 0, 0, 3]; - let mut rng = ReadRng::new(&v[..]); - - assert_eq!(rng.next_u64(), 1_u64.to_be()); - assert_eq!(rng.next_u64(), 2_u64.to_be()); - assert_eq!(rng.next_u64(), 3_u64.to_be()); - } - - #[test] - fn test_reader_rng_u32() { - let v = vec![0u8, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3]; - let mut rng = ReadRng::new(&v[..]); - - assert_eq!(rng.next_u32(), 1_u32.to_be()); - assert_eq!(rng.next_u32(), 2_u32.to_be()); - assert_eq!(rng.next_u32(), 3_u32.to_be()); - } - - #[test] - fn test_reader_rng_fill_bytes() { - let v = [1u8, 2, 3, 4, 5, 6, 7, 8]; - let mut w = [0u8; 8]; - - let mut rng = ReadRng::new(&v[..]); - rng.fill_bytes(&mut w); - - assert!(v == w); - } - - #[test] - fn test_reader_rng_insufficient_bytes() { - let v = [1u8, 2, 3, 4, 5, 6, 7, 8]; - let mut w = [0u8; 9]; - - let mut rng = ReadRng::new(&v[..]); - - let result = rng.try_fill_bytes(&mut w); - assert!(result.is_err()); - println!("Error: {}", result.unwrap_err()); - } -} diff --git a/rand/src/rngs/adapter/reseeding.rs b/rand/src/rngs/adapter/reseeding.rs deleted file mode 100644 index ec88efe..0000000 --- a/rand/src/rngs/adapter/reseeding.rs +++ /dev/null @@ -1,357 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// Copyright 2013 The Rust Project Developers. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! A wrapper around another PRNG that reseeds it after it -//! generates a certain number of random bytes. - -use core::mem::size_of; - -use rand_core::{RngCore, CryptoRng, SeedableRng, Error}; -use rand_core::block::{BlockRngCore, BlockRng}; - -/// A wrapper around any PRNG that implements [`BlockRngCore`], that adds the -/// ability to reseed it. -/// -/// `ReseedingRng` reseeds the underlying PRNG in the following cases: -/// -/// - On a manual call to [`reseed()`]. -/// - After `clone()`, the clone will be reseeded on first use. -/// - After a process is forked, the RNG in the child process is reseeded within -/// the next few generated values, depending on the block size of the -/// underlying PRNG. For ChaCha and Hc128 this is a maximum of -/// 15 `u32` values before reseeding. -/// - After the PRNG has generated a configurable number of random bytes. -/// -/// # When should reseeding after a fixed number of generated bytes be used? -/// -/// Reseeding after a fixed number of generated bytes is never strictly -/// *necessary*. Cryptographic PRNGs don't have a limited number of bytes they -/// can output, or at least not a limit reachable in any practical way. There is -/// no such thing as 'running out of entropy'. -/// -/// Occasionally reseeding can be seen as some form of 'security in depth'. Even -/// if in the future a cryptographic weakness is found in the CSPRNG being used, -/// or a flaw in the implementation, occasionally reseeding should make -/// exploiting it much more difficult or even impossible. -/// -/// Use [`ReseedingRng::new`] with a `threshold` of `0` to disable reseeding -/// after a fixed number of generated bytes. -/// -/// # Error handling -/// -/// Although unlikely, reseeding the wrapped PRNG can fail. `ReseedingRng` will -/// never panic but try to handle the error intelligently through some -/// combination of retrying and delaying reseeding until later. -/// If handling the source error fails `ReseedingRng` will continue generating -/// data from the wrapped PRNG without reseeding. -/// -/// Manually calling [`reseed()`] will not have this retry or delay logic, but -/// reports the error. -/// -/// # Example -/// -/// ``` -/// use rand::prelude::*; -/// use rand_chacha::ChaCha20Core; // Internal part of ChaChaRng that -/// // implements BlockRngCore -/// use rand::rngs::OsRng; -/// use rand::rngs::adapter::ReseedingRng; -/// -/// let prng = ChaCha20Core::from_entropy(); -/// let mut reseeding_rng = ReseedingRng::new(prng, 0, OsRng); -/// -/// println!("{}", reseeding_rng.gen::()); -/// -/// let mut cloned_rng = reseeding_rng.clone(); -/// assert!(reseeding_rng.gen::() != cloned_rng.gen::()); -/// ``` -/// -/// [`BlockRngCore`]: rand_core::block::BlockRngCore -/// [`ReseedingRng::new`]: ReseedingRng::new -/// [`reseed()`]: ReseedingRng::reseed -#[derive(Debug)] -pub struct ReseedingRng(BlockRng>) -where R: BlockRngCore + SeedableRng, - Rsdr: RngCore; - -impl ReseedingRng -where R: BlockRngCore + SeedableRng, - Rsdr: RngCore -{ - /// Create a new `ReseedingRng` from an existing PRNG, combined with a RNG - /// to use as reseeder. - /// - /// `threshold` sets the number of generated bytes after which to reseed the - /// PRNG. Set it to zero to never reseed based on the number of generated - /// values. - pub fn new(rng: R, threshold: u64, reseeder: Rsdr) -> Self { - ReseedingRng(BlockRng::new(ReseedingCore::new(rng, threshold, reseeder))) - } - - /// Reseed the internal PRNG. - pub fn reseed(&mut self) -> Result<(), Error> { - self.0.core.reseed() - } -} - -// TODO: this should be implemented for any type where the inner type -// implements RngCore, but we can't specify that because ReseedingCore is private -impl RngCore for ReseedingRng -where R: BlockRngCore + SeedableRng, - ::Results: AsRef<[u32]> + AsMut<[u32]> -{ - #[inline(always)] - fn next_u32(&mut self) -> u32 { - self.0.next_u32() - } - - #[inline(always)] - fn next_u64(&mut self) -> u64 { - self.0.next_u64() - } - - fn fill_bytes(&mut self, dest: &mut [u8]) { - self.0.fill_bytes(dest) - } - - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - self.0.try_fill_bytes(dest) - } -} - -impl Clone for ReseedingRng -where R: BlockRngCore + SeedableRng + Clone, - Rsdr: RngCore + Clone -{ - fn clone(&self) -> ReseedingRng { - // Recreating `BlockRng` seems easier than cloning it and resetting - // the index. - ReseedingRng(BlockRng::new(self.0.core.clone())) - } -} - -impl CryptoRng for ReseedingRng -where R: BlockRngCore + SeedableRng + CryptoRng, - Rsdr: RngCore + CryptoRng {} - -#[derive(Debug)] -struct ReseedingCore { - inner: R, - reseeder: Rsdr, - threshold: i64, - bytes_until_reseed: i64, - fork_counter: usize, -} - -impl BlockRngCore for ReseedingCore -where R: BlockRngCore + SeedableRng, - Rsdr: RngCore -{ - type Item = ::Item; - type Results = ::Results; - - fn generate(&mut self, results: &mut Self::Results) { - let global_fork_counter = fork::get_fork_counter(); - if self.bytes_until_reseed <= 0 || - self.is_forked(global_fork_counter) { - // We get better performance by not calling only `reseed` here - // and continuing with the rest of the function, but by directly - // returning from a non-inlined function. - return self.reseed_and_generate(results, global_fork_counter); - } - let num_bytes = results.as_ref().len() * size_of::(); - self.bytes_until_reseed -= num_bytes as i64; - self.inner.generate(results); - } -} - -impl ReseedingCore -where R: BlockRngCore + SeedableRng, - Rsdr: RngCore -{ - /// Create a new `ReseedingCore`. - fn new(rng: R, threshold: u64, reseeder: Rsdr) -> Self { - use ::core::i64::MAX; - fork::register_fork_handler(); - - // Because generating more values than `i64::MAX` takes centuries on - // current hardware, we just clamp to that value. - // Also we set a threshold of 0, which indicates no limit, to that - // value. - let threshold = - if threshold == 0 { MAX } - else if threshold <= MAX as u64 { threshold as i64 } - else { MAX }; - - ReseedingCore { - inner: rng, - reseeder, - threshold: threshold as i64, - bytes_until_reseed: threshold as i64, - fork_counter: 0, - } - } - - /// Reseed the internal PRNG. - fn reseed(&mut self) -> Result<(), Error> { - R::from_rng(&mut self.reseeder).map(|result| { - self.bytes_until_reseed = self.threshold; - self.inner = result - }) - } - - fn is_forked(&self, global_fork_counter: usize) -> bool { - // In theory, on 32-bit platforms, it is possible for - // `global_fork_counter` to wrap around after ~4e9 forks. - // - // This check will detect a fork in the normal case where - // `fork_counter < global_fork_counter`, and also when the difference - // between both is greater than `isize::MAX` (wrapped around). - // - // It will still fail to detect a fork if there have been more than - // `isize::MAX` forks, without any reseed in between. Seems unlikely - // enough. - (self.fork_counter.wrapping_sub(global_fork_counter) as isize) < 0 - } - - #[inline(never)] - fn reseed_and_generate(&mut self, - results: &mut ::Results, - global_fork_counter: usize) - { - #![allow(clippy::if_same_then_else)] // false positive - if self.is_forked(global_fork_counter) { - info!("Fork detected, reseeding RNG"); - } else { - trace!("Reseeding RNG (periodic reseed)"); - } - - let num_bytes = - results.as_ref().len() * size_of::<::Item>(); - - if let Err(e) = self.reseed() { - warn!("Reseeding RNG failed: {}", e); - let _ = e; - } - self.fork_counter = global_fork_counter; - - self.bytes_until_reseed = self.threshold - num_bytes as i64; - self.inner.generate(results); - } -} - -impl Clone for ReseedingCore -where R: BlockRngCore + SeedableRng + Clone, - Rsdr: RngCore + Clone -{ - fn clone(&self) -> ReseedingCore { - ReseedingCore { - inner: self.inner.clone(), - reseeder: self.reseeder.clone(), - threshold: self.threshold, - bytes_until_reseed: 0, // reseed clone on first use - fork_counter: self.fork_counter, - } - } -} - -impl CryptoRng for ReseedingCore -where R: BlockRngCore + SeedableRng + CryptoRng, - Rsdr: RngCore + CryptoRng {} - - -#[cfg(all(unix, not(target_os="emscripten")))] -mod fork { - use core::sync::atomic::{AtomicUsize, AtomicBool, Ordering}; - #[allow(deprecated)] // Required for compatibility with Rust < 1.24. - use core::sync::atomic::{ATOMIC_USIZE_INIT, ATOMIC_BOOL_INIT}; - - // Fork protection - // - // We implement fork protection on Unix using `pthread_atfork`. - // When the process is forked, we increment `RESEEDING_RNG_FORK_COUNTER`. - // Every `ReseedingRng` stores the last known value of the static in - // `fork_counter`. If the cached `fork_counter` is less than - // `RESEEDING_RNG_FORK_COUNTER`, it is time to reseed this RNG. - // - // If reseeding fails, we don't deal with this by setting a delay, but just - // don't update `fork_counter`, so a reseed is attempted as soon as - // possible. - - #[allow(deprecated)] - static RESEEDING_RNG_FORK_COUNTER: AtomicUsize = ATOMIC_USIZE_INIT; - - pub fn get_fork_counter() -> usize { - RESEEDING_RNG_FORK_COUNTER.load(Ordering::Relaxed) - } - - #[allow(deprecated)] - static FORK_HANDLER_REGISTERED: AtomicBool = ATOMIC_BOOL_INIT; - - extern fn fork_handler() { - // Note: fetch_add is defined to wrap on overflow - // (which is what we want). - RESEEDING_RNG_FORK_COUNTER.fetch_add(1, Ordering::Relaxed); - } - - pub fn register_fork_handler() { - if !FORK_HANDLER_REGISTERED.load(Ordering::Relaxed) { - unsafe { libc::pthread_atfork(None, None, Some(fork_handler)) }; - FORK_HANDLER_REGISTERED.store(true, Ordering::Relaxed); - } - } -} - -#[cfg(not(all(unix, not(target_os="emscripten"))))] -mod fork { - pub fn get_fork_counter() -> usize { 0 } - pub fn register_fork_handler() {} -} - - -#[cfg(test)] -mod test { - use crate::{Rng, SeedableRng}; - use crate::rngs::std::Core; - use crate::rngs::mock::StepRng; - use super::ReseedingRng; - - #[test] - fn test_reseeding() { - let mut zero = StepRng::new(0, 0); - let rng = Core::from_rng(&mut zero).unwrap(); - let thresh = 1; // reseed every time the buffer is exhausted - let mut reseeding = ReseedingRng::new(rng, thresh, zero); - - // RNG buffer size is [u32; 64] - // Debug is only implemented up to length 32 so use two arrays - let mut buf = ([0u32; 32], [0u32; 32]); - reseeding.fill(&mut buf.0); - reseeding.fill(&mut buf.1); - let seq = buf; - for _ in 0..10 { - reseeding.fill(&mut buf.0); - reseeding.fill(&mut buf.1); - assert_eq!(buf, seq); - } - } - - #[test] - fn test_clone_reseeding() { - let mut zero = StepRng::new(0, 0); - let rng = Core::from_rng(&mut zero).unwrap(); - let mut rng1 = ReseedingRng::new(rng, 32*4, zero); - - let first: u32 = rng1.gen(); - for _ in 0..10 { let _ = rng1.gen::(); } - - let mut rng2 = rng1.clone(); - assert_eq!(first, rng2.gen::()); - } -} diff --git a/rand/src/rngs/entropy.rs b/rand/src/rngs/entropy.rs deleted file mode 100644 index 1ed59ab..0000000 --- a/rand/src/rngs/entropy.rs +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Entropy generator, or wrapper around external generators - -#![allow(deprecated)] // whole module is deprecated - -use rand_core::{RngCore, CryptoRng, Error}; -use crate::rngs::OsRng; - -/// An interface returning random data from external source(s), provided -/// specifically for securely seeding algorithmic generators (PRNGs). -/// -/// This is deprecated. It is suggested you use [`rngs::OsRng`] instead. -/// -/// [`rngs::OsRng`]: crate::rngs::OsRng -#[derive(Debug)] -#[deprecated(since="0.7.0", note="use rngs::OsRng instead")] -pub struct EntropyRng { - source: OsRng, -} - -impl EntropyRng { - /// Create a new `EntropyRng`. - /// - /// This method will do no system calls or other initialization routines, - /// those are done on first use. This is done to make `new` infallible, - /// and `try_fill_bytes` the only place to report errors. - pub fn new() -> Self { - EntropyRng { source: OsRng } - } -} - -impl Default for EntropyRng { - fn default() -> Self { - EntropyRng::new() - } -} - -impl RngCore for EntropyRng { - fn next_u32(&mut self) -> u32 { - self.source.next_u32() - } - - fn next_u64(&mut self) -> u64 { - self.source.next_u64() - } - - fn fill_bytes(&mut self, dest: &mut [u8]) { - self.source.fill_bytes(dest) - } - - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - self.source.try_fill_bytes(dest) - } -} - -impl CryptoRng for EntropyRng {} - - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn test_entropy() { - let mut rng = EntropyRng::new(); - let n = (rng.next_u32() ^ rng.next_u32()).count_ones(); - assert!(n >= 2); // p(failure) approx 1e-7 - } -} diff --git a/rand/src/rngs/mock.rs b/rand/src/rngs/mock.rs deleted file mode 100644 index b4081da..0000000 --- a/rand/src/rngs/mock.rs +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Mock random number generator - -use rand_core::{RngCore, Error, impls}; - -/// A simple implementation of `RngCore` for testing purposes. -/// -/// This generates an arithmetic sequence (i.e. adds a constant each step) -/// over a `u64` number, using wrapping arithmetic. If the increment is 0 -/// the generator yields a constant. -/// -/// ``` -/// use rand::Rng; -/// use rand::rngs::mock::StepRng; -/// -/// let mut my_rng = StepRng::new(2, 1); -/// let sample: [u64; 3] = my_rng.gen(); -/// assert_eq!(sample, [2, 3, 4]); -/// ``` -#[derive(Debug, Clone)] -pub struct StepRng { - v: u64, - a: u64, -} - -impl StepRng { - /// Create a `StepRng`, yielding an arithmetic sequence starting with - /// `initial` and incremented by `increment` each time. - pub fn new(initial: u64, increment: u64) -> Self { - StepRng { v: initial, a: increment } - } -} - -impl RngCore for StepRng { - #[inline] - fn next_u32(&mut self) -> u32 { - self.next_u64() as u32 - } - - #[inline] - fn next_u64(&mut self) -> u64 { - let result = self.v; - self.v = self.v.wrapping_add(self.a); - result - } - - #[inline] - fn fill_bytes(&mut self, dest: &mut [u8]) { - impls::fill_bytes_via_next(self, dest); - } - - #[inline] - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - self.fill_bytes(dest); - Ok(()) - } -} diff --git a/rand/src/rngs/mod.rs b/rand/src/rngs/mod.rs deleted file mode 100644 index abf3243..0000000 --- a/rand/src/rngs/mod.rs +++ /dev/null @@ -1,119 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Random number generators and adapters -//! -//! ## Background: Random number generators (RNGs) -//! -//! Computers cannot produce random numbers from nowhere. We classify -//! random number generators as follows: -//! -//! - "True" random number generators (TRNGs) use hard-to-predict data sources -//! (e.g. the high-resolution parts of event timings and sensor jitter) to -//! harvest random bit-sequences, apply algorithms to remove bias and -//! estimate available entropy, then combine these bits into a byte-sequence -//! or an entropy pool. This job is usually done by the operating system or -//! a hardware generator (HRNG). -//! - "Pseudo"-random number generators (PRNGs) use algorithms to transform a -//! seed into a sequence of pseudo-random numbers. These generators can be -//! fast and produce well-distributed unpredictable random numbers (or not). -//! They are usually deterministic: given algorithm and seed, the output -//! sequence can be reproduced. They have finite period and eventually loop; -//! with many algorithms this period is fixed and can be proven sufficiently -//! long, while others are chaotic and the period depends on the seed. -//! - "Cryptographically secure" pseudo-random number generators (CSPRNGs) -//! are the sub-set of PRNGs which are secure. Security of the generator -//! relies both on hiding the internal state and using a strong algorithm. -//! -//! ## Traits and functionality -//! -//! All RNGs implement the [`RngCore`] trait, as a consequence of which the -//! [`Rng`] extension trait is automatically implemented. Secure RNGs may -//! additionally implement the [`CryptoRng`] trait. -//! -//! All PRNGs require a seed to produce their random number sequence. The -//! [`SeedableRng`] trait provides three ways of constructing PRNGs: -//! -//! - `from_seed` accepts a type specific to the PRNG -//! - `from_rng` allows a PRNG to be seeded from any other RNG -//! - `seed_from_u64` allows any PRNG to be seeded from a `u64` insecurely -//! - `from_entropy` securely seeds a PRNG from fresh entropy -//! -//! Use the [`rand_core`] crate when implementing your own RNGs. -//! -//! ## Our generators -//! -//! This crate provides several random number generators: -//! -//! - [`OsRng`] is an interface to the operating system's random number -//! source. Typically the operating system uses a CSPRNG with entropy -//! provided by a TRNG and some type of on-going re-seeding. -//! - [`ThreadRng`], provided by the [`thread_rng`] function, is a handle to a -//! thread-local CSPRNG with periodic seeding from [`OsRng`]. Because this -//! is local, it is typically much faster than [`OsRng`]. It should be -//! secure, though the paranoid may prefer [`OsRng`]. -//! - [`StdRng`] is a CSPRNG chosen for good performance and trust of security -//! (based on reviews, maturity and usage). The current algorithm is ChaCha20, -//! which is well established and rigorously analysed. -//! [`StdRng`] provides the algorithm used by [`ThreadRng`] but without -//! periodic reseeding. -//! - [`SmallRng`] is an **insecure** PRNG designed to be fast, simple, require -//! little memory, and have good output quality. -//! -//! The algorithms selected for [`StdRng`] and [`SmallRng`] may change in any -//! release and may be platform-dependent, therefore they should be considered -//! **not reproducible**. -//! -//! ## Additional generators -//! -//! **TRNGs**: The [`rdrand`] crate provides an interface to the RDRAND and -//! RDSEED instructions available in modern Intel and AMD CPUs. -//! The [`rand_jitter`] crate provides a user-space implementation of -//! entropy harvesting from CPU timer jitter, but is very slow and has -//! [security issues](https://github.com/rust-random/rand/issues/699). -//! -//! **PRNGs**: Several companion crates are available, providing individual or -//! families of PRNG algorithms. These provide the implementations behind -//! [`StdRng`] and [`SmallRng`] but can also be used directly, indeed *should* -//! be used directly when **reproducibility** matters. -//! Some suggestions are: [`rand_chacha`], [`rand_pcg`], [`rand_xoshiro`]. -//! A full list can be found by searching for crates with the [`rng` tag]. -//! -//! [`SmallRng`]: rngs::SmallRng -//! [`StdRng`]: rngs::StdRng -//! [`OsRng`]: rngs::OsRng -//! [`ThreadRng`]: rngs::ThreadRng -//! [`mock::StepRng`]: rngs::mock::StepRng -//! [`adapter::ReadRng`]: rngs::adapter::ReadRng -//! [`adapter::ReseedingRng`]: rngs::adapter::ReseedingRng -//! [`rdrand`]: https://crates.io/crates/rdrand -//! [`rand_jitter`]: https://crates.io/crates/rand_jitter -//! [`rand_chacha`]: https://crates.io/crates/rand_chacha -//! [`rand_pcg`]: https://crates.io/crates/rand_pcg -//! [`rand_xoshiro`]: https://crates.io/crates/rand_xoshiro -//! [`rng` tag]: https://crates.io/keywords/rng - -pub mod adapter; - -#[cfg(feature="std")] mod entropy; -pub mod mock; // Public so we don't export `StepRng` directly, making it a bit - // more clear it is intended for testing. -#[cfg(feature="small_rng")] -mod small; -mod std; -#[cfg(feature="std")] pub(crate) mod thread; - -#[allow(deprecated)] -#[cfg(feature="std")] pub use self::entropy::EntropyRng; - -#[cfg(feature="small_rng")] -pub use self::small::SmallRng; -pub use self::std::StdRng; -#[cfg(feature="std")] pub use self::thread::ThreadRng; - -#[cfg(feature="getrandom")] pub use rand_core::OsRng; diff --git a/rand/src/rngs/small.rs b/rand/src/rngs/small.rs deleted file mode 100644 index 6571363..0000000 --- a/rand/src/rngs/small.rs +++ /dev/null @@ -1,115 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! A small fast RNG - -use rand_core::{RngCore, SeedableRng, Error}; - -#[cfg(all(not(target_os = "emscripten"), target_pointer_width = "64"))] -type Rng = rand_pcg::Pcg64Mcg; -#[cfg(not(all(not(target_os = "emscripten"), target_pointer_width = "64")))] -type Rng = rand_pcg::Pcg32; - -/// A small-state, fast non-crypto PRNG -/// -/// `SmallRng` may be a good choice when a PRNG with small state, cheap -/// initialization, good statistical quality and good performance are required. -/// It is **not** a good choice when security against prediction or -/// reproducibility are important. -/// -/// This PRNG is **feature-gated**: to use, you must enable the crate feature -/// `small_rng`. -/// -/// The algorithm is deterministic but should not be considered reproducible -/// due to dependence on platform and possible replacement in future -/// library versions. For a reproducible generator, use a named PRNG from an -/// external crate, e.g. [rand_pcg] or [rand_chacha]. -/// Refer also to [The Book](https://rust-random.github.io/book/guide-rngs.html). -/// -/// The PRNG algorithm in `SmallRng` is chosen to be -/// efficient on the current platform, without consideration for cryptography -/// or security. The size of its state is much smaller than [`StdRng`]. -/// The current algorithm is [`Pcg64Mcg`](rand_pcg::Pcg64Mcg) on 64-bit -/// platforms and [`Pcg32`](rand_pcg::Pcg32) on 32-bit platforms. Both are -/// implemented by the [rand_pcg] crate. -/// -/// # Examples -/// -/// Initializing `SmallRng` with a random seed can be done using [`SeedableRng::from_entropy`]: -/// -/// ``` -/// use rand::{Rng, SeedableRng}; -/// use rand::rngs::SmallRng; -/// -/// // Create small, cheap to initialize and fast RNG with a random seed. -/// // The randomness is supplied by the operating system. -/// let mut small_rng = SmallRng::from_entropy(); -/// # let v: u32 = small_rng.gen(); -/// ``` -/// -/// When initializing a lot of `SmallRng`'s, using [`thread_rng`] can be more -/// efficient: -/// -/// ``` -/// use std::iter; -/// use rand::{SeedableRng, thread_rng}; -/// use rand::rngs::SmallRng; -/// -/// // Create a big, expensive to initialize and slower, but unpredictable RNG. -/// // This is cached and done only once per thread. -/// let mut thread_rng = thread_rng(); -/// // Create small, cheap to initialize and fast RNGs with random seeds. -/// // One can generally assume this won't fail. -/// let rngs: Vec = iter::repeat(()) -/// .map(|()| SmallRng::from_rng(&mut thread_rng).unwrap()) -/// .take(10) -/// .collect(); -/// ``` -/// -/// [`StdRng`]: crate::rngs::StdRng -/// [`thread_rng`]: crate::thread_rng -/// [rand_chacha]: https://crates.io/crates/rand_chacha -/// [rand_pcg]: https://crates.io/crates/rand_pcg -#[derive(Clone, Debug)] -pub struct SmallRng(Rng); - -impl RngCore for SmallRng { - #[inline(always)] - fn next_u32(&mut self) -> u32 { - self.0.next_u32() - } - - #[inline(always)] - fn next_u64(&mut self) -> u64 { - self.0.next_u64() - } - - #[inline(always)] - fn fill_bytes(&mut self, dest: &mut [u8]) { - self.0.fill_bytes(dest); - } - - #[inline(always)] - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - self.0.try_fill_bytes(dest) - } -} - -impl SeedableRng for SmallRng { - type Seed = ::Seed; - - #[inline(always)] - fn from_seed(seed: Self::Seed) -> Self { - SmallRng(Rng::from_seed(seed)) - } - - #[inline(always)] - fn from_rng(rng: R) -> Result { - Rng::from_rng(rng).map(SmallRng) - } -} diff --git a/rand/src/rngs/std.rs b/rand/src/rngs/std.rs deleted file mode 100644 index 22e08ae..0000000 --- a/rand/src/rngs/std.rs +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The standard RNG - -use crate::{RngCore, CryptoRng, Error, SeedableRng}; - -#[cfg(target_os = "emscripten")] pub(crate) use rand_hc::Hc128Core as Core; -#[cfg(not(target_os = "emscripten"))] pub(crate) use rand_chacha::ChaCha20Core as Core; -#[cfg(target_os = "emscripten")] use rand_hc::Hc128Rng as Rng; -#[cfg(not(target_os = "emscripten"))] use rand_chacha::ChaCha20Rng as Rng; - -/// The standard RNG. The PRNG algorithm in `StdRng` is chosen to be efficient -/// on the current platform, to be statistically strong and unpredictable -/// (meaning a cryptographically secure PRNG). -/// -/// The current algorithm used is the ChaCha block cipher with either 20 or 12 -/// rounds (see the `stdrng_*` feature flags, documented in the README). -/// This may change as new evidence of cipher security and performance -/// becomes available. -/// -/// The algorithm is deterministic but should not be considered reproducible -/// due to dependence on configuration and possible replacement in future -/// library versions. For a secure reproducible generator, we recommend use of -/// the [rand_chacha] crate directly. -/// -/// [rand_chacha]: https://crates.io/crates/rand_chacha -#[derive(Clone, Debug)] -pub struct StdRng(Rng); - -impl RngCore for StdRng { - #[inline(always)] - fn next_u32(&mut self) -> u32 { - self.0.next_u32() - } - - #[inline(always)] - fn next_u64(&mut self) -> u64 { - self.0.next_u64() - } - - #[inline(always)] - fn fill_bytes(&mut self, dest: &mut [u8]) { - self.0.fill_bytes(dest); - } - - #[inline(always)] - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - self.0.try_fill_bytes(dest) - } -} - -impl SeedableRng for StdRng { - type Seed = ::Seed; - - #[inline(always)] - fn from_seed(seed: Self::Seed) -> Self { - StdRng(Rng::from_seed(seed)) - } - - #[inline(always)] - fn from_rng(rng: R) -> Result { - Rng::from_rng(rng).map(StdRng) - } -} - -impl CryptoRng for StdRng {} - - -#[cfg(test)] -mod test { - use crate::{RngCore, SeedableRng}; - use crate::rngs::StdRng; - - #[test] - fn test_stdrng_construction() { - // Test value-stability of StdRng. This is expected to break any time - // the algorithm is changed. - let seed = [1,0,0,0, 23,0,0,0, 200,1,0,0, 210,30,0,0, - 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; - - #[cfg(any(feature="stdrng_strong", not(feature="stdrng_fast")))] - let target = [3950704604716924505, 5573172343717151650]; - #[cfg(all(not(feature="stdrng_strong"), feature="stdrng_fast"))] - let target = [10719222850664546238, 14064965282130556830]; - - let mut rng0 = StdRng::from_seed(seed); - let x0 = rng0.next_u64(); - - let mut rng1 = StdRng::from_rng(rng0).unwrap(); - let x1 = rng1.next_u64(); - - assert_eq!([x0, x1], target); - } -} diff --git a/rand/src/rngs/thread.rs b/rand/src/rngs/thread.rs deleted file mode 100644 index 2006f41..0000000 --- a/rand/src/rngs/thread.rs +++ /dev/null @@ -1,124 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Thread-local random number generator - -use std::cell::UnsafeCell; -use std::ptr::NonNull; - -use crate::{RngCore, CryptoRng, SeedableRng, Error}; -use crate::rngs::adapter::ReseedingRng; -use crate::rngs::OsRng; -use super::std::Core; - -// Rationale for using `UnsafeCell` in `ThreadRng`: -// -// Previously we used a `RefCell`, with an overhead of ~15%. There will only -// ever be one mutable reference to the interior of the `UnsafeCell`, because -// we only have such a reference inside `next_u32`, `next_u64`, etc. Within a -// single thread (which is the definition of `ThreadRng`), there will only ever -// be one of these methods active at a time. -// -// A possible scenario where there could be multiple mutable references is if -// `ThreadRng` is used inside `next_u32` and co. But the implementation is -// completely under our control. We just have to ensure none of them use -// `ThreadRng` internally, which is nonsensical anyway. We should also never run -// `ThreadRng` in destructors of its implementation, which is also nonsensical. - - -// Number of generated bytes after which to reseed `ThreadRng`. -// According to benchmarks, reseeding has a noticable impact with thresholds -// of 32 kB and less. We choose 64 kB to avoid significant overhead. -const THREAD_RNG_RESEED_THRESHOLD: u64 = 1024 * 64; - -/// The type returned by [`thread_rng`], essentially just a reference to the -/// PRNG in thread-local memory. -/// -/// `ThreadRng` uses the same PRNG as [`StdRng`] for security and performance. -/// As hinted by the name, the generator is thread-local. `ThreadRng` is a -/// handle to this generator and thus supports `Copy`, but not `Send` or `Sync`. -/// -/// Unlike `StdRng`, `ThreadRng` uses the [`ReseedingRng`] wrapper to reseed -/// the PRNG from fresh entropy every 64 kiB of random data. -/// [`OsRng`] is used to provide seed data. -/// -/// Note that the reseeding is done as an extra precaution against side-channel -/// attacks and mis-use (e.g. if somehow weak entropy were supplied initially). -/// The PRNG algorithms used are assumed to be secure. -/// -/// [`ReseedingRng`]: crate::rngs::adapter::ReseedingRng -/// [`StdRng`]: crate::rngs::StdRng -#[derive(Copy, Clone, Debug)] -pub struct ThreadRng { - // inner raw pointer implies type is neither Send nor Sync - rng: NonNull>, -} - -thread_local!( - static THREAD_RNG_KEY: UnsafeCell> = { - let r = Core::from_rng(OsRng).unwrap_or_else(|err| - panic!("could not initialize thread_rng: {}", err)); - let rng = ReseedingRng::new(r, - THREAD_RNG_RESEED_THRESHOLD, - OsRng); - UnsafeCell::new(rng) - } -); - -/// Retrieve the lazily-initialized thread-local random number generator, -/// seeded by the system. Intended to be used in method chaining style, -/// e.g. `thread_rng().gen::()`, or cached locally, e.g. -/// `let mut rng = thread_rng();`. Invoked by the `Default` trait, making -/// `ThreadRng::default()` equivalent. -/// -/// For more information see [`ThreadRng`]. -pub fn thread_rng() -> ThreadRng { - let raw = THREAD_RNG_KEY.with(|t| t.get()); - let nn = NonNull::new(raw).unwrap(); - ThreadRng { rng: nn } -} - -impl Default for ThreadRng { - fn default() -> ThreadRng { - crate::prelude::thread_rng() - } -} - -impl RngCore for ThreadRng { - #[inline(always)] - fn next_u32(&mut self) -> u32 { - unsafe { self.rng.as_mut().next_u32() } - } - - #[inline(always)] - fn next_u64(&mut self) -> u64 { - unsafe { self.rng.as_mut().next_u64() } - } - - fn fill_bytes(&mut self, dest: &mut [u8]) { - unsafe { self.rng.as_mut().fill_bytes(dest) } - } - - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - unsafe { self.rng.as_mut().try_fill_bytes(dest) } - } -} - -impl CryptoRng for ThreadRng {} - - -#[cfg(test)] -mod test { - #[test] - fn test_thread_rng() { - use crate::Rng; - let mut r = crate::thread_rng(); - r.gen::(); - assert_eq!(r.gen_range(0, 1), 0); - } -} diff --git a/rand/src/seq/index.rs b/rand/src/seq/index.rs deleted file mode 100644 index 22a5733..0000000 --- a/rand/src/seq/index.rs +++ /dev/null @@ -1,409 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Low-level API for sampling indices - -#[cfg(feature="alloc")] use core::slice; - -#[cfg(feature="std")] use std::vec; -#[cfg(all(feature="alloc", not(feature="std")))] use crate::alloc::vec::{self, Vec}; -// BTreeMap is not as fast in tests, but better than nothing. -#[cfg(feature="std")] use std::collections::{HashSet}; -#[cfg(all(feature="alloc", not(feature="std")))] use crate::alloc::collections::BTreeSet; - -#[cfg(feature="alloc")] use crate::distributions::{Distribution, Uniform, uniform::SampleUniform}; -use crate::Rng; - -/// A vector of indices. -/// -/// Multiple internal representations are possible. -#[derive(Clone, Debug)] -pub enum IndexVec { - #[doc(hidden)] U32(Vec), - #[doc(hidden)] USize(Vec), -} - -impl IndexVec { - /// Returns the number of indices - #[inline] - pub fn len(&self) -> usize { - match *self { - IndexVec::U32(ref v) => v.len(), - IndexVec::USize(ref v) => v.len(), - } - } - - /// Returns `true` if the length is 0. - #[inline] - pub fn is_empty(&self) -> bool { - match *self { - IndexVec::U32(ref v) => v.is_empty(), - IndexVec::USize(ref v) => v.is_empty(), - } - } - - /// Return the value at the given `index`. - /// - /// (Note: we cannot implement [`std::ops::Index`] because of lifetime - /// restrictions.) - #[inline] - pub fn index(&self, index: usize) -> usize { - match *self { - IndexVec::U32(ref v) => v[index] as usize, - IndexVec::USize(ref v) => v[index], - } - } - - /// Return result as a `Vec`. Conversion may or may not be trivial. - #[inline] - pub fn into_vec(self) -> Vec { - match self { - IndexVec::U32(v) => v.into_iter().map(|i| i as usize).collect(), - IndexVec::USize(v) => v, - } - } - - /// Iterate over the indices as a sequence of `usize` values - #[inline] - pub fn iter(&self) -> IndexVecIter<'_> { - match *self { - IndexVec::U32(ref v) => IndexVecIter::U32(v.iter()), - IndexVec::USize(ref v) => IndexVecIter::USize(v.iter()), - } - } - - /// Convert into an iterator over the indices as a sequence of `usize` values - #[inline] - pub fn into_iter(self) -> IndexVecIntoIter { - match self { - IndexVec::U32(v) => IndexVecIntoIter::U32(v.into_iter()), - IndexVec::USize(v) => IndexVecIntoIter::USize(v.into_iter()), - } - } -} - -impl PartialEq for IndexVec { - fn eq(&self, other: &IndexVec) -> bool { - use self::IndexVec::*; - match (self, other) { - (&U32(ref v1), &U32(ref v2)) => v1 == v2, - (&USize(ref v1), &USize(ref v2)) => v1 == v2, - (&U32(ref v1), &USize(ref v2)) => (v1.len() == v2.len()) - && (v1.iter().zip(v2.iter()).all(|(x, y)| *x as usize == *y)), - (&USize(ref v1), &U32(ref v2)) => (v1.len() == v2.len()) - && (v1.iter().zip(v2.iter()).all(|(x, y)| *x == *y as usize)), - } - } -} - -impl From> for IndexVec { - #[inline] - fn from(v: Vec) -> Self { - IndexVec::U32(v) - } -} - -impl From> for IndexVec { - #[inline] - fn from(v: Vec) -> Self { - IndexVec::USize(v) - } -} - -/// Return type of `IndexVec::iter`. -#[derive(Debug)] -pub enum IndexVecIter<'a> { - #[doc(hidden)] U32(slice::Iter<'a, u32>), - #[doc(hidden)] USize(slice::Iter<'a, usize>), -} - -impl<'a> Iterator for IndexVecIter<'a> { - type Item = usize; - #[inline] - fn next(&mut self) -> Option { - use self::IndexVecIter::*; - match *self { - U32(ref mut iter) => iter.next().map(|i| *i as usize), - USize(ref mut iter) => iter.next().cloned(), - } - } - - #[inline] - fn size_hint(&self) -> (usize, Option) { - match *self { - IndexVecIter::U32(ref v) => v.size_hint(), - IndexVecIter::USize(ref v) => v.size_hint(), - } - } -} - -impl<'a> ExactSizeIterator for IndexVecIter<'a> {} - -/// Return type of `IndexVec::into_iter`. -#[derive(Clone, Debug)] -pub enum IndexVecIntoIter { - #[doc(hidden)] U32(vec::IntoIter), - #[doc(hidden)] USize(vec::IntoIter), -} - -impl Iterator for IndexVecIntoIter { - type Item = usize; - - #[inline] - fn next(&mut self) -> Option { - use self::IndexVecIntoIter::*; - match *self { - U32(ref mut v) => v.next().map(|i| i as usize), - USize(ref mut v) => v.next(), - } - } - - #[inline] - fn size_hint(&self) -> (usize, Option) { - use self::IndexVecIntoIter::*; - match *self { - U32(ref v) => v.size_hint(), - USize(ref v) => v.size_hint(), - } - } -} - -impl ExactSizeIterator for IndexVecIntoIter {} - - -/// Randomly sample exactly `amount` distinct indices from `0..length`, and -/// return them in random order (fully shuffled). -/// -/// This method is used internally by the slice sampling methods, but it can -/// sometimes be useful to have the indices themselves so this is provided as -/// an alternative. -/// -/// The implementation used is not specified; we automatically select the -/// fastest available algorithm for the `length` and `amount` parameters -/// (based on detailed profiling on an Intel Haswell CPU). Roughly speaking, -/// complexity is `O(amount)`, except that when `amount` is small, performance -/// is closer to `O(amount^2)`, and when `length` is close to `amount` then -/// `O(length)`. -/// -/// Note that performance is significantly better over `u32` indices than over -/// `u64` indices. Because of this we hide the underlying type behind an -/// abstraction, `IndexVec`. -/// -/// If an allocation-free `no_std` function is required, it is suggested -/// to adapt the internal `sample_floyd` implementation. -/// -/// Panics if `amount > length`. -pub fn sample(rng: &mut R, length: usize, amount: usize) -> IndexVec -where R: Rng + ?Sized { - if amount > length { - panic!("`amount` of samples must be less than or equal to `length`"); - } - if length > (::core::u32::MAX as usize) { - // We never want to use inplace here, but could use floyd's alg - // Lazy version: always use the cache alg. - return sample_rejection(rng, length, amount); - } - let amount = amount as u32; - let length = length as u32; - - // Choice of algorithm here depends on both length and amount. See: - // https://github.com/rust-random/rand/pull/479 - // We do some calculations with f32. Accuracy is not very important. - - if amount < 163 { - const C: [[f32; 2]; 2] = [[1.6, 8.0/45.0], [10.0, 70.0/9.0]]; - let j = if length < 500_000 { 0 } else { 1 }; - let amount_fp = amount as f32; - let m4 = C[0][j] * amount_fp; - // Short-cut: when amount < 12, floyd's is always faster - if amount > 11 && (length as f32) < (C[1][j] + m4) * amount_fp { - sample_inplace(rng, length, amount) - } else { - sample_floyd(rng, length, amount) - } - } else { - const C: [f32; 2] = [270.0, 330.0/9.0]; - let j = if length < 500_000 { 0 } else { 1 }; - if (length as f32) < C[j] * (amount as f32) { - sample_inplace(rng, length, amount) - } else { - sample_rejection(rng, length, amount) - } - } -} - -/// Randomly sample exactly `amount` indices from `0..length`, using Floyd's -/// combination algorithm. -/// -/// The output values are fully shuffled. (Overhead is under 50%.) -/// -/// This implementation uses `O(amount)` memory and `O(amount^2)` time. -fn sample_floyd(rng: &mut R, length: u32, amount: u32) -> IndexVec -where R: Rng + ?Sized { - // For small amount we use Floyd's fully-shuffled variant. For larger - // amounts this is slow due to Vec::insert performance, so we shuffle - // afterwards. Benchmarks show little overhead from extra logic. - let floyd_shuffle = amount < 50; - - debug_assert!(amount <= length); - let mut indices = Vec::with_capacity(amount as usize); - for j in length - amount .. length { - let t = rng.gen_range(0, j + 1); - if floyd_shuffle { - if let Some(pos) = indices.iter().position(|&x| x == t) { - indices.insert(pos, j); - continue; - } - } else if indices.contains(&t) { - indices.push(j); - continue; - } - indices.push(t); - } - if !floyd_shuffle { - // Reimplement SliceRandom::shuffle with smaller indices - for i in (1..amount).rev() { - // invariant: elements with index > i have been locked in place. - indices.swap(i as usize, rng.gen_range(0, i + 1) as usize); - } - } - IndexVec::from(indices) -} - -/// Randomly sample exactly `amount` indices from `0..length`, using an inplace -/// partial Fisher-Yates method. -/// Sample an amount of indices using an inplace partial fisher yates method. -/// -/// This allocates the entire `length` of indices and randomizes only the first `amount`. -/// It then truncates to `amount` and returns. -/// -/// This method is not appropriate for large `length` and potentially uses a lot -/// of memory; because of this we only implement for `u32` index (which improves -/// performance in all cases). -/// -/// Set-up is `O(length)` time and memory and shuffling is `O(amount)` time. -fn sample_inplace(rng: &mut R, length: u32, amount: u32) -> IndexVec -where R: Rng + ?Sized { - debug_assert!(amount <= length); - let mut indices: Vec = Vec::with_capacity(length as usize); - indices.extend(0..length); - for i in 0..amount { - let j: u32 = rng.gen_range(i, length); - indices.swap(i as usize, j as usize); - } - indices.truncate(amount as usize); - debug_assert_eq!(indices.len(), amount as usize); - IndexVec::from(indices) -} - -trait UInt: Copy + PartialOrd + Ord + PartialEq + Eq + SampleUniform + core::hash::Hash { - fn zero() -> Self; - fn as_usize(self) -> usize; -} -impl UInt for u32 { - #[inline] fn zero() -> Self { 0 } - #[inline] fn as_usize(self) -> usize { self as usize } -} -impl UInt for usize { - #[inline] fn zero() -> Self { 0 } - #[inline] fn as_usize(self) -> usize { self } -} - -/// Randomly sample exactly `amount` indices from `0..length`, using rejection -/// sampling. -/// -/// Since `amount <<< length` there is a low chance of a random sample in -/// `0..length` being a duplicate. We test for duplicates and resample where -/// necessary. The algorithm is `O(amount)` time and memory. -/// -/// This function is generic over X primarily so that results are value-stable -/// over 32-bit and 64-bit platforms. -fn sample_rejection(rng: &mut R, length: X, amount: X) -> IndexVec -where R: Rng + ?Sized, IndexVec: From> { - debug_assert!(amount < length); - #[cfg(feature="std")] let mut cache = HashSet::with_capacity(amount.as_usize()); - #[cfg(not(feature="std"))] let mut cache = BTreeSet::new(); - let distr = Uniform::new(X::zero(), length); - let mut indices = Vec::with_capacity(amount.as_usize()); - for _ in 0..amount.as_usize() { - let mut pos = distr.sample(rng); - while !cache.insert(pos) { - pos = distr.sample(rng); - } - indices.push(pos); - } - - debug_assert_eq!(indices.len(), amount.as_usize()); - IndexVec::from(indices) -} - -#[cfg(test)] -mod test { - #[cfg(feature="std")] use std::vec; - #[cfg(all(feature="alloc", not(feature="std")))] use crate::alloc::vec; - use super::*; - - #[test] - fn test_sample_boundaries() { - let mut r = crate::test::rng(404); - - assert_eq!(sample_inplace(&mut r, 0, 0).len(), 0); - assert_eq!(sample_inplace(&mut r, 1, 0).len(), 0); - assert_eq!(sample_inplace(&mut r, 1, 1).into_vec(), vec![0]); - - assert_eq!(sample_rejection(&mut r, 1u32, 0).len(), 0); - - assert_eq!(sample_floyd(&mut r, 0, 0).len(), 0); - assert_eq!(sample_floyd(&mut r, 1, 0).len(), 0); - assert_eq!(sample_floyd(&mut r, 1, 1).into_vec(), vec![0]); - - // These algorithms should be fast with big numbers. Test average. - let sum: usize = sample_rejection(&mut r, 1 << 25, 10u32) - .into_iter().sum(); - assert!(1 << 25 < sum && sum < (1 << 25) * 25); - - let sum: usize = sample_floyd(&mut r, 1 << 25, 10) - .into_iter().sum(); - assert!(1 << 25 < sum && sum < (1 << 25) * 25); - } - - #[test] - #[cfg(not(miri))] // Miri is too slow - fn test_sample_alg() { - let seed_rng = crate::test::rng; - - // We can't test which algorithm is used directly, but Floyd's alg - // should produce different results from the others. (Also, `inplace` - // and `cached` currently use different sizes thus produce different results.) - - // A small length and relatively large amount should use inplace - let (length, amount): (usize, usize) = (100, 50); - let v1 = sample(&mut seed_rng(420), length, amount); - let v2 = sample_inplace(&mut seed_rng(420), length as u32, amount as u32); - assert!(v1.iter().all(|e| e < length)); - assert_eq!(v1, v2); - - // Test Floyd's alg does produce different results - let v3 = sample_floyd(&mut seed_rng(420), length as u32, amount as u32); - assert!(v1 != v3); - - // A large length and small amount should use Floyd - let (length, amount): (usize, usize) = (1<<20, 50); - let v1 = sample(&mut seed_rng(421), length, amount); - let v2 = sample_floyd(&mut seed_rng(421), length as u32, amount as u32); - assert!(v1.iter().all(|e| e < length)); - assert_eq!(v1, v2); - - // A large length and larger amount should use cache - let (length, amount): (usize, usize) = (1<<20, 600); - let v1 = sample(&mut seed_rng(422), length, amount); - let v2 = sample_rejection(&mut seed_rng(422), length as u32, amount as u32); - assert!(v1.iter().all(|e| e < length)); - assert_eq!(v1, v2); - } -} diff --git a/rand/src/seq/mod.rs b/rand/src/seq/mod.rs deleted file mode 100644 index cec9bb1..0000000 --- a/rand/src/seq/mod.rs +++ /dev/null @@ -1,791 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Sequence-related functionality -//! -//! This module provides: -//! -//! * [`seq::SliceRandom`] slice sampling and mutation -//! * [`seq::IteratorRandom`] iterator sampling -//! * [`seq::index::sample`] low-level API to choose multiple indices from -//! `0..length` -//! -//! Also see: -//! -//! * [`distributions::weighted`] module which provides implementations of -//! weighted index sampling. -//! -//! In order to make results reproducible across 32-64 bit architectures, all -//! `usize` indices are sampled as a `u32` where possible (also providing a -//! small performance boost in some cases). - - -#[cfg(feature="alloc")] pub mod index; - -#[cfg(feature="alloc")] use core::ops::Index; - -#[cfg(all(feature="alloc", not(feature="std")))] use crate::alloc::vec::Vec; - -use crate::Rng; -#[cfg(feature="alloc")] use crate::distributions::WeightedError; -#[cfg(feature="alloc")] use crate::distributions::uniform::{SampleUniform, SampleBorrow}; - -/// Extension trait on slices, providing random mutation and sampling methods. -/// -/// This trait is implemented on all `[T]` slice types, providing several -/// methods for choosing and shuffling elements. You must `use` this trait: -/// -/// ``` -/// use rand::seq::SliceRandom; -/// -/// fn main() { -/// let mut rng = rand::thread_rng(); -/// let mut bytes = "Hello, random!".to_string().into_bytes(); -/// bytes.shuffle(&mut rng); -/// let str = String::from_utf8(bytes).unwrap(); -/// println!("{}", str); -/// } -/// ``` -/// Example output (non-deterministic): -/// ```none -/// l,nmroHado !le -/// ``` -pub trait SliceRandom { - /// The element type. - type Item; - - /// Returns a reference to one random element of the slice, or `None` if the - /// slice is empty. - /// - /// For slices, complexity is `O(1)`. - /// - /// # Example - /// - /// ``` - /// use rand::thread_rng; - /// use rand::seq::SliceRandom; - /// - /// let choices = [1, 2, 4, 8, 16, 32]; - /// let mut rng = thread_rng(); - /// println!("{:?}", choices.choose(&mut rng)); - /// assert_eq!(choices[..0].choose(&mut rng), None); - /// ``` - fn choose(&self, rng: &mut R) -> Option<&Self::Item> - where R: Rng + ?Sized; - - /// Returns a mutable reference to one random element of the slice, or - /// `None` if the slice is empty. - /// - /// For slices, complexity is `O(1)`. - fn choose_mut(&mut self, rng: &mut R) -> Option<&mut Self::Item> - where R: Rng + ?Sized; - - /// Chooses `amount` elements from the slice at random, without repetition, - /// and in random order. The returned iterator is appropriate both for - /// collection into a `Vec` and filling an existing buffer (see example). - /// - /// In case this API is not sufficiently flexible, use [`index::sample`]. - /// - /// For slices, complexity is the same as [`index::sample`]. - /// - /// # Example - /// ``` - /// use rand::seq::SliceRandom; - /// - /// let mut rng = &mut rand::thread_rng(); - /// let sample = "Hello, audience!".as_bytes(); - /// - /// // collect the results into a vector: - /// let v: Vec = sample.choose_multiple(&mut rng, 3).cloned().collect(); - /// - /// // store in a buffer: - /// let mut buf = [0u8; 5]; - /// for (b, slot) in sample.choose_multiple(&mut rng, buf.len()).zip(buf.iter_mut()) { - /// *slot = *b; - /// } - /// ``` - #[cfg(feature = "alloc")] - fn choose_multiple(&self, rng: &mut R, amount: usize) -> SliceChooseIter - where R: Rng + ?Sized; - - /// Similar to [`choose`], but where the likelihood of each outcome may be - /// specified. - /// - /// The specified function `weight` maps each item `x` to a relative - /// likelihood `weight(x)`. The probability of each item being selected is - /// therefore `weight(x) / s`, where `s` is the sum of all `weight(x)`. - /// - /// For slices of length `n`, complexity is `O(n)`. - /// See also [`choose_weighted_mut`], [`distributions::weighted`]. - /// - /// # Example - /// - /// ``` - /// use rand::prelude::*; - /// - /// let choices = [('a', 2), ('b', 1), ('c', 1)]; - /// let mut rng = thread_rng(); - /// // 50% chance to print 'a', 25% chance to print 'b', 25% chance to print 'c' - /// println!("{:?}", choices.choose_weighted(&mut rng, |item| item.1).unwrap().0); - /// ``` - /// [`choose`]: SliceRandom::choose - /// [`choose_weighted_mut`]: SliceRandom::choose_weighted_mut - /// [`distributions::weighted`]: crate::distributions::weighted - #[cfg(feature = "alloc")] - fn choose_weighted( - &self, rng: &mut R, weight: F, - ) -> Result<&Self::Item, WeightedError> - where - R: Rng + ?Sized, - F: Fn(&Self::Item) -> B, - B: SampleBorrow, - X: SampleUniform - + for<'a> ::core::ops::AddAssign<&'a X> - + ::core::cmp::PartialOrd - + Clone - + Default; - - /// Similar to [`choose_mut`], but where the likelihood of each outcome may - /// be specified. - /// - /// The specified function `weight` maps each item `x` to a relative - /// likelihood `weight(x)`. The probability of each item being selected is - /// therefore `weight(x) / s`, where `s` is the sum of all `weight(x)`. - /// - /// For slices of length `n`, complexity is `O(n)`. - /// See also [`choose_weighted`], [`distributions::weighted`]. - /// - /// [`choose_mut`]: SliceRandom::choose_mut - /// [`choose_weighted`]: SliceRandom::choose_weighted - /// [`distributions::weighted`]: crate::distributions::weighted - #[cfg(feature = "alloc")] - fn choose_weighted_mut( - &mut self, rng: &mut R, weight: F, - ) -> Result<&mut Self::Item, WeightedError> - where - R: Rng + ?Sized, - F: Fn(&Self::Item) -> B, - B: SampleBorrow, - X: SampleUniform - + for<'a> ::core::ops::AddAssign<&'a X> - + ::core::cmp::PartialOrd - + Clone - + Default; - - /// Shuffle a mutable slice in place. - /// - /// For slices of length `n`, complexity is `O(n)`. - /// - /// # Example - /// - /// ``` - /// use rand::seq::SliceRandom; - /// use rand::thread_rng; - /// - /// let mut rng = thread_rng(); - /// let mut y = [1, 2, 3, 4, 5]; - /// println!("Unshuffled: {:?}", y); - /// y.shuffle(&mut rng); - /// println!("Shuffled: {:?}", y); - /// ``` - fn shuffle(&mut self, rng: &mut R) - where R: Rng + ?Sized; - - /// Shuffle a slice in place, but exit early. - /// - /// Returns two mutable slices from the source slice. The first contains - /// `amount` elements randomly permuted. The second has the remaining - /// elements that are not fully shuffled. - /// - /// This is an efficient method to select `amount` elements at random from - /// the slice, provided the slice may be mutated. - /// - /// If you only need to choose elements randomly and `amount > self.len()/2` - /// then you may improve performance by taking - /// `amount = values.len() - amount` and using only the second slice. - /// - /// If `amount` is greater than the number of elements in the slice, this - /// will perform a full shuffle. - /// - /// For slices, complexity is `O(m)` where `m = amount`. - fn partial_shuffle( - &mut self, rng: &mut R, amount: usize, - ) -> (&mut [Self::Item], &mut [Self::Item]) - where R: Rng + ?Sized; -} - -/// Extension trait on iterators, providing random sampling methods. -/// -/// This trait is implemented on all sized iterators, providing methods for -/// choosing one or more elements. You must `use` this trait: -/// -/// ``` -/// use rand::seq::IteratorRandom; -/// -/// fn main() { -/// let mut rng = rand::thread_rng(); -/// -/// let faces = "πŸ˜€πŸ˜ŽπŸ˜πŸ˜•πŸ˜ πŸ˜’"; -/// println!("I am {}!", faces.chars().choose(&mut rng).unwrap()); -/// } -/// ``` -/// Example output (non-deterministic): -/// ```none -/// I am πŸ˜€! -/// ``` -pub trait IteratorRandom: Iterator + Sized { - /// Choose one element at random from the iterator. - /// - /// Returns `None` if and only if the iterator is empty. - /// - /// This method uses [`Iterator::size_hint`] for optimisation. With an - /// accurate hint and where [`Iterator::nth`] is a constant-time operation - /// this method can offer `O(1)` performance. Where no size hint is - /// available, complexity is `O(n)` where `n` is the iterator length. - /// Partial hints (where `lower > 0`) also improve performance. - /// - /// For slices, prefer [`SliceRandom::choose`] which guarantees `O(1)` - /// performance. - fn choose(mut self, rng: &mut R) -> Option - where R: Rng + ?Sized { - let (mut lower, mut upper) = self.size_hint(); - let mut consumed = 0; - let mut result = None; - - if upper == Some(lower) { - return if lower == 0 { None } else { self.nth(gen_index(rng, lower)) }; - } - - // Continue until the iterator is exhausted - loop { - if lower > 1 { - let ix = gen_index(rng, lower + consumed); - let skip = if ix < lower { - result = self.nth(ix); - lower - (ix + 1) - } else { - lower - }; - if upper == Some(lower) { - return result; - } - consumed += lower; - if skip > 0 { - self.nth(skip - 1); - } - } else { - let elem = self.next(); - if elem.is_none() { - return result; - } - consumed += 1; - let denom = consumed as f64; // accurate to 2^53 elements - if rng.gen_bool(1.0 / denom) { - result = elem; - } - } - - let hint = self.size_hint(); - lower = hint.0; - upper = hint.1; - } - } - - /// Collects values at random from the iterator into a supplied buffer - /// until that buffer is filled. - /// - /// Although the elements are selected randomly, the order of elements in - /// the buffer is neither stable nor fully random. If random ordering is - /// desired, shuffle the result. - /// - /// Returns the number of elements added to the buffer. This equals the length - /// of the buffer unless the iterator contains insufficient elements, in which - /// case this equals the number of elements available. - /// - /// Complexity is `O(n)` where `n` is the length of the iterator. - /// For slices, prefer [`SliceRandom::choose_multiple`]. - fn choose_multiple_fill(mut self, rng: &mut R, buf: &mut [Self::Item]) -> usize - where R: Rng + ?Sized { - let amount = buf.len(); - let mut len = 0; - while len < amount { - if let Some(elem) = self.next() { - buf[len] = elem; - len += 1; - } else { - // Iterator exhausted; stop early - return len; - } - } - - // Continue, since the iterator was not exhausted - for (i, elem) in self.enumerate() { - let k = gen_index(rng, i + 1 + amount); - if let Some(slot) = buf.get_mut(k) { - *slot = elem; - } - } - len - } - - /// Collects `amount` values at random from the iterator into a vector. - /// - /// This is equivalent to `choose_multiple_fill` except for the result type. - /// - /// Although the elements are selected randomly, the order of elements in - /// the buffer is neither stable nor fully random. If random ordering is - /// desired, shuffle the result. - /// - /// The length of the returned vector equals `amount` unless the iterator - /// contains insufficient elements, in which case it equals the number of - /// elements available. - /// - /// Complexity is `O(n)` where `n` is the length of the iterator. - /// For slices, prefer [`SliceRandom::choose_multiple`]. - #[cfg(feature = "alloc")] - fn choose_multiple(mut self, rng: &mut R, amount: usize) -> Vec - where R: Rng + ?Sized { - let mut reservoir = Vec::with_capacity(amount); - reservoir.extend(self.by_ref().take(amount)); - - // Continue unless the iterator was exhausted - // - // note: this prevents iterators that "restart" from causing problems. - // If the iterator stops once, then so do we. - if reservoir.len() == amount { - for (i, elem) in self.enumerate() { - let k = gen_index(rng, i + 1 + amount); - if let Some(slot) = reservoir.get_mut(k) { - *slot = elem; - } - } - } else { - // Don't hang onto extra memory. There is a corner case where - // `amount` was much less than `self.len()`. - reservoir.shrink_to_fit(); - } - reservoir - } -} - - -impl SliceRandom for [T] { - type Item = T; - - fn choose(&self, rng: &mut R) -> Option<&Self::Item> - where R: Rng + ?Sized { - if self.is_empty() { - None - } else { - Some(&self[gen_index(rng, self.len())]) - } - } - - fn choose_mut(&mut self, rng: &mut R) -> Option<&mut Self::Item> - where R: Rng + ?Sized { - if self.is_empty() { - None - } else { - let len = self.len(); - Some(&mut self[gen_index(rng, len)]) - } - } - - #[cfg(feature = "alloc")] - fn choose_multiple(&self, rng: &mut R, amount: usize) -> SliceChooseIter - where R: Rng + ?Sized { - let amount = ::core::cmp::min(amount, self.len()); - SliceChooseIter { - slice: self, - _phantom: Default::default(), - indices: index::sample(rng, self.len(), amount).into_iter(), - } - } - - #[cfg(feature = "alloc")] - fn choose_weighted( - &self, rng: &mut R, weight: F, - ) -> Result<&Self::Item, WeightedError> - where - R: Rng + ?Sized, - F: Fn(&Self::Item) -> B, - B: SampleBorrow, - X: SampleUniform - + for<'a> ::core::ops::AddAssign<&'a X> - + ::core::cmp::PartialOrd - + Clone - + Default, - { - use crate::distributions::{Distribution, WeightedIndex}; - let distr = WeightedIndex::new(self.iter().map(weight))?; - Ok(&self[distr.sample(rng)]) - } - - #[cfg(feature = "alloc")] - fn choose_weighted_mut( - &mut self, rng: &mut R, weight: F, - ) -> Result<&mut Self::Item, WeightedError> - where - R: Rng + ?Sized, - F: Fn(&Self::Item) -> B, - B: SampleBorrow, - X: SampleUniform - + for<'a> ::core::ops::AddAssign<&'a X> - + ::core::cmp::PartialOrd - + Clone - + Default, - { - use crate::distributions::{Distribution, WeightedIndex}; - let distr = WeightedIndex::new(self.iter().map(weight))?; - Ok(&mut self[distr.sample(rng)]) - } - - fn shuffle(&mut self, rng: &mut R) - where R: Rng + ?Sized { - for i in (1..self.len()).rev() { - // invariant: elements with index > i have been locked in place. - self.swap(i, gen_index(rng, i + 1)); - } - } - - fn partial_shuffle( - &mut self, rng: &mut R, amount: usize, - ) -> (&mut [Self::Item], &mut [Self::Item]) - where R: Rng + ?Sized { - // This applies Durstenfeld's algorithm for the - // [Fisher–Yates shuffle](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm) - // for an unbiased permutation, but exits early after choosing `amount` - // elements. - - let len = self.len(); - let end = if amount >= len { 0 } else { len - amount }; - - for i in (end..len).rev() { - // invariant: elements with index > i have been locked in place. - self.swap(i, gen_index(rng, i + 1)); - } - let r = self.split_at_mut(end); - (r.1, r.0) - } -} - -impl IteratorRandom for I where I: Iterator + Sized {} - - -/// An iterator over multiple slice elements. -/// -/// This struct is created by -/// [`SliceRandom::choose_multiple`](trait.SliceRandom.html#tymethod.choose_multiple). -#[cfg(feature = "alloc")] -#[derive(Debug)] -pub struct SliceChooseIter<'a, S: ?Sized + 'a, T: 'a> { - slice: &'a S, - _phantom: ::core::marker::PhantomData, - indices: index::IndexVecIntoIter, -} - -#[cfg(feature = "alloc")] -impl<'a, S: Index + ?Sized + 'a, T: 'a> Iterator for SliceChooseIter<'a, S, T> { - type Item = &'a T; - - fn next(&mut self) -> Option { - // TODO: investigate using SliceIndex::get_unchecked when stable - self.indices.next().map(|i| &self.slice[i as usize]) - } - - fn size_hint(&self) -> (usize, Option) { - (self.indices.len(), Some(self.indices.len())) - } -} - -#[cfg(feature = "alloc")] -impl<'a, S: Index + ?Sized + 'a, T: 'a> ExactSizeIterator - for SliceChooseIter<'a, S, T> -{ - fn len(&self) -> usize { - self.indices.len() - } -} - - -// Sample a number uniformly between 0 and `ubound`. Uses 32-bit sampling where -// possible, primarily in order to produce the same output on 32-bit and 64-bit -// platforms. -#[inline] -fn gen_index(rng: &mut R, ubound: usize) -> usize { - if ubound <= (core::u32::MAX as usize) { - rng.gen_range(0, ubound as u32) as usize - } else { - rng.gen_range(0, ubound) - } -} - - -#[cfg(test)] -mod test { - use super::*; - #[cfg(feature = "alloc")] use crate::Rng; - #[cfg(all(feature="alloc", not(feature="std")))] - use alloc::vec::Vec; - - #[test] - fn test_slice_choose() { - let mut r = crate::test::rng(107); - let chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n']; - let mut chosen = [0i32; 14]; - // The below all use a binomial distribution with n=1000, p=1/14. - // binocdf(40, 1000, 1/14) ~= 2e-5; 1-binocdf(106, ..) ~= 2e-5 - for _ in 0..1000 { - let picked = *chars.choose(&mut r).unwrap(); - chosen[(picked as usize) - ('a' as usize)] += 1; - } - for count in chosen.iter() { - assert!(40 < *count && *count < 106); - } - - chosen.iter_mut().for_each(|x| *x = 0); - for _ in 0..1000 { - *chosen.choose_mut(&mut r).unwrap() += 1; - } - for count in chosen.iter() { - assert!(40 < *count && *count < 106); - } - - let mut v: [isize; 0] = []; - assert_eq!(v.choose(&mut r), None); - assert_eq!(v.choose_mut(&mut r), None); - } - - #[derive(Clone)] - struct UnhintedIterator { - iter: I, - } - impl Iterator for UnhintedIterator { - type Item = I::Item; - fn next(&mut self) -> Option { - self.iter.next() - } - } - - #[derive(Clone)] - struct ChunkHintedIterator { - iter: I, - chunk_remaining: usize, - chunk_size: usize, - hint_total_size: bool, - } - impl Iterator for ChunkHintedIterator { - type Item = I::Item; - fn next(&mut self) -> Option { - if self.chunk_remaining == 0 { - self.chunk_remaining = ::core::cmp::min(self.chunk_size, - self.iter.len()); - } - self.chunk_remaining = self.chunk_remaining.saturating_sub(1); - - self.iter.next() - } - fn size_hint(&self) -> (usize, Option) { - (self.chunk_remaining, - if self.hint_total_size { Some(self.iter.len()) } else { None }) - } - } - - #[derive(Clone)] - struct WindowHintedIterator { - iter: I, - window_size: usize, - hint_total_size: bool, - } - impl Iterator for WindowHintedIterator { - type Item = I::Item; - fn next(&mut self) -> Option { - self.iter.next() - } - fn size_hint(&self) -> (usize, Option) { - (::core::cmp::min(self.iter.len(), self.window_size), - if self.hint_total_size { Some(self.iter.len()) } else { None }) - } - } - - #[test] - #[cfg(not(miri))] // Miri is too slow - fn test_iterator_choose() { - let r = &mut crate::test::rng(109); - fn test_iter + Clone>(r: &mut R, iter: Iter) { - let mut chosen = [0i32; 9]; - for _ in 0..1000 { - let picked = iter.clone().choose(r).unwrap(); - chosen[picked] += 1; - } - for count in chosen.iter() { - // Samples should follow Binomial(1000, 1/9) - // Octave: binopdf(x, 1000, 1/9) gives the prob of *count == x - // Note: have seen 153, which is unlikely but not impossible. - assert!(72 < *count && *count < 154, "count not close to 1000/9: {}", count); - } - } - - test_iter(r, 0..9); - test_iter(r, [0, 1, 2, 3, 4, 5, 6, 7, 8].iter().cloned()); - #[cfg(feature = "alloc")] - test_iter(r, (0..9).collect::>().into_iter()); - test_iter(r, UnhintedIterator { iter: 0..9 }); - test_iter(r, ChunkHintedIterator { iter: 0..9, chunk_size: 4, chunk_remaining: 4, hint_total_size: false }); - test_iter(r, ChunkHintedIterator { iter: 0..9, chunk_size: 4, chunk_remaining: 4, hint_total_size: true }); - test_iter(r, WindowHintedIterator { iter: 0..9, window_size: 2, hint_total_size: false }); - test_iter(r, WindowHintedIterator { iter: 0..9, window_size: 2, hint_total_size: true }); - - assert_eq!((0..0).choose(r), None); - assert_eq!(UnhintedIterator{ iter: 0..0 }.choose(r), None); - } - - #[test] - #[cfg(not(miri))] // Miri is too slow - fn test_shuffle() { - let mut r = crate::test::rng(108); - let empty: &mut [isize] = &mut []; - empty.shuffle(&mut r); - let mut one = [1]; - one.shuffle(&mut r); - let b: &[_] = &[1]; - assert_eq!(one, b); - - let mut two = [1, 2]; - two.shuffle(&mut r); - assert!(two == [1, 2] || two == [2, 1]); - - fn move_last(slice: &mut [usize], pos: usize) { - // use slice[pos..].rotate_left(1); once we can use that - let last_val = slice[pos]; - for i in pos..slice.len() - 1 { - slice[i] = slice[i + 1]; - } - *slice.last_mut().unwrap() = last_val; - } - let mut counts = [0i32; 24]; - for _ in 0..10000 { - let mut arr: [usize; 4] = [0, 1, 2, 3]; - arr.shuffle(&mut r); - let mut permutation = 0usize; - let mut pos_value = counts.len(); - for i in 0..4 { - pos_value /= 4 - i; - let pos = arr.iter().position(|&x| x == i).unwrap(); - assert!(pos < (4 - i)); - permutation += pos * pos_value; - move_last(&mut arr, pos); - assert_eq!(arr[3], i); - } - for i in 0..4 { - assert_eq!(arr[i], i); - } - counts[permutation] += 1; - } - for count in counts.iter() { - // Binomial(10000, 1/24) with average 416.667 - // Octave: binocdf(n, 10000, 1/24) - // 99.9% chance samples lie within this range: - assert!(352 <= *count && *count <= 483, "count: {}", count); - } - } - - #[test] - fn test_partial_shuffle() { - let mut r = crate::test::rng(118); - - let mut empty: [u32; 0] = []; - let res = empty.partial_shuffle(&mut r, 10); - assert_eq!((res.0.len(), res.1.len()), (0, 0)); - - let mut v = [1, 2, 3, 4, 5]; - let res = v.partial_shuffle(&mut r, 2); - assert_eq!((res.0.len(), res.1.len()), (2, 3)); - assert!(res.0[0] != res.0[1]); - // First elements are only modified if selected, so at least one isn't modified: - assert!(res.1[0] == 1 || res.1[1] == 2 || res.1[2] == 3); - } - - #[test] - #[cfg(feature = "alloc")] - fn test_sample_iter() { - let min_val = 1; - let max_val = 100; - - let mut r = crate::test::rng(401); - let vals = (min_val..max_val).collect::>(); - let small_sample = vals.iter().choose_multiple(&mut r, 5); - let large_sample = vals.iter().choose_multiple(&mut r, vals.len() + 5); - - assert_eq!(small_sample.len(), 5); - assert_eq!(large_sample.len(), vals.len()); - // no randomization happens when amount >= len - assert_eq!(large_sample, vals.iter().collect::>()); - - assert!(small_sample.iter().all(|e| { - **e >= min_val && **e <= max_val - })); - } - - #[test] - #[cfg(feature = "alloc")] - #[cfg(not(miri))] // Miri is too slow - fn test_weighted() { - let mut r = crate::test::rng(406); - const N_REPS: u32 = 3000; - let weights = [1u32, 2, 3, 0, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7]; - let total_weight = weights.iter().sum::() as f32; - - let verify = |result: [i32; 14]| { - for (i, count) in result.iter().enumerate() { - let exp = (weights[i] * N_REPS) as f32 / total_weight; - let mut err = (*count as f32 - exp).abs(); - if err != 0.0 { - err /= exp; - } - assert!(err <= 0.25); - } - }; - - // choose_weighted - fn get_weight(item: &(u32, T)) -> u32 { - item.0 - } - let mut chosen = [0i32; 14]; - let mut items = [(0u32, 0usize); 14]; // (weight, index) - for (i, item) in items.iter_mut().enumerate() { - *item = (weights[i], i); - } - for _ in 0..N_REPS { - let item = items.choose_weighted(&mut r, get_weight).unwrap(); - chosen[item.1] += 1; - } - verify(chosen); - - // choose_weighted_mut - let mut items = [(0u32, 0i32); 14]; // (weight, count) - for (i, item) in items.iter_mut().enumerate() { - *item = (weights[i], 0); - } - for _ in 0..N_REPS { - items.choose_weighted_mut(&mut r, get_weight).unwrap().1 += 1; - } - for (ch, item) in chosen.iter_mut().zip(items.iter()) { - *ch = item.1; - } - verify(chosen); - - // Check error cases - let empty_slice = &mut [10][0..0]; - assert_eq!(empty_slice.choose_weighted(&mut r, |_| 1), Err(WeightedError::NoItem)); - assert_eq!(empty_slice.choose_weighted_mut(&mut r, |_| 1), Err(WeightedError::NoItem)); - assert_eq!(['x'].choose_weighted_mut(&mut r, |_| 0), Err(WeightedError::AllWeightsZero)); - assert_eq!([0, -1].choose_weighted_mut(&mut r, |x| *x), Err(WeightedError::InvalidWeight)); - assert_eq!([-1, 0].choose_weighted_mut(&mut r, |x| *x), Err(WeightedError::InvalidWeight)); - } -} diff --git a/rand/tests/wasm_bindgen/Cargo.toml b/rand/tests/wasm_bindgen/Cargo.toml deleted file mode 100644 index e83c174..0000000 --- a/rand/tests/wasm_bindgen/Cargo.toml +++ /dev/null @@ -1,16 +0,0 @@ -[package] -name = "rand_wasm_bindgen_test" -description = "Minimal crate to test that rand can be build for web assembly target" -version = "0.1.0" -authors = ["The Rand Project Developers"] -publish = false -license = "MIT OR Apache-2.0" -edition = "2018" - -[lib] -crate-type = ["cdylib"] - -[dependencies] -rand = { path = "../..", features = ["wasm-bindgen"] } -wasm-bindgen = "0.2" -wasm-bindgen-test = "0.2" diff --git a/rand/tests/wasm_bindgen/js/index.js b/rand/tests/wasm_bindgen/js/index.js deleted file mode 100644 index a02fb59..0000000 --- a/rand/tests/wasm_bindgen/js/index.js +++ /dev/null @@ -1,7 +0,0 @@ -'use strict'; - -const rand_wasm_bindgen_test = require('./rand_wasm_bindgen_test'); - -console.log(rand_wasm_bindgen_test.generate_from_entropy()); -console.log(rand_wasm_bindgen_test.generate_from_os_rand()); -console.log(rand_wasm_bindgen_test.generate_from_seed()); diff --git a/rand/tests/wasm_bindgen/src/lib.rs b/rand/tests/wasm_bindgen/src/lib.rs deleted file mode 100644 index 9af0b9e..0000000 --- a/rand/tests/wasm_bindgen/src/lib.rs +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -// Crate to test WASM with the `wasm-bindgen` lib. - -#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png")] - -use rand::rngs::{OsRng, StdRng}; -use rand::{Rng, SeedableRng}; -use wasm_bindgen::prelude::*; - -#[wasm_bindgen] -pub fn generate_from_seed(seed: u32) -> i32 { - StdRng::seed_from_u64(seed as u64).gen() -} - -#[wasm_bindgen] -pub fn generate_from_os_rand() -> i32 { - OsRng.gen() -} - -#[wasm_bindgen] -pub fn generate_from_entropy() -> i32 { - StdRng::from_entropy().gen() -} - -pub mod tests { - use wasm_bindgen_test::*; - - #[wasm_bindgen_test] - fn generate_from_seed() { - let _ = super::generate_from_seed(42); - } - - #[wasm_bindgen_test] - fn generate_from_os_rand() { - let _ = super::generate_from_os_rand(); - } - - #[wasm_bindgen_test] - fn generate_from_entropy() { - let _ = super::generate_from_entropy(); - } -} diff --git a/rand/utils/ci/install.sh b/rand/utils/ci/install.sh deleted file mode 100644 index 8e636e1..0000000 --- a/rand/utils/ci/install.sh +++ /dev/null @@ -1,49 +0,0 @@ -# From https://github.com/japaric/trust - -set -ex - -main() { - local target= - if [ $TRAVIS_OS_NAME = linux ]; then - target=x86_64-unknown-linux-musl - sort=sort - else - target=x86_64-apple-darwin - sort=gsort # for `sort --sort-version`, from brew's coreutils. - fi - - # Builds for iOS are done on OSX, but require the specific target to be - # installed. - case $TARGET in - aarch64-apple-ios) - rustup target install aarch64-apple-ios - ;; - armv7-apple-ios) - rustup target install armv7-apple-ios - ;; - armv7s-apple-ios) - rustup target install armv7s-apple-ios - ;; - i386-apple-ios) - rustup target install i386-apple-ios - ;; - x86_64-apple-ios) - rustup target install x86_64-apple-ios - ;; - esac - - # This fetches latest stable release - local tag=$(git ls-remote --tags --refs --exit-code https://github.com/japaric/cross \ - | cut -d/ -f3 \ - | grep -E '^v[0.1.0-9.]+$' \ - | $sort --version-sort \ - | tail -n1) - curl -LSfs https://japaric.github.io/trust/install.sh | \ - sh -s -- \ - --force \ - --git japaric/cross \ - --tag $tag \ - --target $target -} - -main diff --git a/rand/utils/ci/install_cargo_web.sh b/rand/utils/ci/install_cargo_web.sh deleted file mode 100755 index b35f069..0000000 --- a/rand/utils/ci/install_cargo_web.sh +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/bash - -set -euo pipefail -IFS=$'\n\t' - -CARGO_WEB_RELEASE=$(curl -L -s -H 'Accept: application/json' https://github.com/koute/cargo-web/releases/latest) -CARGO_WEB_VERSION=$(echo $CARGO_WEB_RELEASE | sed -e 's/.*"tag_name":"\([^"]*\)".*/\1/') -CARGO_WEB_URL="https://github.com/koute/cargo-web/releases/download/$CARGO_WEB_VERSION/cargo-web-x86_64-unknown-linux-gnu.gz" - -echo "Downloading cargo-web from: $CARGO_WEB_URL" -curl -L $CARGO_WEB_URL | gzip -d > cargo-web -chmod +x cargo-web - -mkdir -p ~/.cargo/bin -mv cargo-web ~/.cargo/bin diff --git a/rand/utils/ci/miri.sh b/rand/utils/ci/miri.sh deleted file mode 100644 index 209adf2..0000000 --- a/rand/utils/ci/miri.sh +++ /dev/null @@ -1,23 +0,0 @@ -set -ex - -MIRI_NIGHTLY=nightly-$(curl -s https://rust-lang.github.io/rustup-components-history/x86_64-unknown-linux-gnu/miri) -echo "Installing latest nightly with Miri: $MIRI_NIGHTLY" -rustup default "$MIRI_NIGHTLY" - -rustup component add miri -cargo miri setup - -cargo miri test --no-default-features -- -- -Zunstable-options --exclude-should-panic -cargo miri test --features=log -- -- -Zunstable-options --exclude-should-panic -cargo miri test --manifest-path rand_core/Cargo.toml -cargo miri test --manifest-path rand_core/Cargo.toml --features=serde1 -cargo miri test --manifest-path rand_core/Cargo.toml --no-default-features -#cargo miri test --manifest-path rand_distr/Cargo.toml # no unsafe and lots of slow tests -cargo miri test --manifest-path rand_isaac/Cargo.toml --features=serde1 -cargo miri test --manifest-path rand_pcg/Cargo.toml --features=serde1 -cargo miri test --manifest-path rand_xorshift/Cargo.toml --features=serde1 -cargo miri test --manifest-path rand_xoshiro/Cargo.toml --features=serde1 -cargo miri test --manifest-path rand_chacha/Cargo.toml --no-default-features -cargo miri test --manifest-path rand_hc/Cargo.toml -cargo miri test --manifest-path rand_jitter/Cargo.toml -cargo miri test --manifest-path rand_os/Cargo.toml diff --git a/rand/utils/ci/script.sh b/rand/utils/ci/script.sh deleted file mode 100644 index 852a850..0000000 --- a/rand/utils/ci/script.sh +++ /dev/null @@ -1,27 +0,0 @@ -# Derived from https://github.com/japaric/trust - -set -ex - -main() { - cross test --target $TARGET --tests --no-default-features - # TODO: add simd_support feature: - cross test --target $TARGET --features=log - cross test --target $TARGET --examples - cross test --target $TARGET --manifest-path rand_core/Cargo.toml - cross test --target $TARGET --manifest-path rand_core/Cargo.toml --features=serde1 - cross test --target $TARGET --manifest-path rand_core/Cargo.toml --no-default-features - cross test --target $TARGET --manifest-path rand_distr/Cargo.toml - cross test --target $TARGET --manifest-path rand_isaac/Cargo.toml --features=serde1 - cross test --target $TARGET --manifest-path rand_pcg/Cargo.toml --features=serde1 - cross test --target $TARGET --manifest-path rand_xorshift/Cargo.toml --features=serde1 - cross test --target $TARGET --manifest-path rand_xoshiro/Cargo.toml --features=serde1 - cross test --target $TARGET --manifest-path rand_chacha/Cargo.toml - cross test --target $TARGET --manifest-path rand_hc/Cargo.toml - cross test --target $TARGET --manifest-path rand_os/Cargo.toml - cross test --target $TARGET --manifest-path rand_jitter/Cargo.toml -} - -# we don't run the "test phase" when doing deploys -if [ -z $TRAVIS_TAG ]; then - main -fi diff --git a/rand/utils/ziggurat_tables.py b/rand/utils/ziggurat_tables.py deleted file mode 100755 index 88cfdab..0000000 --- a/rand/utils/ziggurat_tables.py +++ /dev/null @@ -1,125 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2018 Developers of the Rand project. -# Copyright 2013 The Rust Project Developers. -# -# Licensed under the Apache License, Version 2.0 or the MIT license -# , at your -# option. This file may not be copied, modified, or distributed -# except according to those terms. - -# This creates the tables used for distributions implemented using the -# ziggurat algorithm in `rand::distributions;`. They are -# (basically) the tables as used in the ZIGNOR variant (Doornik 2005). -# They are changed rarely, so the generated file should be checked in -# to git. -# -# It creates 3 tables: X as in the paper, F which is f(x_i), and -# F_DIFF which is f(x_i) - f(x_{i-1}). The latter two are just cached -# values which is not done in that paper (but is done in other -# variants). Note that the adZigR table is unnecessary because of -# algebra. -# -# It is designed to be compatible with Python 2 and 3. - -from math import exp, sqrt, log, floor -import random - -# The order should match the return value of `tables` -TABLE_NAMES = ['X', 'F'] - -# The actual length of the table is 1 more, to stop -# index-out-of-bounds errors. This should match the bitwise operation -# to find `i` in `zigurrat` in `libstd/rand/mod.rs`. Also the *_R and -# *_V constants below depend on this value. -TABLE_LEN = 256 - -# equivalent to `zigNorInit` in Doornik2005, but generalised to any -# distribution. r = dR, v = dV, f = probability density function, -# f_inv = inverse of f -def tables(r, v, f, f_inv): - # compute the x_i - xvec = [0]*(TABLE_LEN+1) - - xvec[0] = v / f(r) - xvec[1] = r - - for i in range(2, TABLE_LEN): - last = xvec[i-1] - xvec[i] = f_inv(v / last + f(last)) - - # cache the f's - fvec = [0]*(TABLE_LEN+1) - for i in range(TABLE_LEN+1): - fvec[i] = f(xvec[i]) - - return xvec, fvec - -# Distributions -# N(0, 1) -def norm_f(x): - return exp(-x*x/2.0) -def norm_f_inv(y): - return sqrt(-2.0*log(y)) - -NORM_R = 3.6541528853610088 -NORM_V = 0.00492867323399 - -NORM = tables(NORM_R, NORM_V, - norm_f, norm_f_inv) - -# Exp(1) -def exp_f(x): - return exp(-x) -def exp_f_inv(y): - return -log(y) - -EXP_R = 7.69711747013104972 -EXP_V = 0.0039496598225815571993 - -EXP = tables(EXP_R, EXP_V, - exp_f, exp_f_inv) - - -# Output the tables/constants/types - -def render_static(name, type, value): - # no space or - return 'pub static %s: %s =%s;\n' % (name, type, value) - -# static `name`: [`type`, .. `len(values)`] = -# [values[0], ..., values[3], -# values[4], ..., values[7], -# ... ]; -def render_table(name, values): - rows = [] - # 4 values on each row - for i in range(0, len(values), 4): - row = values[i:i+4] - rows.append(', '.join('%.18f' % f for f in row)) - - rendered = '\n [%s]' % ',\n '.join(rows) - return render_static(name, '[f64, .. %d]' % len(values), rendered) - - -with open('ziggurat_tables.rs', 'w') as f: - f.write('''// Copyright 2018 Developers of the Rand project. -// Copyright 2013 The Rust Project Developers. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -// Tables for distributions which are sampled using the ziggurat -// algorithm. Autogenerated by `ziggurat_tables.py`. - -pub type ZigTable = &\'static [f64, .. %d]; -''' % (TABLE_LEN + 1)) - for name, tables, r in [('NORM', NORM, NORM_R), - ('EXP', EXP, EXP_R)]: - f.write(render_static('ZIG_%s_R' % name, 'f64', ' %.18f' % r)) - for (tabname, table) in zip(TABLE_NAMES, tables): - f.write(render_table('ZIG_%s_%s' % (name, tabname), table)) -- cgit v1.2.1