core: apply JS-generated Yjs updates
Rust reproduces what real yjs produced, including the unicode fixture (UTF-16 vs UTF-8 indexing) and the formatted fixture's delta/attributes (text alone can't prove bold survived the round trip). apply_update/text_content reference yrs::Doc from docs-core's public API (required so the test binary can call them against the rlib), which turned out to be enough on its own to link wasm-bindgen's JS-import glue into the wasm32 cdylib via yrs -> fastrand -> getrandom(wasm_js) — even though nothing here ever constructs a Doc or reaches that code at runtime. Fixed by vendoring fastrand 2.5.0 (Cargo.toml only; source untouched) to drop its forced "wasm_js" feature request, paired with a getrandom "custom" backend selected via .cargo/config.toml for wasm32-unknown-unknown only, backed by a fixed-fill __getrandom_v03_custom in core/src/lib.rs. See vendor/README.md for the full chain. no_host_imports still passes (464 bytes, zero imports).
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011F5CivVm4CmL9ByfSSAaXA
16 files changed,
+2344
−79
.cargo/config.toml+19 −0core/Cargo.lock+5 −79core/Cargo.toml+8 −0core/src/lib.rs+70 −0core/tests/wire_compat.rs+115 −0vendor/README.md+45 −0vendor/fastrand-2.5.0/CHANGELOG.md+140 −0vendor/fastrand-2.5.0/Cargo.toml+96 −0vendor/fastrand-2.5.0/LICENSE-APACHE+201 −0vendor/fastrand-2.5.0/LICENSE-MIT+23 −0vendor/fastrand-2.5.0/README.md+110 −0vendor/fastrand-2.5.0/benches/bench.rs+141 −0vendor/fastrand-2.5.0/src/global_rng.rs+234 −0vendor/fastrand-2.5.0/src/lib.rs+736 −0vendor/fastrand-2.5.0/tests/char.rs+44 −0vendor/fastrand-2.5.0/tests/smoke.rs+357 −0
diff --git a/.cargo/config.toml b/.cargo/config.toml| new file mode 100644 |
| index 0000000..59839f9 |
| --- /dev/null |
| +++ b/.cargo/config.toml |
| @@ -0,0 +1,19 @@ |
| +# yrs (pinned in core/Cargo.toml) unconditionally generates a random |
| +# document GUID internally (`Doc::with_client_id` still calls `uuid_v4()`, |
| +# via `fastrand`, on every Doc construction — the "with_client_id" name only |
| +# refers to the collaboration client id, not the guid). On wasm32-unknown- |
| +# unknown, fastrand's transitively-required "js" feature makes `getrandom` |
| +# default to a `wasm-bindgen`-based backend that imports host JS functions |
| +# (`crypto.getRandomValues` etc.) — even when the randomness-using code path |
| +# is never actually reachable at runtime, referencing `yrs::Doc` anywhere in |
| +# this crate is enough for those wasm-bindgen exports to end up in the final |
| +# module. The Go/wazero host provides no JS glue, so that import breaks the |
| +# zero-imports contract enforced by core/tests/no_host_imports.rs. |
| +# |
| +# Selecting getrandom's "custom" backend (see core/src/lib.rs for the |
| +# `__getrandom_v03_custom` symbol this requires) routes entropy requests to |
| +# our own no-JS-dependency implementation instead, for the wasm32 target |
| +# only — native builds (tests, tooling) are unaffected and keep getrandom's |
| +# normal OS-backed source. |
| +[target.wasm32-unknown-unknown] |
| +rustflags = ["--cfg", 'getrandom_backend="custom"'] |
diff --git a/core/Cargo.lock b/core/Cargo.lock| index 341d10e..579007f 100644 |
| --- a/core/Cargo.lock |
| +++ b/core/Cargo.lock |
| @@ -30,7 +30,7 @@ checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" |
| dependencies = [ |
| "proc-macro2", |
| "quote", |
| - "syn 3.0.4", |
| + "syn", |
| ] |
| [[package]] |
| @@ -39,12 +39,6 @@ version = "2.13.1" |
| source = "registry+https://github.com/rust-lang/crates.io-index" |
| checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da" |
| -[[package]] |
| -name = "bumpalo" |
| -version = "3.20.3" |
| -source = "registry+https://github.com/rust-lang/crates.io-index" |
| -checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" |
| - |
| [[package]] |
| name = "cfg-if" |
| version = "1.0.4" |
| @@ -75,6 +69,8 @@ dependencies = [ |
| name = "docs-core" |
| version = "0.1.0" |
| dependencies = [ |
| + "getrandom", |
| + "serde_json", |
| "wasmparser", |
| "yrs", |
| ] |
| @@ -108,8 +104,6 @@ dependencies = [ |
| [[package]] |
| name = "fastrand" |
| version = "2.5.0" |
| -source = "registry+https://github.com/rust-lang/crates.io-index" |
| -checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" |
| dependencies = [ |
| "getrandom", |
| ] |
| @@ -127,10 +121,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" |
| checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" |
| dependencies = [ |
| "cfg-if", |
| - "js-sys", |
| "libc", |
| "r-efi", |
| - "wasm-bindgen", |
| ] |
| [[package]] |
| @@ -168,16 +160,6 @@ version = "1.0.18" |
| source = "registry+https://github.com/rust-lang/crates.io-index" |
| checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" |
| -[[package]] |
| -name = "js-sys" |
| -version = "0.3.104" |
| -source = "registry+https://github.com/rust-lang/crates.io-index" |
| -checksum = "0e0c1080212aad755ea003d18543e8768dd432c48819efd73a7bf1e39b7a5a3a" |
| -dependencies = [ |
| - "cfg-if", |
| - "wasm-bindgen", |
| -] |
| - |
| [[package]] |
| name = "libc" |
| version = "0.2.189" |
| @@ -308,7 +290,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" |
| dependencies = [ |
| "proc-macro2", |
| "quote", |
| - "syn 3.0.4", |
| + "syn", |
| ] |
| [[package]] |
| @@ -339,17 +321,6 @@ version = "1.15.2" |
| source = "registry+https://github.com/rust-lang/crates.io-index" |
| checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" |
| -[[package]] |
| -name = "syn" |
| -version = "2.0.119" |
| -source = "registry+https://github.com/rust-lang/crates.io-index" |
| -checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" |
| -dependencies = [ |
| - "proc-macro2", |
| - "quote", |
| - "unicode-ident", |
| -] |
| - |
| [[package]] |
| name = "syn" |
| version = "3.0.4" |
| @@ -378,7 +349,7 @@ checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" |
| dependencies = [ |
| "proc-macro2", |
| "quote", |
| - "syn 3.0.4", |
| + "syn", |
| ] |
| [[package]] |
| @@ -387,51 +358,6 @@ version = "1.0.24" |
| source = "registry+https://github.com/rust-lang/crates.io-index" |
| checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" |
| -[[package]] |
| -name = "wasm-bindgen" |
| -version = "0.2.127" |
| -source = "registry+https://github.com/rust-lang/crates.io-index" |
| -checksum = "1b70935747edd64d89de3efa29d73789b806c15798f8e7dca4d8ac356b50ce70" |
| -dependencies = [ |
| - "cfg-if", |
| - "once_cell", |
| - "rustversion", |
| - "wasm-bindgen-macro", |
| - "wasm-bindgen-shared", |
| -] |
| - |
| -[[package]] |
| -name = "wasm-bindgen-macro" |
| -version = "0.2.127" |
| -source = "registry+https://github.com/rust-lang/crates.io-index" |
| -checksum = "77775f8f3f7217702089053b94958f8f54061a3f663417df76e19cbdcca29bc1" |
| -dependencies = [ |
| - "quote", |
| - "wasm-bindgen-macro-support", |
| -] |
| - |
| -[[package]] |
| -name = "wasm-bindgen-macro-support" |
| -version = "0.2.127" |
| -source = "registry+https://github.com/rust-lang/crates.io-index" |
| -checksum = "e11d33f857dc2fb11b8bc75aee111aa9cbeb12cd9f25efd3d4c2a3dd4e235284" |
| -dependencies = [ |
| - "bumpalo", |
| - "proc-macro2", |
| - "quote", |
| - "syn 2.0.119", |
| - "wasm-bindgen-shared", |
| -] |
| - |
| -[[package]] |
| -name = "wasm-bindgen-shared" |
| -version = "0.2.127" |
| -source = "registry+https://github.com/rust-lang/crates.io-index" |
| -checksum = "7ef64dbcc55df09c7e5a46182d181c2cfa3e925f3da937ea764728b4bbb9dcbf" |
| -dependencies = [ |
| - "unicode-ident", |
| -] |
| - |
| [[package]] |
| name = "wasmparser" |
| version = "0.258.0" |
diff --git a/core/Cargo.toml b/core/Cargo.toml| index 1352fe6..ea84dbf 100644 |
| --- a/core/Cargo.toml |
| +++ b/core/Cargo.toml |
| @@ -8,6 +8,7 @@ crate-type = ["cdylib", "rlib"] |
| [dependencies] |
| yrs = "=0.23.5" |
| +getrandom = "=0.4.3" |
| [profile.release] |
| opt-level = "s" |
| @@ -15,4 +16,11 @@ lto = true |
| panic = "abort" |
| [dev-dependencies] |
| +serde_json = "=1.0.151" |
| wasmparser = "=0.258.0" |
| + |
| +# See vendor/README.md — this fixes a `getrandom`/`fastrand` feature |
| +# conflict that only manifests when overriding getrandom's backend to |
| +# avoid a wasm-bindgen (JS) import on wasm32-unknown-unknown. |
| +[patch.crates-io] |
| +fastrand = { path = "../vendor/fastrand-2.5.0" } |
diff --git a/core/src/lib.rs b/core/src/lib.rs| index d9bde7d..05d3aeb 100644 |
| --- a/core/src/lib.rs |
| +++ b/core/src/lib.rs |
| @@ -7,6 +7,39 @@ |
| //! `Doc::new()` internally reaches for random entropy via fastrand, which pulls a JS |
| //! import that the Go/wazero host cannot provide. Providing an explicit client ID |
| //! avoids this and aligns with the design, which assigns client IDs deterministically. |
| +//! |
| +//! # Zero host imports and the custom getrandom backend |
| +//! |
| +//! `yrs::Doc` unconditionally generates a random document GUID on construction |
| +//! (`Options::with_client_id` — used even by `Doc::with_client_id` — still calls |
| +//! `uuid_v4()` via `fastrand`; "client ID" and "GUID" are different fields). |
| +//! On `wasm32-unknown-unknown`, `yrs`'s pinned `fastrand` dependency requires |
| +//! the `js` feature, which makes the transitively-pulled `getrandom` crate |
| +//! default to a `wasm-bindgen`-based backend that imports host JS functions. |
| +//! Merely referencing `yrs::Doc` anywhere in this crate is enough for those |
| +//! `wasm-bindgen` exports (`__wbindgen_describe`, `__wbindgen_malloc`, ...) |
| +//! to end up linked into the final module, even along code paths that are |
| +//! never reached at runtime — which breaks the zero-imports contract with |
| +//! the Go/wazero host (see `core/tests/no_host_imports.rs`). |
| +//! |
| +//! `docs-wt-core/.cargo/config.toml` selects getrandom's "custom" backend |
| +//! for the `wasm32-unknown-unknown` target only (native builds, including |
| +//! `cargo test`, are unaffected and keep the real OS entropy source). That |
| +//! backend calls out to the `__getrandom_v03_custom` symbol defined below |
| +//! instead of any JS API. This module never actually depends on document |
| +//! GUIDs being unpredictable, so a fixed, non-cryptographic fill is fine. |
| +#[cfg(target_arch = "wasm32")] |
| +#[no_mangle] |
| +extern "Rust" fn __getrandom_v03_custom( |
| + dest: *mut u8, |
| + len: usize, |
| +) -> Result<(), getrandom::Error> { |
| + // SAFETY: `getrandom`'s custom-backend contract requires `dest` to be |
| + // valid for `len` bytes and fully initialized by this function. |
| + let buf = unsafe { std::slice::from_raw_parts_mut(dest, len) }; |
| + buf.fill(0); |
| + Ok(()) |
| +} |
| /// Returns the ABI version this module exports. The Go host checks this on |
| /// load and refuses a module it does not understand, so a stale .wasm on a |
| @@ -15,3 +48,40 @@ |
| pub extern "C" fn docs_core_abi_version() -> u32 { |
| 1 |
| } |
| + |
| +use yrs::updates::decoder::Decode; |
| +use yrs::{Doc, GetString, Transact, Update}; |
| + |
| +#[derive(Debug)] |
| +pub enum CoreError { |
| + /// The bytes were not a valid Yjs v1 update. |
| + Decode(String), |
| + /// The update decoded but could not be applied. |
| + Apply(String), |
| +} |
| + |
| +impl std::fmt::Display for CoreError { |
| + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| + match self { |
| + CoreError::Decode(m) => write!(f, "decode: {m}"), |
| + CoreError::Apply(m) => write!(f, "apply: {m}"), |
| + } |
| + } |
| +} |
| + |
| +/// Applies a Yjs v1 update to `doc`. |
| +pub fn apply_update(doc: &Doc, update: &[u8]) -> Result<(), CoreError> { |
| + let update = Update::decode_v1(update).map_err(|e| CoreError::Decode(e.to_string()))?; |
| + let mut txn = doc.transact_mut(); |
| + txn.apply_update(update) |
| + .map_err(|e| CoreError::Apply(e.to_string())) |
| +} |
| + |
| +/// The plain-text content of the document's root text type. The name |
| +/// "content" matches what the fixture generator writes; it is the CRDT root |
| +/// name and is part of the wire contract. |
| +pub fn text_content(doc: &Doc) -> String { |
| + let text = doc.get_or_insert_text("content"); |
| + let txn = doc.transact(); |
| + text.get_string(&txn) |
| +} |
diff --git a/core/tests/wire_compat.rs b/core/tests/wire_compat.rs| new file mode 100644 |
| index 0000000..fac6bc2 |
| --- /dev/null |
| +++ b/core/tests/wire_compat.rs |
| @@ -0,0 +1,115 @@ |
| +use std::fs; |
| +use std::path::PathBuf; |
| + |
| +use serde_json::{json, Value}; |
| +use yrs::types::text::YChange; |
| +use yrs::types::Attrs; |
| +use yrs::{Any, Doc, Text, Transact}; |
| + |
| +fn fixture(name: &str) -> (Vec<u8>, String, Value) { |
| + let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")) |
| + .parent() |
| + .unwrap() |
| + .join("fixtures/data"); |
| + let update = fs::read(dir.join(format!("{name}.update.bin"))) |
| + .unwrap_or_else(|e| panic!("missing fixture {name}.update.bin: {e}")); |
| + let expected: Value = serde_json::from_str( |
| + &fs::read_to_string(dir.join(format!("{name}.expected.json"))).unwrap(), |
| + ) |
| + .unwrap(); |
| + let text = expected["text"].as_str().unwrap().to_string(); |
| + let delta = expected["delta"].clone(); |
| + (update, text, delta) |
| +} |
| + |
| +/// Converts a `yrs::Any` into the equivalent `serde_json::Value`, so an |
| +/// attribute map read off the CRDT can be compared directly against the |
| +/// `expected.json` fixture written by real JS `yjs`. |
| +fn any_to_json(any: &Any) -> Value { |
| + match any { |
| + Any::Null => Value::Null, |
| + Any::Undefined => Value::Null, |
| + Any::Bool(b) => Value::Bool(*b), |
| + Any::Number(n) => json!(n), |
| + Any::BigInt(n) => json!(n), |
| + Any::String(s) => Value::String(s.to_string()), |
| + Any::Buffer(_) => Value::Null, |
| + Any::Array(items) => Value::Array(items.iter().map(any_to_json).collect()), |
| + Any::Map(map) => { |
| + let mut entries: Vec<(&String, &Any)> = map.iter().collect(); |
| + entries.sort_by(|a, b| a.0.cmp(b.0)); |
| + let mut obj = serde_json::Map::new(); |
| + for (k, v) in entries { |
| + obj.insert(k.clone(), any_to_json(v)); |
| + } |
| + Value::Object(obj) |
| + } |
| + } |
| +} |
| + |
| +/// Converts an `Attrs` map (`HashMap<Arc<str>, Any>`) into a `serde_json::Value` |
| +/// object, with keys sorted so the comparison isn't flaky on `HashMap` |
| +/// iteration order. |
| +fn attrs_to_json(attrs: &Attrs) -> Value { |
| + let mut entries: Vec<(&std::sync::Arc<str>, &Any)> = attrs.iter().collect(); |
| + entries.sort_by(|a, b| a.0.cmp(b.0)); |
| + let mut obj = serde_json::Map::new(); |
| + for (k, v) in entries { |
| + obj.insert(k.to_string(), any_to_json(v)); |
| + } |
| + Value::Object(obj) |
| +} |
| + |
| +/// Produces the same attributed-run shape as Yjs's `toDelta()`, so the |
| +/// fixture's `delta` field (which is what actually proves formatting round- |
| +/// trips, not just plain text) can be compared directly. |
| +fn delta_of(doc: &Doc) -> Value { |
| + let text = doc.get_or_insert_text("content"); |
| + let txn = doc.transact(); |
| + let diffs = text.diff(&txn, YChange::identity); |
| + let runs: Vec<Value> = diffs |
| + .into_iter() |
| + .map(|diff| { |
| + let insert = diff.insert.to_string(&txn); |
| + let mut obj = serde_json::Map::new(); |
| + obj.insert("insert".to_string(), Value::String(insert)); |
| + if let Some(attrs) = diff.attributes { |
| + obj.insert("attributes".to_string(), attrs_to_json(&attrs)); |
| + } |
| + Value::Object(obj) |
| + }) |
| + .collect(); |
| + Value::Array(runs) |
| +} |
| + |
| +fn check(name: &str) { |
| + let (update, expected_text, expected_delta) = fixture(name); |
| + let doc = Doc::with_client_id(9001); // never Doc::new() — see Global Constraints |
| + docs_core::apply_update(&doc, &update).expect("apply failed"); |
| + assert_eq!( |
| + docs_core::text_content(&doc), |
| + expected_text, |
| + "fixture {name} text" |
| + ); |
| + assert_eq!(delta_of(&doc), expected_delta, "fixture {name} delta"); |
| +} |
| + |
| +#[test] |
| +fn applies_hello() { |
| + check("hello"); |
| +} |
| + |
| +#[test] |
| +fn applies_unicode() { |
| + check("unicode"); |
| +} |
| + |
| +#[test] |
| +fn applies_formatted() { |
| + check("formatted"); |
| +} |
| + |
| +#[test] |
| +fn applies_concurrent() { |
| + check("concurrent"); |
| +} |
diff --git a/vendor/README.md b/vendor/README.md| new file mode 100644 |
| index 0000000..1f47c06 |
| --- /dev/null |
| +++ b/vendor/README.md |
| @@ -0,0 +1,45 @@ |
| +# Vendored dependency patches |
| + |
| +## fastrand-2.5.0 |
| + |
| +`yrs` (pinned exact in `core/Cargo.toml`) depends on `fastrand` with its |
| +`js` feature enabled unconditionally, and fastrand's own manifest ties that |
| +feature, on `wasm32-unknown-unknown`, to `getrandom` with the `wasm_js` |
| +feature forced on. That feature makes `getrandom` default to a |
| +`wasm-bindgen`-based backend which imports host JS functions |
| +(`crypto.getRandomValues`, etc.) — an import the Go/wazero host cannot |
| +satisfy, and the thing `core/tests/no_host_imports.rs` gates against. |
| + |
| +`yrs::Doc` calls into this path unconditionally on construction (even via |
| +`Doc::with_client_id`, which still generates a random document GUID via |
| +`fastrand`). Merely referencing `yrs::Doc` anywhere in `docs-core`'s public |
| +API — required by `apply_update`/`text_content`, since the test suite calls |
| +them from a separate compilation unit against the `rlib` — is enough for |
| +those `wasm-bindgen` exports to end up linked into the final `.wasm` module, |
| +even though the code path is never reached at runtime. |
| + |
| +`getrandom` supports exactly this scenario: selecting its `custom` backend |
| +via `--cfg getrandom_backend="custom"` (set in `docs-wt-core/.cargo/ |
| +config.toml`, scoped to the `wasm32-unknown-unknown` target only) routes |
| +entropy requests to a symbol we provide ourselves |
| +(`__getrandom_v03_custom` in `core/src/lib.rs`), with no JS dependency. |
| + |
| +That override alone isn't enough, though: `getrandom-0.4.3`'s `error.rs` |
| +has a `Display` match arm for `Error::WEB_CRYPTO` gated only on |
| +`feature = "wasm_js"` (not on which backend is actually selected), while |
| +`Error::WEB_CRYPTO` itself is defined inside the `wasm_js` backend module, |
| +which a `custom`-backend override skips compiling entirely. As long as |
| +fastrand keeps requesting the `wasm_js` feature, this is a hard compile |
| +error (`E0599`) — Cargo features are additive across the whole dependency |
| +graph, so `docs-core` cannot un-request a feature another crate requires. |
| + |
| +This vendored copy of `fastrand-2.5.0` (unmodified Rust source; see the |
| +comment in its `Cargo.toml`) drops the forced `features = ["wasm_js"]` on |
| +its `wasm32`/`wasm64`-`unknown` `getrandom` dependency, so nothing in the |
| +graph requests that feature and the conflicting match arm is never |
| +compiled. `fastrand`'s actual logic (the `js` feature still exists, and |
| +`fastrand::Rng::new()` still calls into `getrandom`) is untouched — only |
| +which `getrandom` backend gets linked changes, and that is exactly what the |
| +`--cfg getrandom_backend="custom"` override is choosing on purpose. |
| + |
| +Wired in via `[patch.crates-io]` in `core/Cargo.toml`. |
diff --git a/vendor/fastrand-2.5.0/CHANGELOG.md b/vendor/fastrand-2.5.0/CHANGELOG.md| new file mode 100644 |
| index 0000000..455730f |
| --- /dev/null |
| +++ b/vendor/fastrand-2.5.0/CHANGELOG.md |
| @@ -0,0 +1,140 @@ |
| +# Version 2.5.0 |
| + |
| +- Update `getrandom` to 0.4. (#131) |
| + |
| +# Version 2.4.1 |
| + |
| +- Fix build failure with `js` feature. (#125) |
| + |
| +# Version 2.4.0 |
| + |
| +- Bump MSRV to 1.63. (#104) |
| +- Improve quality of f32/f64 generation. (#103) |
| +- Add `f{32,64}_inclusive` and `Rng::f{32,64}_inclusive`. (#103) |
| +- Make `Rng::with_seed` const. (#107) |
| +- Update `getrandom` to 0.3. (#104) |
| + |
| +# Version 2.3.0 |
| + |
| +- Accept `IntoIterator` in `choose_multiple` functions instead of just `Iterator`. (#92) |
| + |
| +# Version 2.2.0 |
| + |
| +- Expose missing `fill` method for the global RNG. (#90) |
| + |
| +# Version 2.1.1 |
| + |
| +- Remove support for 128-bit targets, as they are not supported by rustc yet. (#87) |
| + |
| +# Version 2.1.0 |
| + |
| +- Change the RNG algorithm and the way that the seed is computed. This will cause |
| + the algorithm to emit different constants for different seeds, hence the minor |
| + SemVer change. |
| + - Update to the final WyRand v4.2 constants for better entropy. (#82) |
| + - Remove an unnecessary seed modification. (#73) |
| + |
| +# Version 2.0.2 |
| + |
| +- Slight restructuring of the `with_seed` function. (#79) |
| + |
| +# Version 2.0.1 |
| + |
| +- Clarify documentation for the `fork()` method. (#62) |
| +- Mention `fastrand-contrib` in documentation. (#70) |
| + |
| +# Version 2.0.0 |
| + |
| +- **Breaking:** Remove interior mutability from `Rng`. (#47) |
| +- Add a `fork()` method. (#49) |
| +- Add a `no_std` mode. (#50) |
| +- Add an iterator selection function. (#51) |
| +- Add a `choose_multiple()` function for sampling several elements from an iterator. (#55) |
| +- Use the `getrandom` crate for seeding on WebAssembly targets if the `js` feature is enabled. (#60) |
| + |
| +# Version 1.9.0 |
| + |
| +- Add `Rng::fill()` (#35, #43) |
| +- Add `#[must_use]` to `Rng::with_seed()` (#46) |
| + |
| +# Version 1.8.0 |
| + |
| +- Add `get_seed()` and `Rng::get_seed()` (#33) |
| + |
| +# Version 1.7.0 |
| + |
| +- Add `char()` and `Rng::char()` (#25) |
| + |
| +# Version 1.6.0 |
| + |
| +- Implement `PartialEq` and `Eq` for `Rng` (#23) |
| + |
| +# Version 1.5.0 |
| + |
| +- Switch to Wyrand (#14) |
| + |
| +# Version 1.4.1 |
| + |
| +- Fix bug when generating a signed integer within a range (#16) |
| + |
| +# Version 1.4.0 |
| + |
| +- Add wasm support. |
| + |
| +# Version 1.3.5 |
| + |
| +- Reword docs. |
| +- Add `Rng::with_seed()`. |
| + |
| +# Version 1.3.4 |
| + |
| +- Implement `Clone` for `Rng`. |
| + |
| +# Version 1.3.3 |
| + |
| +- Forbid unsafe code. |
| + |
| +# Version 1.3.2 |
| + |
| +- Support older Rust versions. |
| + |
| +# Version 1.3.1 |
| + |
| +- Tweak Cargo keywords. |
| + |
| +# Version 1.3.0 |
| + |
| +- Add `f32()` and `f64()`. |
| +- Add `lowercase()`, `uppercase()`, `alphabetic()`, and `digit()`. |
| + |
| +# Version 1.2.4 |
| + |
| +- Switch to PCG XSH RR 64/32. |
| +- Fix a bug in `gen_mod_u128`. |
| +- Fix bias in ranges. |
| + |
| +# Version 1.2.3 |
| + |
| +- Support Rust 1.32.0 |
| + |
| +# Version 1.2.2 |
| + |
| +- Use `std::$t::MAX` rather than `$t::MAX` to support older Rust versions. |
| + |
| +# Version 1.2.1 |
| + |
| +- Inline all functions. |
| + |
| +# Version 1.2.0 |
| + |
| +- Add `Rng` struct. |
| + |
| +# Version 1.1.0 |
| + |
| +- Switch to PCG implementation. |
| +- Add `alphanumeric()`. |
| +- Add `seed()`. |
| + |
| +# Version 1.0.0 |
| + |
| +- Initial version |
diff --git a/vendor/fastrand-2.5.0/Cargo.toml b/vendor/fastrand-2.5.0/Cargo.toml| new file mode 100644 |
| index 0000000..e21cde2 |
| --- /dev/null |
| +++ b/vendor/fastrand-2.5.0/Cargo.toml |
| @@ -0,0 +1,96 @@ |
| +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO |
| +# |
| +# When uploading crates to the registry Cargo will automatically |
| +# "normalize" Cargo.toml files for maximal compatibility |
| +# with all versions of Cargo and also rewrite `path` dependencies |
| +# to registry (e.g., crates.io) dependencies. |
| +# |
| +# If you are reading this file be aware that the original Cargo.toml |
| +# will likely look very different (and much more reasonable). |
| +# See Cargo.toml.orig for the original contents. |
| + |
| +[package] |
| +edition = "2018" |
| +rust-version = "1.63" |
| +name = "fastrand" |
| +version = "2.5.0" |
| +authors = ["Stjepan Glavina <stjepang@gmail.com>"] |
| +build = false |
| +exclude = ["/.*"] |
| +autolib = false |
| +autobins = false |
| +autoexamples = false |
| +autotests = false |
| +autobenches = false |
| +description = "A simple and fast random number generator" |
| +readme = "README.md" |
| +keywords = [ |
| + "simple", |
| + "fast", |
| + "rand", |
| + "random", |
| + "wyrand", |
| +] |
| +categories = ["algorithms"] |
| +license = "Apache-2.0 OR MIT" |
| +repository = "https://github.com/smol-rs/fastrand" |
| + |
| +[package.metadata.docs.rs] |
| +all-features = true |
| +rustdoc-args = [ |
| + "--cfg", |
| + "docsrs", |
| +] |
| + |
| +[features] |
| +alloc = [] |
| +default = ["std"] |
| +js = [ |
| + "std", |
| + "getrandom", |
| +] |
| +std = ["alloc"] |
| + |
| +[lib] |
| +name = "fastrand" |
| +path = "src/lib.rs" |
| + |
| +[[test]] |
| +name = "char" |
| +path = "tests/char.rs" |
| + |
| +[[test]] |
| +name = "smoke" |
| +path = "tests/smoke.rs" |
| + |
| +[[bench]] |
| +name = "bench" |
| +path = "benches/bench.rs" |
| + |
| +[dev-dependencies.getrandom] |
| +version = "0.4" |
| + |
| +[dev-dependencies.rand] |
| +version = "0.10" |
| + |
| +[dev-dependencies.wyhash] |
| +version = "0.6" |
| + |
| +# Vendored patch (see docs-wt-core/vendor/README.md): dropped the forced |
| +# "wasm_js" feature so that a `--cfg getrandom_backend="..."` override (used |
| +# by docs-core to avoid a wasm-bindgen/JS import dependency) doesn't hit |
| +# getrandom's `Error::WEB_CRYPTO` cfg mismatch (that item only exists when |
| +# the "wasm_js" backend module itself is compiled, which a cfg override to |
| +# a different backend skips, but `error.rs`'s Display impl references it |
| +# whenever the "wasm_js" *feature* is enabled, regardless of which backend |
| +# is actually selected). |
| +[target.'cfg(all(any(target_arch = "wasm32", target_arch = "wasm64"), target_os = "unknown"))'.dependencies.getrandom] |
| +version = "0.4" |
| +optional = true |
| + |
| +[target.'cfg(all(any(target_arch = "wasm32", target_arch = "wasm64"), target_os = "unknown"))'.dev-dependencies.getrandom] |
| +version = "0.4" |
| +features = ["wasm_js"] |
| + |
| +[target.'cfg(all(any(target_arch = "wasm32", target_arch = "wasm64"), target_os = "unknown"))'.dev-dependencies.wasm-bindgen-test] |
| +version = "0.3" |
diff --git a/vendor/fastrand-2.5.0/LICENSE-APACHE b/vendor/fastrand-2.5.0/LICENSE-APACHE| new file mode 100644 |
| index 0000000..16fe87b |
| --- /dev/null |
| +++ b/vendor/fastrand-2.5.0/LICENSE-APACHE |
| @@ -0,0 +1,201 @@ |
| + 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/vendor/fastrand-2.5.0/LICENSE-MIT b/vendor/fastrand-2.5.0/LICENSE-MIT| new file mode 100644 |
| index 0000000..31aa793 |
| --- /dev/null |
| +++ b/vendor/fastrand-2.5.0/LICENSE-MIT |
| @@ -0,0 +1,23 @@ |
| +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/vendor/fastrand-2.5.0/README.md b/vendor/fastrand-2.5.0/README.md| new file mode 100644 |
| index 0000000..f478b42 |
| --- /dev/null |
| +++ b/vendor/fastrand-2.5.0/README.md |
| @@ -0,0 +1,110 @@ |
| +# fastrand |
| + |
| +[]( |
| +https://github.com/smol-rs/fastrand/actions) |
| +[]( |
| +https://github.com/smol-rs/fastrand) |
| +[]( |
| +https://crates.io/crates/fastrand) |
| +[]( |
| +https://docs.rs/fastrand) |
| + |
| +A simple and fast random number generator. |
| + |
| +The implementation uses [Wyrand](https://github.com/wangyi-fudan/wyhash), a simple and fast |
| +generator but **not** cryptographically secure. |
| + |
| +## Examples |
| + |
| +Flip a coin: |
| + |
| +```rust |
| +if fastrand::bool() { |
| + println!("heads"); |
| +} else { |
| + println!("tails"); |
| +} |
| +``` |
| + |
| +Generate a random `i32`: |
| + |
| +```rust |
| +let num = fastrand::i32(..); |
| +``` |
| + |
| +Choose a random element in an array: |
| + |
| +```rust |
| +let v = vec![1, 2, 3, 4, 5]; |
| +let i = fastrand::usize(..v.len()); |
| +let elem = v[i]; |
| +``` |
| + |
| +Sample values from an array with `O(n)` complexity (`n` is the length of the array): |
| + |
| +```rust |
| +fastrand::choose_multiple([1, 4, 5], 2); |
| +fastrand::choose_multiple(0..20, 12); |
| +``` |
| + |
| +Shuffle an array: |
| + |
| +```rust |
| +let mut v = vec![1, 2, 3, 4, 5]; |
| +fastrand::shuffle(&mut v); |
| +``` |
| + |
| +Generate a random `Vec` or `String`: |
| + |
| +```rust |
| +use std::iter::repeat_with; |
| + |
| +let v: Vec<i32> = repeat_with(|| fastrand::i32(..)).take(10).collect(); |
| +let s: String = repeat_with(fastrand::alphanumeric).take(10).collect(); |
| +``` |
| + |
| +To get reproducible results on every run, initialize the generator with a seed: |
| + |
| +```rust |
| +// Pick an arbitrary number as seed. |
| +fastrand::seed(7); |
| + |
| +// Now this prints the same number on every run: |
| +println!("{}", fastrand::u32(..)); |
| +``` |
| + |
| +To be more efficient, create a new `Rng` instance instead of using the thread-local |
| +generator: |
| + |
| +```rust |
| +use std::iter::repeat_with; |
| + |
| +let mut rng = fastrand::Rng::new(); |
| +let mut bytes: Vec<u8> = repeat_with(|| rng.u8(..)).take(10_000).collect(); |
| +``` |
| + |
| +This crate aims to expose a core set of useful randomness primitives. For more niche algorithms, consider using the [`fastrand-contrib`] crate alongside this one. |
| + |
| +# Features |
| + |
| +- `std` (enabled by default): Enables the `std` library. This is required for the global |
| + generator and global entropy. Without this feature, [`Rng`] can only be instantiated using |
| + the [`with_seed`](https://docs.rs/fastrand/latest/fastrand/struct.Rng.html#method.with_seed) method. |
| +- `js`: Assumes that WebAssembly targets are being run in a JavaScript environment. |
| + |
| +[`fastrand-contrib`]: https://crates.io/crates/fastrand-contrib |
| + |
| +## License |
| + |
| +Licensed under either of |
| + |
| + * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or https://www.apache.org/licenses/LICENSE-2.0) |
| + * MIT license ([LICENSE-MIT](LICENSE-MIT) or https://opensource.org/license/mit) |
| + |
| +at your option. |
| + |
| +#### Contribution |
| + |
| +Unless you explicitly state otherwise, any contribution intentionally submitted |
| +for inclusion in the work by you, as defined in the Apache-2.0 license, shall be |
| +dual licensed as above, without any additional terms or conditions. |
diff --git a/vendor/fastrand-2.5.0/benches/bench.rs b/vendor/fastrand-2.5.0/benches/bench.rs| new file mode 100644 |
| index 0000000..4789e80 |
| --- /dev/null |
| +++ b/vendor/fastrand-2.5.0/benches/bench.rs |
| @@ -0,0 +1,141 @@ |
| +#![feature(test)] |
| + |
| +extern crate test; |
| + |
| +use rand::prelude::*; |
| +use test::Bencher; |
| + |
| +/// Exposes wyhash's RNG through the rand traits |
| +struct WyRng(u64); |
| + |
| +impl rand::TryRng for WyRng { |
| + type Error = std::convert::Infallible; |
| + |
| + fn try_next_u32(&mut self) -> Result<u32, Self::Error> { |
| + Ok(wyhash::wyrng(&mut self.0) as u32) |
| + } |
| + |
| + fn try_next_u64(&mut self) -> Result<u64, Self::Error> { |
| + Ok(wyhash::wyrng(&mut self.0)) |
| + } |
| + |
| + fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Self::Error> { |
| + for chunk in dst.chunks_mut(8) { |
| + let bytes = wyhash::wyrng(&mut self.0).to_le_bytes(); |
| + chunk.copy_from_slice(&bytes[..chunk.len()]); |
| + } |
| + Ok(()) |
| + } |
| +} |
| + |
| +fn wyrng() -> WyRng { |
| + WyRng(rand::random()) |
| +} |
| + |
| +#[bench] |
| +fn shuffle_wyhash(b: &mut Bencher) { |
| + let mut rng = wyrng(); |
| + let mut x = (0..100).collect::<Vec<usize>>(); |
| + b.iter(|| { |
| + x.shuffle(&mut rng); |
| + x[0] |
| + }) |
| +} |
| + |
| +#[bench] |
| +fn shuffle_fastrand(b: &mut Bencher) { |
| + let mut rng = fastrand::Rng::new(); |
| + let mut x = (0..100).collect::<Vec<usize>>(); |
| + b.iter(|| { |
| + rng.shuffle(&mut x); |
| + x[0] |
| + }) |
| +} |
| + |
| +#[bench] |
| +fn u8_wyhash(b: &mut Bencher) { |
| + let mut rng = wyrng(); |
| + b.iter(|| { |
| + let mut sum = 0u8; |
| + for _ in 0..10_000 { |
| + sum = sum.wrapping_add(rng.random::<u8>()); |
| + } |
| + sum |
| + }) |
| +} |
| + |
| +#[bench] |
| +fn u8_fastrand(b: &mut Bencher) { |
| + let mut rng = fastrand::Rng::new(); |
| + b.iter(|| { |
| + let mut sum = 0u8; |
| + for _ in 0..10_000 { |
| + sum = sum.wrapping_add(rng.u8(..)); |
| + } |
| + sum |
| + }) |
| +} |
| + |
| +#[bench] |
| +fn u32_wyhash(b: &mut Bencher) { |
| + let mut rng = wyrng(); |
| + b.iter(|| { |
| + let mut sum = 0u32; |
| + for _ in 0..10_000 { |
| + sum = sum.wrapping_add(rng.random::<u32>()); |
| + } |
| + sum |
| + }) |
| +} |
| + |
| +#[bench] |
| +fn u32_fastrand(b: &mut Bencher) { |
| + let mut rng = fastrand::Rng::new(); |
| + b.iter(|| { |
| + let mut sum = 0u32; |
| + for _ in 0..10_000 { |
| + sum = sum.wrapping_add(rng.u32(..)); |
| + } |
| + sum |
| + }) |
| +} |
| + |
| +#[bench] |
| +fn f32_fastrand(b: &mut Bencher) { |
| + let mut rng = fastrand::Rng::new(); |
| + b.iter(|| { |
| + // f32 sum unrolled 2x to hide f32-add latency. |
| + // |
| + // Optimal amount of unrolling is somewhat sensitive to CPU and algorithm. |
| + // Variously could be 2x, 3x, or 4x unrolling. On AArch64 and x86-64 on the |
| + // current algorithm, 2x seems to be optimal on this benchmark. |
| + let mut sum = 0.0; |
| + for _ in 0..5_000 { |
| + sum += rng.f32() + rng.f32(); |
| + } |
| + sum |
| + }) |
| +} |
| + |
| +#[bench] |
| +fn fill(b: &mut Bencher) { |
| + let mut rng = fastrand::Rng::new(); |
| + b.iter(|| { |
| + // Pick a size that isn't divisible by 8. |
| + let mut bytes = [0u8; 367]; |
| + rng.fill(&mut bytes); |
| + bytes |
| + }) |
| +} |
| + |
| +#[bench] |
| +fn fill_naive(b: &mut Bencher) { |
| + let mut rng = fastrand::Rng::new(); |
| + b.iter(|| { |
| + let mut bytes = [0u8; 367]; |
| + for item in &mut bytes { |
| + *item = rng.u8(..); |
| + } |
| + bytes |
| + }) |
| +} |
diff --git a/vendor/fastrand-2.5.0/src/global_rng.rs b/vendor/fastrand-2.5.0/src/global_rng.rs| new file mode 100644 |
| index 0000000..bfece0a |
| --- /dev/null |
| +++ b/vendor/fastrand-2.5.0/src/global_rng.rs |
| @@ -0,0 +1,234 @@ |
| +//! A global, thread-local random number generator. |
| + |
| +use crate::Rng; |
| + |
| +use std::cell::Cell; |
| +use std::ops::RangeBounds; |
| +use std::vec::Vec; |
| + |
| +// Chosen by a fair roll of the dice. |
| +const DEFAULT_RNG_SEED: u64 = 0xef6f79ed30ba75a; |
| + |
| +impl Default for Rng { |
| + /// Initialize the `Rng` from the system's random number generator. |
| + /// |
| + /// This is equivalent to [`Rng::new()`]. |
| + #[inline] |
| + fn default() -> Rng { |
| + Rng::new() |
| + } |
| +} |
| + |
| +impl Rng { |
| + /// Creates a new random number generator. |
| + #[inline] |
| + pub fn new() -> Rng { |
| + try_with_rng(Rng::fork).unwrap_or_else(|_| Rng::with_seed(0x4d595df4d0f33173)) |
| + } |
| +} |
| + |
| +std::thread_local! { |
| + static RNG: Cell<Rng> = Cell::new(Rng(random_seed().unwrap_or(DEFAULT_RNG_SEED))); |
| +} |
| + |
| +/// Run an operation with the current thread-local generator. |
| +#[inline] |
| +fn with_rng<R>(f: impl FnOnce(&mut Rng) -> R) -> R { |
| + RNG.with(|rng| { |
| + let current = rng.replace(Rng(0)); |
| + |
| + let mut restore = RestoreOnDrop { rng, current }; |
| + |
| + f(&mut restore.current) |
| + }) |
| +} |
| + |
| +/// Try to run an operation with the current thread-local generator. |
| +#[inline] |
| +fn try_with_rng<R>(f: impl FnOnce(&mut Rng) -> R) -> Result<R, std::thread::AccessError> { |
| + RNG.try_with(|rng| { |
| + let current = rng.replace(Rng(0)); |
| + |
| + let mut restore = RestoreOnDrop { rng, current }; |
| + |
| + f(&mut restore.current) |
| + }) |
| +} |
| + |
| +/// Make sure the original RNG is restored even on panic. |
| +struct RestoreOnDrop<'a> { |
| + rng: &'a Cell<Rng>, |
| + current: Rng, |
| +} |
| + |
| +impl Drop for RestoreOnDrop<'_> { |
| + fn drop(&mut self) { |
| + self.rng.set(Rng(self.current.0)); |
| + } |
| +} |
| + |
| +/// Initializes the thread-local generator with the given seed. |
| +#[inline] |
| +pub fn seed(seed: u64) { |
| + with_rng(|r| r.seed(seed)); |
| +} |
| + |
| +/// Gives back **current** seed that is being held by the thread-local generator. |
| +#[inline] |
| +pub fn get_seed() -> u64 { |
| + with_rng(|r| r.get_seed()) |
| +} |
| + |
| +/// Generates a random `bool`. |
| +#[inline] |
| +pub fn bool() -> bool { |
| + with_rng(|r| r.bool()) |
| +} |
| + |
| +/// Generates a random `char` in range a-z and A-Z. |
| +#[inline] |
| +pub fn alphabetic() -> char { |
| + with_rng(|r| r.alphabetic()) |
| +} |
| + |
| +/// Generates a random `char` in range a-z, A-Z and 0-9. |
| +#[inline] |
| +pub fn alphanumeric() -> char { |
| + with_rng(|r| r.alphanumeric()) |
| +} |
| + |
| +/// Generates a random `char` in range a-z. |
| +#[inline] |
| +pub fn lowercase() -> char { |
| + with_rng(|r| r.lowercase()) |
| +} |
| + |
| +/// Generates a random `char` in range A-Z. |
| +#[inline] |
| +pub fn uppercase() -> char { |
| + with_rng(|r| r.uppercase()) |
| +} |
| + |
| +/// Choose an item from an iterator at random. |
| +/// |
| +/// This function may have an unexpected result if the `len()` property of the |
| +/// iterator does not match the actual number of items in the iterator. If |
| +/// the iterator is empty, this returns `None`. |
| +#[inline] |
| +pub fn choice<I>(iter: I) -> Option<I::Item> |
| +where |
| + I: IntoIterator, |
| + I::IntoIter: ExactSizeIterator, |
| +{ |
| + with_rng(|r| r.choice(iter)) |
| +} |
| + |
| +/// Generates a random digit in the given `base`. |
| +/// |
| +/// Digits are represented by `char`s in range 0-9 and a-z. |
| +/// |
| +/// Panics if the base is zero or greater than 36. |
| +#[inline] |
| +pub fn digit(base: u32) -> char { |
| + with_rng(|r| r.digit(base)) |
| +} |
| + |
| +/// Shuffles a slice randomly. |
| +#[inline] |
| +pub fn shuffle<T>(slice: &mut [T]) { |
| + with_rng(|r| r.shuffle(slice)) |
| +} |
| + |
| +/// Fill a byte slice with random data. |
| +#[inline] |
| +pub fn fill(slice: &mut [u8]) { |
| + with_rng(|r| r.fill(slice)) |
| +} |
| + |
| +macro_rules! integer { |
| + ($t:tt, $doc:tt) => { |
| + #[doc = $doc] |
| + /// |
| + /// Panics if the range is empty. |
| + #[inline] |
| + pub fn $t(range: impl RangeBounds<$t>) -> $t { |
| + with_rng(|r| r.$t(range)) |
| + } |
| + }; |
| +} |
| + |
| +integer!(u8, "Generates a random `u8` in the given range."); |
| +integer!(i8, "Generates a random `i8` in the given range."); |
| +integer!(u16, "Generates a random `u16` in the given range."); |
| +integer!(i16, "Generates a random `i16` in the given range."); |
| +integer!(u32, "Generates a random `u32` in the given range."); |
| +integer!(i32, "Generates a random `i32` in the given range."); |
| +integer!(u64, "Generates a random `u64` in the given range."); |
| +integer!(i64, "Generates a random `i64` in the given range."); |
| +integer!(u128, "Generates a random `u128` in the given range."); |
| +integer!(i128, "Generates a random `i128` in the given range."); |
| +integer!(usize, "Generates a random `usize` in the given range."); |
| +integer!(isize, "Generates a random `isize` in the given range."); |
| +integer!(char, "Generates a random `char` in the given range."); |
| + |
| +/// Generates a random `f32` in range `0..1`. |
| +pub fn f32() -> f32 { |
| + with_rng(|r| r.f32()) |
| +} |
| + |
| +/// Generates a random `f32` in range `0..=1`. |
| +pub fn f32_inclusive() -> f32 { |
| + with_rng(|r| r.f32_inclusive()) |
| +} |
| + |
| +/// Generates a random `f64` in range `0..1`. |
| +pub fn f64() -> f64 { |
| + with_rng(|r| r.f64()) |
| +} |
| + |
| +/// Generates a random `f64` in range `0..=1`. |
| +pub fn f64_inclusive() -> f64 { |
| + with_rng(|r| r.f64_inclusive()) |
| +} |
| + |
| +/// Collects `amount` values at random from the iterable into a vector. |
| +pub fn choose_multiple<I: IntoIterator>(source: I, amount: usize) -> Vec<I::Item> { |
| + with_rng(|rng| rng.choose_multiple(source, amount)) |
| +} |
| + |
| +#[cfg(not(all( |
| + any(target_arch = "wasm32", target_arch = "wasm64"), |
| + target_os = "unknown" |
| +)))] |
| +fn random_seed() -> Option<u64> { |
| + use std::collections::hash_map::DefaultHasher; |
| + use std::hash::{Hash, Hasher}; |
| + use std::thread; |
| + use std::time::Instant; |
| + |
| + let mut hasher = DefaultHasher::new(); |
| + Instant::now().hash(&mut hasher); |
| + thread::current().id().hash(&mut hasher); |
| + Some(hasher.finish()) |
| +} |
| + |
| +#[cfg(all( |
| + any(target_arch = "wasm32", target_arch = "wasm64"), |
| + target_os = "unknown", |
| + feature = "js" |
| +))] |
| +fn random_seed() -> Option<u64> { |
| + // TODO(notgull): Failures should be logged somewhere. |
| + let mut seed = [0u8; 8]; |
| + getrandom::fill(&mut seed).ok()?; |
| + Some(u64::from_ne_bytes(seed)) |
| +} |
| + |
| +#[cfg(all( |
| + any(target_arch = "wasm32", target_arch = "wasm64"), |
| + target_os = "unknown", |
| + not(feature = "js") |
| +))] |
| +fn random_seed() -> Option<u64> { |
| + None |
| +} |
diff --git a/vendor/fastrand-2.5.0/src/lib.rs b/vendor/fastrand-2.5.0/src/lib.rs| new file mode 100644 |
| index 0000000..a753110 |
| --- /dev/null |
| +++ b/vendor/fastrand-2.5.0/src/lib.rs |
| @@ -0,0 +1,736 @@ |
| +//! A simple and fast random number generator. |
| +//! |
| +//! The implementation uses [Wyrand](https://github.com/wangyi-fudan/wyhash), a simple and fast |
| +//! generator but **not** cryptographically secure. |
| +//! |
| +//! # Examples |
| +//! |
| +//! Flip a coin: |
| +//! |
| +//! ``` |
| +//! if fastrand::bool() { |
| +//! println!("heads"); |
| +//! } else { |
| +//! println!("tails"); |
| +//! } |
| +//! ``` |
| +//! |
| +//! Generate a random `i32`: |
| +//! |
| +//! ``` |
| +//! let num = fastrand::i32(..); |
| +//! ``` |
| +//! |
| +//! Choose a random element in an array: |
| +//! |
| +//! ``` |
| +//! let v = vec![1, 2, 3, 4, 5]; |
| +//! let i = fastrand::usize(..v.len()); |
| +//! let elem = v[i]; |
| +//! ``` |
| +//! |
| +//! Sample values from an array with `O(n)` complexity (`n` is the length of the array): |
| +//! |
| +//! ``` |
| +//! fastrand::choose_multiple([1, 4, 5], 2); |
| +//! fastrand::choose_multiple(0..20, 12); |
| +//! ``` |
| +//! |
| +//! |
| +//! Shuffle an array: |
| +//! |
| +//! ``` |
| +//! let mut v = vec![1, 2, 3, 4, 5]; |
| +//! fastrand::shuffle(&mut v); |
| +//! ``` |
| +//! |
| +//! Generate a random [`Vec`] or [`String`](alloc::string::String): |
| +//! |
| +//! ``` |
| +//! use std::iter::repeat_with; |
| +//! |
| +//! let v: Vec<i32> = repeat_with(|| fastrand::i32(..)).take(10).collect(); |
| +//! let s: String = repeat_with(fastrand::alphanumeric).take(10).collect(); |
| +//! ``` |
| +//! |
| +//! To get reproducible results on every run, initialize the generator with a seed: |
| +//! |
| +//! ``` |
| +//! // Pick an arbitrary number as seed. |
| +//! fastrand::seed(7); |
| +//! |
| +//! // Now this prints the same number on every run: |
| +//! println!("{}", fastrand::u32(..)); |
| +//! ``` |
| +//! |
| +//! To be more efficient, create a new [`Rng`] instance instead of using the thread-local |
| +//! generator: |
| +//! |
| +//! ``` |
| +//! use std::iter::repeat_with; |
| +//! |
| +//! let mut rng = fastrand::Rng::new(); |
| +//! let mut bytes: Vec<u8> = repeat_with(|| rng.u8(..)).take(10_000).collect(); |
| +//! ``` |
| +//! |
| +//! This crate aims to expose a core set of useful randomness primitives. For more niche algorithms, |
| +//! consider using the [`fastrand-contrib`] crate alongside this one. |
| +//! |
| +//! # Features |
| +//! |
| +//! - `std` (enabled by default): Enables the `std` library. This is required for the global |
| +//! generator and global entropy. Without this feature, [`Rng`] can only be instantiated using |
| +//! the [`with_seed`](Rng::with_seed) method. |
| +//! - `js`: Assumes that WebAssembly targets are being run in a JavaScript environment. See the |
| +//! [WebAssembly Notes](#webassembly-notes) section for more information. |
| +//! |
| +//! # WebAssembly Notes |
| +//! |
| +//! For non-WASI WASM targets, there is additional subtlety to consider when utilizing the global RNG. |
| +//! By default, `std` targets will use entropy sources in the standard library to seed the global RNG. |
| +//! However, these sources are not available by default on WASM targets outside of WASI. |
| +//! |
| +//! If the `js` feature is enabled, this crate will assume that it is running in a JavaScript |
| +//! environment. At this point, the [`getrandom`] crate will be used in order to access the available |
| +//! entropy sources and seed the global RNG. If the `js` feature is not enabled, the global RNG will |
| +//! use a predefined seed. |
| +//! |
| +//! [`fastrand-contrib`]: https://crates.io/crates/fastrand-contrib |
| +//! [`getrandom`]: https://crates.io/crates/getrandom |
| + |
| +#![no_std] |
| +#![cfg_attr(docsrs, feature(doc_cfg))] |
| +#![forbid(unsafe_code)] |
| +#![warn(missing_docs, missing_debug_implementations, rust_2018_idioms)] |
| +#![doc( |
| + html_favicon_url = "https://raw.githubusercontent.com/smol-rs/smol/master/assets/images/logo_fullsize_transparent.png" |
| +)] |
| +#![doc( |
| + html_logo_url = "https://raw.githubusercontent.com/smol-rs/smol/master/assets/images/logo_fullsize_transparent.png" |
| +)] |
| + |
| +#[cfg(feature = "alloc")] |
| +extern crate alloc; |
| +#[cfg(feature = "std")] |
| +extern crate std; |
| + |
| +use core::convert::{TryFrom, TryInto}; |
| +use core::ops::{Bound, RangeBounds}; |
| + |
| +#[cfg(feature = "alloc")] |
| +use alloc::vec::Vec; |
| + |
| +#[cfg(feature = "std")] |
| +mod global_rng; |
| + |
| +#[cfg(feature = "std")] |
| +pub use global_rng::*; |
| + |
| +/// A random number generator. |
| +#[derive(Debug, PartialEq, Eq)] |
| +pub struct Rng(u64); |
| + |
| +impl Clone for Rng { |
| + /// Clones the generator by creating a new generator with the same seed. |
| + fn clone(&self) -> Rng { |
| + Rng::with_seed(self.0) |
| + } |
| +} |
| + |
| +impl Rng { |
| + /// Generates a random `u32`. |
| + #[inline] |
| + fn gen_u32(&mut self) -> u32 { |
| + self.gen_u64() as u32 |
| + } |
| + |
| + /// Generates a random `u64`. |
| + #[inline] |
| + fn gen_u64(&mut self) -> u64 { |
| + // Constants for WyRand taken from: https://github.com/wangyi-fudan/wyhash/blob/master/wyhash.h#L151 |
| + // Updated for the final v4.2 implementation with improved constants for better entropy output. |
| + const WY_CONST_0: u64 = 0x2d35_8dcc_aa6c_78a5; |
| + const WY_CONST_1: u64 = 0x8bb8_4b93_962e_acc9; |
| + |
| + let s = self.0.wrapping_add(WY_CONST_0); |
| + self.0 = s; |
| + let t = u128::from(s) * u128::from(s ^ WY_CONST_1); |
| + (t as u64) ^ (t >> 64) as u64 |
| + } |
| + |
| + /// Generates a random `u128`. |
| + #[inline] |
| + fn gen_u128(&mut self) -> u128 { |
| + (u128::from(self.gen_u64()) << 64) | u128::from(self.gen_u64()) |
| + } |
| + |
| + /// Generates a random `u32` in `0..n`. |
| + #[inline] |
| + fn gen_mod_u32(&mut self, n: u32) -> u32 { |
| + // Adapted from: https://lemire.me/blog/2016/06/30/fast-random-shuffling/ |
| + let mut r = self.gen_u32(); |
| + let mut hi = mul_high_u32(r, n); |
| + let mut lo = r.wrapping_mul(n); |
| + if lo < n { |
| + let t = n.wrapping_neg() % n; |
| + while lo < t { |
| + r = self.gen_u32(); |
| + hi = mul_high_u32(r, n); |
| + lo = r.wrapping_mul(n); |
| + } |
| + } |
| + hi |
| + } |
| + |
| + /// Generates a random `u64` in `0..n`. |
| + #[inline] |
| + fn gen_mod_u64(&mut self, n: u64) -> u64 { |
| + // Adapted from: https://lemire.me/blog/2016/06/30/fast-random-shuffling/ |
| + let mut r = self.gen_u64(); |
| + let mut hi = mul_high_u64(r, n); |
| + let mut lo = r.wrapping_mul(n); |
| + if lo < n { |
| + let t = n.wrapping_neg() % n; |
| + while lo < t { |
| + r = self.gen_u64(); |
| + hi = mul_high_u64(r, n); |
| + lo = r.wrapping_mul(n); |
| + } |
| + } |
| + hi |
| + } |
| + |
| + /// Generates a random `u128` in `0..n`. |
| + #[inline] |
| + fn gen_mod_u128(&mut self, n: u128) -> u128 { |
| + // Adapted from: https://lemire.me/blog/2016/06/30/fast-random-shuffling/ |
| + let mut r = self.gen_u128(); |
| + let mut hi = mul_high_u128(r, n); |
| + let mut lo = r.wrapping_mul(n); |
| + if lo < n { |
| + let t = n.wrapping_neg() % n; |
| + while lo < t { |
| + r = self.gen_u128(); |
| + hi = mul_high_u128(r, n); |
| + lo = r.wrapping_mul(n); |
| + } |
| + } |
| + hi |
| + } |
| +} |
| + |
| +/// Computes `(a * b) >> 32`. |
| +#[inline] |
| +fn mul_high_u32(a: u32, b: u32) -> u32 { |
| + (((a as u64) * (b as u64)) >> 32) as u32 |
| +} |
| + |
| +/// Computes `(a * b) >> 64`. |
| +#[inline] |
| +fn mul_high_u64(a: u64, b: u64) -> u64 { |
| + (((a as u128) * (b as u128)) >> 64) as u64 |
| +} |
| + |
| +/// Computes `(a * b) >> 128`. |
| +#[inline] |
| +fn mul_high_u128(a: u128, b: u128) -> u128 { |
| + // Adapted from: https://stackoverflow.com/a/28904636 |
| + let a_lo = a as u64 as u128; |
| + let a_hi = (a >> 64) as u64 as u128; |
| + let b_lo = b as u64 as u128; |
| + let b_hi = (b >> 64) as u64 as u128; |
| + let carry = (a_lo * b_lo) >> 64; |
| + let carry = ((a_hi * b_lo) as u64 as u128 + (a_lo * b_hi) as u64 as u128 + carry) >> 64; |
| + a_hi * b_hi + ((a_hi * b_lo) >> 64) + ((a_lo * b_hi) >> 64) + carry |
| +} |
| + |
| +macro_rules! rng_integer { |
| + ($t:tt, $unsigned_t:tt, $gen:tt, $mod:tt, $doc:tt) => { |
| + #[doc = $doc] |
| + /// |
| + /// Panics if the range is empty. |
| + #[inline] |
| + pub fn $t(&mut self, range: impl RangeBounds<$t>) -> $t { |
| + let panic_empty_range = || { |
| + panic!( |
| + "empty range: {:?}..{:?}", |
| + range.start_bound(), |
| + range.end_bound() |
| + ) |
| + }; |
| + |
| + let low = match range.start_bound() { |
| + Bound::Unbounded => $t::MIN, |
| + Bound::Included(&x) => x, |
| + Bound::Excluded(&x) => x.checked_add(1).unwrap_or_else(panic_empty_range), |
| + }; |
| + |
| + let high = match range.end_bound() { |
| + Bound::Unbounded => $t::MAX, |
| + Bound::Included(&x) => x, |
| + Bound::Excluded(&x) => x.checked_sub(1).unwrap_or_else(panic_empty_range), |
| + }; |
| + |
| + if low > high { |
| + panic_empty_range(); |
| + } |
| + |
| + if low == $t::MIN && high == $t::MAX { |
| + self.$gen() as $t |
| + } else { |
| + let len = high.wrapping_sub(low).wrapping_add(1); |
| + low.wrapping_add(self.$mod(len as $unsigned_t as _) as $t) |
| + } |
| + } |
| + }; |
| +} |
| + |
| +impl Rng { |
| + /// Creates a new random number generator with the initial seed. |
| + #[inline] |
| + #[must_use = "this creates a new instance of `Rng`; if you want to initialize the thread-local generator, use `fastrand::seed()` instead"] |
| + pub const fn with_seed(seed: u64) -> Self { |
| + Rng(seed) |
| + } |
| + |
| + /// Clones the generator by deterministically deriving a new generator based on the initial |
| + /// seed. |
| + /// |
| + /// This function can be used to create a new generator that is a "spinoff" of the old |
| + /// generator. The new generator will not produce the same sequence of values as the |
| + /// old generator. |
| + /// |
| + /// # Example |
| + /// |
| + /// ``` |
| + /// // Seed two generators equally, and clone both of them. |
| + /// let mut base1 = fastrand::Rng::with_seed(0x4d595df4d0f33173); |
| + /// base1.bool(); // Use the generator once. |
| + /// |
| + /// let mut base2 = fastrand::Rng::with_seed(0x4d595df4d0f33173); |
| + /// base2.bool(); // Use the generator once. |
| + /// |
| + /// let mut rng1 = base1.fork(); |
| + /// let mut rng2 = base2.fork(); |
| + /// |
| + /// println!("rng1 returns {}", rng1.u32(..)); |
| + /// println!("rng2 returns {}", rng2.u32(..)); |
| + /// ``` |
| + #[inline] |
| + #[must_use = "this creates a new instance of `Rng`"] |
| + pub fn fork(&mut self) -> Self { |
| + Rng::with_seed(self.gen_u64()) |
| + } |
| + |
| + /// Generates a random `char` in range a-z and A-Z. |
| + #[inline] |
| + pub fn alphabetic(&mut self) -> char { |
| + const CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; |
| + *self.choice(CHARS).unwrap() as char |
| + } |
| + |
| + /// Generates a random `char` in range a-z, A-Z and 0-9. |
| + #[inline] |
| + pub fn alphanumeric(&mut self) -> char { |
| + const CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; |
| + *self.choice(CHARS).unwrap() as char |
| + } |
| + |
| + /// Generates a random `bool`. |
| + #[inline] |
| + pub fn bool(&mut self) -> bool { |
| + self.u8(..) % 2 == 0 |
| + } |
| + |
| + /// Generates a random digit in the given `base`. |
| + /// |
| + /// Digits are represented by `char`s in range 0-9 and a-z. |
| + /// |
| + /// Panics if the base is zero or greater than 36. |
| + #[inline] |
| + pub fn digit(&mut self, base: u32) -> char { |
| + if base == 0 { |
| + panic!("base cannot be zero"); |
| + } |
| + if base > 36 { |
| + panic!("base cannot be larger than 36"); |
| + } |
| + let num = self.u8(..base as u8); |
| + if num < 10 { |
| + (b'0' + num) as char |
| + } else { |
| + (b'a' + num - 10) as char |
| + } |
| + } |
| + |
| + /// Generates a random `f32` in range `0..=1`. |
| + #[inline] |
| + pub fn f32_inclusive(&mut self) -> f32 { |
| + // Generate a number in 0..2^63 then convert to f32 and multiply by 2^(-63). |
| + // |
| + // Even though we're returning f32, we still generate u64 internally to make |
| + // it possible to return nonzero numbers as small as 2^(-63). If we only |
| + // generated u32 internally, the smallest nonzero number we could return |
| + // would be 2^(-32). |
| + // |
| + // The integer we generate is in 0..2^63 rather than 0..2^64 to improve speed |
| + // on x86-64, which has efficient i64->float conversion (cvtsi2ss) but for |
| + // which u64->float conversion must be implemented in software. |
| + // |
| + // There is still some remaining bias in the int-to-float conversion, because |
| + // nonzero numbers <=2^(-64) are never generated, even though they are |
| + // expressible in f32. However, at this point the bias in int-to-float conversion |
| + // is no larger than the bias in the underlying WyRand generator: since it only |
| + // has a 64-bit state, it necessarily already have biases of at least 2^(-64) |
| + // probability. |
| + // |
| + // See e.g. Section 3.1 of Thomas, David B., et al. "Gaussian random number generators, |
| + // https://www.doc.ic.ac.uk/~wl/papers/07/csur07dt.pdf, for background. |
| + const MUL: f32 = 1.0 / (1u64 << 63) as f32; |
| + (self.gen_u64() >> 1) as f32 * MUL |
| + } |
| + |
| + /// Generates a random `f32` in range `0..1`. |
| + /// |
| + /// Function `f32_inclusive()` is a little simpler and faster, so default |
| + /// to that if inclusive range is acceptable. |
| + #[inline] |
| + pub fn f32(&mut self) -> f32 { |
| + loop { |
| + let x = self.f32_inclusive(); |
| + if x < 1.0 { |
| + return x; |
| + } |
| + } |
| + } |
| + |
| + /// Generates a random `f64` in range `0..=1`. |
| + #[inline] |
| + pub fn f64_inclusive(&mut self) -> f64 { |
| + // See the comment in f32_inclusive() for more details. |
| + const MUL: f64 = 1.0 / (1u64 << 63) as f64; |
| + (self.gen_u64() >> 1) as f64 * MUL |
| + } |
| + |
| + /// Generates a random `f64` in range `0..1`. |
| + /// |
| + /// Function `f64_inclusive()` is a little simpler and faster, so default |
| + /// to that if inclusive range is acceptable. |
| + #[inline] |
| + pub fn f64(&mut self) -> f64 { |
| + loop { |
| + let x = self.f64_inclusive(); |
| + if x < 1.0 { |
| + return x; |
| + } |
| + } |
| + } |
| + |
| + /// Collects `amount` values at random from the iterable into a vector. |
| + /// |
| + /// The length of the returned vector equals `amount` unless the iterable |
| + /// contains insufficient elements, in which case it equals the number of |
| + /// elements available. |
| + /// |
| + /// Complexity is `O(n)` where `n` is the length of the iterable. |
| + #[cfg(feature = "alloc")] |
| + pub fn choose_multiple<I: IntoIterator>(&mut self, source: I, amount: usize) -> Vec<I::Item> { |
| + // Adapted from: https://docs.rs/rand/latest/rand/seq/trait.IteratorRandom.html#method.choose_multiple |
| + let mut reservoir = Vec::with_capacity(amount); |
| + let mut iter = source.into_iter(); |
| + |
| + reservoir.extend(iter.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 iter.enumerate() { |
| + let end = i + 1 + amount; |
| + let k = self.usize(0..end); |
| + if let Some(slot) = reservoir.get_mut(k) { |
| + *slot = elem; |
| + } |
| + } |
| + } else { |
| + // If less than one third of the `Vec` was used, reallocate |
| + // so that the unused space is not wasted. There is a corner |
| + // case where `amount` was much less than `self.len()`. |
| + if reservoir.capacity() > 3 * reservoir.len() { |
| + reservoir.shrink_to_fit(); |
| + } |
| + } |
| + reservoir |
| + } |
| + |
| + rng_integer!( |
| + i8, |
| + u8, |
| + gen_u32, |
| + gen_mod_u32, |
| + "Generates a random `i8` in the given range." |
| + ); |
| + |
| + rng_integer!( |
| + i16, |
| + u16, |
| + gen_u32, |
| + gen_mod_u32, |
| + "Generates a random `i16` in the given range." |
| + ); |
| + |
| + rng_integer!( |
| + i32, |
| + u32, |
| + gen_u32, |
| + gen_mod_u32, |
| + "Generates a random `i32` in the given range." |
| + ); |
| + |
| + rng_integer!( |
| + i64, |
| + u64, |
| + gen_u64, |
| + gen_mod_u64, |
| + "Generates a random `i64` in the given range." |
| + ); |
| + |
| + rng_integer!( |
| + i128, |
| + u128, |
| + gen_u128, |
| + gen_mod_u128, |
| + "Generates a random `i128` in the given range." |
| + ); |
| + |
| + #[cfg(target_pointer_width = "16")] |
| + rng_integer!( |
| + isize, |
| + usize, |
| + gen_u32, |
| + gen_mod_u32, |
| + "Generates a random `isize` in the given range." |
| + ); |
| + #[cfg(target_pointer_width = "32")] |
| + rng_integer!( |
| + isize, |
| + usize, |
| + gen_u32, |
| + gen_mod_u32, |
| + "Generates a random `isize` in the given range." |
| + ); |
| + #[cfg(target_pointer_width = "64")] |
| + rng_integer!( |
| + isize, |
| + usize, |
| + gen_u64, |
| + gen_mod_u64, |
| + "Generates a random `isize` in the given range." |
| + ); |
| + |
| + /// Generates a random `char` in range a-z. |
| + #[inline] |
| + pub fn lowercase(&mut self) -> char { |
| + const CHARS: &[u8] = b"abcdefghijklmnopqrstuvwxyz"; |
| + *self.choice(CHARS).unwrap() as char |
| + } |
| + |
| + /// Initializes this generator with the given seed. |
| + #[inline] |
| + pub fn seed(&mut self, seed: u64) { |
| + self.0 = seed; |
| + } |
| + |
| + /// Gives back **current** seed that is being held by this generator. |
| + #[inline] |
| + pub fn get_seed(&self) -> u64 { |
| + self.0 |
| + } |
| + |
| + /// Choose an item from an iterator at random. |
| + /// |
| + /// This function may have an unexpected result if the `len()` property of the |
| + /// iterator does not match the actual number of items in the iterator. If |
| + /// the iterator is empty, this returns `None`. |
| + #[inline] |
| + pub fn choice<I>(&mut self, iter: I) -> Option<I::Item> |
| + where |
| + I: IntoIterator, |
| + I::IntoIter: ExactSizeIterator, |
| + { |
| + let mut iter = iter.into_iter(); |
| + |
| + // Get the item at a random index. |
| + let len = iter.len(); |
| + if len == 0 { |
| + return None; |
| + } |
| + let index = self.usize(0..len); |
| + |
| + iter.nth(index) |
| + } |
| + |
| + /// Shuffles a slice randomly. |
| + #[inline] |
| + pub fn shuffle<T>(&mut self, slice: &mut [T]) { |
| + for i in 1..slice.len() { |
| + slice.swap(i, self.usize(..=i)); |
| + } |
| + } |
| + |
| + /// Fill a byte slice with random data. |
| + #[inline] |
| + pub fn fill(&mut self, slice: &mut [u8]) { |
| + // We fill the slice by chunks of 8 bytes, or one block of |
| + // WyRand output per new state. |
| + let mut chunks = slice.chunks_exact_mut(core::mem::size_of::<u64>()); |
| + for chunk in chunks.by_ref() { |
| + let n = self.gen_u64().to_ne_bytes(); |
| + // Safe because the chunks are always 8 bytes exactly. |
| + chunk.copy_from_slice(&n); |
| + } |
| + |
| + let remainder = chunks.into_remainder(); |
| + |
| + // Any remainder will always be less than 8 bytes. |
| + if !remainder.is_empty() { |
| + // Generate one last block of 8 bytes of entropy |
| + let n = self.gen_u64().to_ne_bytes(); |
| + |
| + // Use the remaining length to copy from block |
| + remainder.copy_from_slice(&n[..remainder.len()]); |
| + } |
| + } |
| + |
| + rng_integer!( |
| + u8, |
| + u8, |
| + gen_u32, |
| + gen_mod_u32, |
| + "Generates a random `u8` in the given range." |
| + ); |
| + |
| + rng_integer!( |
| + u16, |
| + u16, |
| + gen_u32, |
| + gen_mod_u32, |
| + "Generates a random `u16` in the given range." |
| + ); |
| + |
| + rng_integer!( |
| + u32, |
| + u32, |
| + gen_u32, |
| + gen_mod_u32, |
| + "Generates a random `u32` in the given range." |
| + ); |
| + |
| + rng_integer!( |
| + u64, |
| + u64, |
| + gen_u64, |
| + gen_mod_u64, |
| + "Generates a random `u64` in the given range." |
| + ); |
| + |
| + rng_integer!( |
| + u128, |
| + u128, |
| + gen_u128, |
| + gen_mod_u128, |
| + "Generates a random `u128` in the given range." |
| + ); |
| + |
| + #[cfg(target_pointer_width = "16")] |
| + rng_integer!( |
| + usize, |
| + usize, |
| + gen_u32, |
| + gen_mod_u32, |
| + "Generates a random `usize` in the given range." |
| + ); |
| + #[cfg(target_pointer_width = "32")] |
| + rng_integer!( |
| + usize, |
| + usize, |
| + gen_u32, |
| + gen_mod_u32, |
| + "Generates a random `usize` in the given range." |
| + ); |
| + #[cfg(target_pointer_width = "64")] |
| + rng_integer!( |
| + usize, |
| + usize, |
| + gen_u64, |
| + gen_mod_u64, |
| + "Generates a random `usize` in the given range." |
| + ); |
| + |
| + /// Generates a random `char` in range A-Z. |
| + #[inline] |
| + pub fn uppercase(&mut self) -> char { |
| + const CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ"; |
| + *self.choice(CHARS).unwrap() as char |
| + } |
| + |
| + /// Generates a random `char` in the given range. |
| + /// |
| + /// Panics if the range is empty. |
| + #[inline] |
| + pub fn char(&mut self, range: impl RangeBounds<char>) -> char { |
| + let panic_empty_range = || { |
| + panic!( |
| + "empty range: {:?}..{:?}", |
| + range.start_bound(), |
| + range.end_bound() |
| + ) |
| + }; |
| + |
| + let surrogate_start = 0xd800u32; |
| + let surrogate_len = 0x800u32; |
| + |
| + let low = match range.start_bound() { |
| + Bound::Unbounded => 0u8 as char, |
| + Bound::Included(&x) => x, |
| + Bound::Excluded(&x) => { |
| + let scalar = if x as u32 == surrogate_start - 1 { |
| + surrogate_start + surrogate_len |
| + } else { |
| + x as u32 + 1 |
| + }; |
| + char::try_from(scalar).unwrap_or_else(|_| panic_empty_range()) |
| + } |
| + }; |
| + |
| + let high = match range.end_bound() { |
| + Bound::Unbounded => core::char::MAX, |
| + Bound::Included(&x) => x, |
| + Bound::Excluded(&x) => { |
| + let scalar = if x as u32 == surrogate_start + surrogate_len { |
| + surrogate_start - 1 |
| + } else { |
| + (x as u32).wrapping_sub(1) |
| + }; |
| + char::try_from(scalar).unwrap_or_else(|_| panic_empty_range()) |
| + } |
| + }; |
| + |
| + if low > high { |
| + panic_empty_range(); |
| + } |
| + |
| + let gap = if (low as u32) < surrogate_start && (high as u32) >= surrogate_start { |
| + surrogate_len |
| + } else { |
| + 0 |
| + }; |
| + let range = high as u32 - low as u32 - gap; |
| + let mut val = self.u32(0..=range) + low as u32; |
| + if val >= surrogate_start { |
| + val += gap; |
| + } |
| + val.try_into().unwrap() |
| + } |
| +} |
diff --git a/vendor/fastrand-2.5.0/tests/char.rs b/vendor/fastrand-2.5.0/tests/char.rs| new file mode 100644 |
| index 0000000..0f48c57 |
| --- /dev/null |
| +++ b/vendor/fastrand-2.5.0/tests/char.rs |
| @@ -0,0 +1,44 @@ |
| +use std::convert::TryFrom; |
| +use std::ops::RangeBounds; |
| + |
| +fn test_char_coverage<R>(n: usize, range: R) |
| +where |
| + R: Iterator<Item = char> + RangeBounds<char> + Clone, |
| +{ |
| + use std::collections::HashSet; |
| + |
| + let all: HashSet<char> = range.clone().collect(); |
| + let mut covered = HashSet::new(); |
| + for _ in 0..n { |
| + let c = fastrand::char(range.clone()); |
| + assert!(all.contains(&c)); |
| + covered.insert(c); |
| + } |
| + assert_eq!(covered, all); |
| +} |
| + |
| +#[test] |
| +fn test_char() { |
| + // ASCII control chars. |
| + let nul = 0u8 as char; |
| + let soh = 1u8 as char; |
| + let stx = 2u8 as char; |
| + // Some undefined Hangul Jamo codepoints just before |
| + // the surrogate area. |
| + let last_jamo = char::try_from(0xd7ffu32).unwrap(); |
| + let penultimate_jamo = char::try_from(last_jamo as u32 - 1).unwrap(); |
| + // Private-use codepoints just after the surrogate area. |
| + let first_private = char::try_from(0xe000u32).unwrap(); |
| + let second_private = char::try_from(first_private as u32 + 1).unwrap(); |
| + // Private-use codepoints at the end of Unicode space. |
| + let last_private = std::char::MAX; |
| + let penultimate_private = char::try_from(last_private as u32 - 1).unwrap(); |
| + |
| + test_char_coverage(100, nul..stx); |
| + test_char_coverage(100, nul..=soh); |
| + |
| + test_char_coverage(400, penultimate_jamo..second_private); |
| + test_char_coverage(400, penultimate_jamo..=second_private); |
| + |
| + test_char_coverage(100, penultimate_private..=last_private); |
| +} |
diff --git a/vendor/fastrand-2.5.0/tests/smoke.rs b/vendor/fastrand-2.5.0/tests/smoke.rs| new file mode 100644 |
| index 0000000..ea200b9 |
| --- /dev/null |
| +++ b/vendor/fastrand-2.5.0/tests/smoke.rs |
| @@ -0,0 +1,357 @@ |
| +#[cfg(all(target_family = "wasm", not(target_os = "wasi")))] |
| +use wasm_bindgen_test::wasm_bindgen_test as test; |
| + |
| +#[cfg(all(target_family = "wasm", not(target_os = "wasi")))] |
| +wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser); |
| + |
| +#[test] |
| +fn bool() { |
| + for x in &[false, true] { |
| + while fastrand::bool() != *x {} |
| + } |
| +} |
| + |
| +#[test] |
| +fn u8() { |
| + for x in 0..10 { |
| + while fastrand::u8(..10) != x {} |
| + } |
| + |
| + for x in 200..=u8::MAX { |
| + while fastrand::u8(200..) != x {} |
| + } |
| +} |
| + |
| +#[test] |
| +fn i8() { |
| + for x in -128..-120 { |
| + while fastrand::i8(..-120) != x {} |
| + } |
| + |
| + for x in 120..=127 { |
| + while fastrand::i8(120..) != x {} |
| + } |
| +} |
| + |
| +#[test] |
| +fn u32() { |
| + for n in 1u32..10_000 { |
| + let n = n.wrapping_mul(n); |
| + let n = n.wrapping_mul(n); |
| + if n != 0 { |
| + for _ in 0..1000 { |
| + assert!(fastrand::u32(..n) < n); |
| + } |
| + } |
| + } |
| +} |
| + |
| +#[test] |
| +fn u64() { |
| + for n in 1u64..10_000 { |
| + let n = n.wrapping_mul(n); |
| + let n = n.wrapping_mul(n); |
| + let n = n.wrapping_mul(n); |
| + if n != 0 { |
| + for _ in 0..1000 { |
| + assert!(fastrand::u64(..n) < n); |
| + } |
| + } |
| + } |
| +} |
| + |
| +#[test] |
| +fn u128() { |
| + for n in 1u128..10_000 { |
| + let n = n.wrapping_mul(n); |
| + let n = n.wrapping_mul(n); |
| + let n = n.wrapping_mul(n); |
| + let n = n.wrapping_mul(n); |
| + if n != 0 { |
| + for _ in 0..1000 { |
| + assert!(fastrand::u128(..n) < n); |
| + } |
| + } |
| + } |
| +} |
| + |
| +#[test] |
| +fn f32() { |
| + let mut r = fastrand::Rng::with_seed(0); |
| + let tiny = (-24.0f32).exp2(); |
| + let mut count_tiny_nonzero = 0; |
| + let mut count_top_half = 0; |
| + for _ in 0..100_000_000 { |
| + let x = r.f32(); |
| + assert!((0.0..1.0).contains(&x)); |
| + if x > 0.0 && x < tiny { |
| + count_tiny_nonzero += 1; |
| + } else if x > 0.5 { |
| + count_top_half += 1; |
| + } |
| + } |
| + assert!(count_top_half >= 49_000_000); |
| + assert!(count_tiny_nonzero > 0); |
| +} |
| + |
| +#[test] |
| +fn f32_inclusive() { |
| + let mut r = fastrand::Rng::with_seed(0); |
| + let tiny = (-24.0f32).exp2(); |
| + let mut count_top_half = 0; |
| + let mut count_tiny_nonzero = 0; |
| + let mut count_one = 0; |
| + for _ in 0..100_000_000 { |
| + let x = r.f32_inclusive(); |
| + assert!((0.0..=1.0).contains(&x)); |
| + if x == 1.0 { |
| + count_one += 1; |
| + } else if x > 0.5 { |
| + count_top_half += 1; |
| + } else if x > 0.0 && x < tiny { |
| + count_tiny_nonzero += 1; |
| + } |
| + } |
| + assert!(count_top_half >= 49_000_000); |
| + assert!(count_one > 0); |
| + assert!(count_tiny_nonzero > 0); |
| +} |
| + |
| +#[test] |
| +fn f64() { |
| + let mut r = fastrand::Rng::with_seed(0); |
| + let mut count_top_half = 0; |
| + for _ in 0..100_000_000 { |
| + let x = r.f64(); |
| + assert!((0.0..1.0).contains(&x)); |
| + if x > 0.5 { |
| + count_top_half += 1; |
| + } |
| + } |
| + assert!(count_top_half >= 49_000_000); |
| +} |
| + |
| +#[test] |
| +fn f64_inclusive() { |
| + let mut r = fastrand::Rng::with_seed(0); |
| + let mut count_top_half = 0; |
| + for _ in 0..100_000_000 { |
| + let x = r.f64_inclusive(); |
| + assert!((0.0..=1.0).contains(&x)); |
| + if x > 0.5 { |
| + count_top_half += 1; |
| + } |
| + } |
| + assert!(count_top_half >= 49_000_000); |
| +} |
| + |
| +#[test] |
| +fn digit() { |
| + for base in 1..36 { |
| + let result = fastrand::digit(base); |
| + assert!(result.is_ascii_digit() || result.is_ascii_lowercase()); |
| + } |
| +} |
| + |
| +#[test] |
| +fn global_rng_choice() { |
| + let items = [1, 4, 9, 5, 2, 3, 6, 7, 8, 0]; |
| + |
| + for item in &items { |
| + while fastrand::choice(&items).unwrap() != item {} |
| + } |
| +} |
| + |
| +#[test] |
| +fn global_rng_alphabetic() { |
| + for _ in 0..1000 { |
| + let result = fastrand::alphabetic(); |
| + assert!(result.is_ascii_alphabetic()) |
| + } |
| +} |
| + |
| +#[test] |
| +fn global_rng_lowercase() { |
| + for _ in 0..1000 { |
| + let result = fastrand::lowercase(); |
| + assert!(result.is_ascii_lowercase()) |
| + } |
| +} |
| + |
| +#[test] |
| +fn global_rng_uppercase() { |
| + for _ in 0..1000 { |
| + let result = fastrand::uppercase(); |
| + assert!(result.is_ascii_uppercase()) |
| + } |
| +} |
| + |
| +#[test] |
| +fn fill() { |
| + let mut r = fastrand::Rng::new(); |
| + let mut a = [0u8; 64]; |
| + let mut b = [0u8; 64]; |
| + |
| + r.fill(&mut a); |
| + r.fill(&mut b); |
| + |
| + assert_ne!(a, b); |
| + |
| + let mut a = [0u8; 9]; |
| + let mut b = [0u8; 9]; |
| + |
| + r.fill(&mut a); |
| + r.fill(&mut b); |
| + |
| + assert_ne!(a, b); |
| +} |
| + |
| +#[test] |
| +fn global_rng_fill() { |
| + let mut a = [0u8; 64]; |
| + let mut b = [0u8; 64]; |
| + |
| + fastrand::fill(&mut a); |
| + fastrand::fill(&mut b); |
| + |
| + assert_ne!(a, b); |
| +} |
| + |
| +#[test] |
| +fn rng() { |
| + let mut r = fastrand::Rng::new(); |
| + |
| + assert_ne!(r.u64(..), r.u64(..)); |
| + |
| + r.seed(7); |
| + let a = r.u64(..); |
| + r.seed(7); |
| + let b = r.u64(..); |
| + assert_eq!(a, b); |
| +} |
| + |
| +#[test] |
| +fn rng_init() { |
| + let mut a = fastrand::Rng::new(); |
| + let mut b = fastrand::Rng::new(); |
| + assert_ne!(a.u64(..), b.u64(..)); |
| + |
| + a.seed(7); |
| + b.seed(7); |
| + assert_eq!(a.u64(..), b.u64(..)); |
| +} |
| + |
| +#[test] |
| +fn rng_digit() { |
| + let mut rng = fastrand::Rng::new(); |
| + for base in 1..36 { |
| + let result = rng.digit(base); |
| + assert!(result.is_ascii_digit() || result.is_ascii_lowercase()); |
| + } |
| +} |
| + |
| +#[test] |
| +#[should_panic] |
| +fn rng_digit_panic_1() { |
| + let mut rng = fastrand::Rng::new(); |
| + let _result = rng.digit(0); |
| +} |
| + |
| +#[test] |
| +#[should_panic] |
| +fn rng_digit_panic_2() { |
| + let mut rng = fastrand::Rng::new(); |
| + let base = rng.u32(37..); |
| + let _result = rng.digit(base); |
| +} |
| + |
| +#[test] |
| +fn with_seed() { |
| + let mut a = fastrand::Rng::with_seed(7); |
| + let mut b = fastrand::Rng::new(); |
| + b.seed(7); |
| + assert_eq!(a.u64(..), b.u64(..)); |
| +} |
| + |
| +#[test] |
| +fn choose_multiple() { |
| + let mut a = fastrand::Rng::new(); |
| + let mut elements = (0..20).collect::<Vec<_>>(); |
| + |
| + while !elements.is_empty() { |
| + let chosen = a.choose_multiple(0..20, 5); |
| + for &x in &chosen { |
| + elements.retain(|&y| y != x); |
| + } |
| + } |
| + |
| + let empty_elements: Vec<i32> = Vec::new(); |
| + let empty_result = a.choose_multiple(empty_elements, 5); |
| + assert!(empty_result.is_empty()); |
| +} |
| + |
| +#[test] |
| +fn choice() { |
| + let items = [1, 4, 9, 5, 2, 3, 6, 7, 8, 0]; |
| + let mut r = fastrand::Rng::new(); |
| + |
| + for item in &items { |
| + while r.choice(&items).unwrap() != item {} |
| + } |
| +} |
| + |
| +#[test] |
| +fn choice_empty() { |
| + let mut rng = fastrand::Rng::new(); |
| + let data: Vec<i32> = Vec::new(); |
| + let result = rng.choice(data); |
| + assert!(result.is_none()); |
| +} |
| + |
| +#[test] |
| +fn lowercase() { |
| + let mut rng = fastrand::Rng::new(); |
| + for _ in 0..1000 { |
| + let result = rng.lowercase(); |
| + assert!(result.is_ascii_lowercase()) |
| + } |
| +} |
| + |
| +#[test] |
| +fn alphabetic() { |
| + let mut rng = fastrand::Rng::new(); |
| + for _ in 0..1000 { |
| + let result = rng.alphabetic(); |
| + assert!(result.is_ascii_alphabetic()) |
| + } |
| +} |
| + |
| +#[test] |
| +fn uppercase() { |
| + let mut rng = fastrand::Rng::new(); |
| + for _ in 0..1000 { |
| + let result = rng.uppercase(); |
| + assert!(result.is_ascii_uppercase()) |
| + } |
| +} |
| + |
| +#[test] |
| +#[should_panic] |
| +fn char_panic() { |
| + let mut rng = fastrand::Rng::new(); |
| + let _result = rng.char('z'..='a'); |
| +} |
| + |
| +#[test] |
| +fn char() { |
| + use core::ops::Bound; |
| + let mut rng = fastrand::Rng::new(); |
| + |
| + let result = rng.char(..); |
| + assert!(result >= 0 as char && result <= core::char::MAX); |
| + |
| + let result = rng.char((Bound::Excluded('0'), Bound::Excluded('9'))); |
| + for _ in 0..1000 { |
| + assert!(result > '0' && result < '9'); |
| + } |
| +} |