diff --git a/.lock b/.lock new file mode 100644 index 000000000..e69de29bb diff --git a/.nojekyll b/.nojekyll new file mode 100644 index 000000000..e69de29bb diff --git a/crates.js b/crates.js new file mode 100644 index 000000000..013cf0e38 --- /dev/null +++ b/crates.js @@ -0,0 +1,2 @@ +window.ALL_CRATES = ["rand_core","rand_mt"]; +//{"start":21,"fragment_lengths":[11,10]} \ No newline at end of file diff --git a/help.html b/help.html new file mode 100644 index 000000000..48e5cd1fa --- /dev/null +++ b/help.html @@ -0,0 +1 @@ +Help

Rustdoc help

Back
\ No newline at end of file diff --git a/rand_core/all.html b/rand_core/all.html new file mode 100644 index 000000000..a5f9a2852 --- /dev/null +++ b/rand_core/all.html @@ -0,0 +1 @@ +List of all items in this crate

List of all items

Structs

Traits

Functions

\ No newline at end of file diff --git a/rand_core/block/index.html b/rand_core/block/index.html new file mode 100644 index 000000000..fe44f5a7b --- /dev/null +++ b/rand_core/block/index.html @@ -0,0 +1,44 @@ +rand_core::block - Rust
rand_core

Module block

source
Expand description

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 crate) perform periodic +reseeding with very low overhead.

+

§Example

+
use rand_core::{RngCore, SeedableRng};
+use rand_core::block::{BlockRngCore, BlockRng};
+
+struct MyRngCore;
+
+impl BlockRngCore for MyRngCore {
+    type Item = u32;
+    type Results = [u32; 16];
+
+    fn generate(&mut self, results: &mut Self::Results) {
+        unimplemented!()
+    }
+}
+
+impl SeedableRng for MyRngCore {
+    type Seed = [u8; 32];
+    fn from_seed(seed: Self::Seed) -> Self {
+        unimplemented!()
+    }
+}
+
+// optionally, also implement CryptoRng for MyRngCore
+
+// Final RNG.
+let mut rng = BlockRng::<MyRngCore>::seed_from_u64(0);
+println!("First value: {}", rng.next_u32());
+

Structs§

  • 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.
  • 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.

Traits§

  • 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.
\ No newline at end of file diff --git a/rand_core/block/sidebar-items.js b/rand_core/block/sidebar-items.js new file mode 100644 index 000000000..420685d09 --- /dev/null +++ b/rand_core/block/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"struct":["BlockRng","BlockRng64"],"trait":["BlockRngCore"]}; \ No newline at end of file diff --git a/rand_core/block/struct.BlockRng.html b/rand_core/block/struct.BlockRng.html new file mode 100644 index 000000000..524cf8a3d --- /dev/null +++ b/rand_core/block/struct.BlockRng.html @@ -0,0 +1,67 @@ +BlockRng in rand_core::block - Rust
rand_core::block

Struct BlockRng

source
pub struct BlockRng<R: BlockRngCore + ?Sized> {
+    pub core: R,
+    /* private fields */
+}
Expand description

A wrapper type implementing RngCore for some type implementing +BlockRngCore with u32 array buffer; i.e. this can be used to implement +a full RNG from just a generate function.

+

The core field may be accessed directly but the results buffer may not. +PRNG implementations can simply use a type alias +(pub type MyRng = BlockRng<MyRngCore>;) but might prefer to use a +wrapper type (pub struct MyRng(BlockRng<MyRngCore>);); the latter must +re-implement RngCore but hides the implementation details and allows +extra functionality to be defined on the RNG +(e.g. impl MyRng { fn set_stream(...){...} }).

+

BlockRng has heavily optimized implementations of the RngCore methods +reading values from the results buffer, as well as +calling BlockRngCore::generate directly on the output array when +fill_bytes / try_fill_bytes is called on a large array. These methods +also handle the bookkeeping of when to generate a new batch of values.

+

No whole generated u32 values are thrown away and all values are consumed +in-order. next_u32 simply takes the next available u32 value. +next_u64 is implemented by combining two u32 values, least +significant first. fill_bytes and try_fill_bytes consume a whole +number of u32 values, converting each u32 to a byte slice in +little-endian order. If the requested byte length is not a multiple of 4, +some bytes will be discarded.

+

See also BlockRng64 which uses u64 array buffers. Currently there is +no direct support for other buffer types.

+

For easy initialization BlockRng also implements SeedableRng.

+

Fields§

§core: R

The core part of the RNG, implementing the generate function.

+

Implementations§

source§

impl<R: BlockRngCore> BlockRng<R>

source

pub fn new(core: R) -> BlockRng<R>

Create a new BlockRng from an existing RNG implementing +BlockRngCore. Results will be generated on first use.

+
source

pub fn index(&self) -> usize

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.

+
source

pub fn reset(&mut self)

Reset the number of available results. +This will force a new set of results to be generated on next use.

+
source

pub fn generate_and_set(&mut self, index: usize)

Generate a new set of results immediately, setting the index to the +given value.

+

Trait Implementations§

source§

impl<R: Clone + BlockRngCore + ?Sized> Clone for BlockRng<R>
where + R::Results: Clone,

source§

fn clone(&self) -> BlockRng<R>

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<R: BlockRngCore + Debug> Debug for BlockRng<R>

source§

fn fmt(&self, fmt: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<R: BlockRngCore<Item = u32>> RngCore for BlockRng<R>
where + <R as BlockRngCore>::Results: AsRef<[u32]> + AsMut<[u32]>,

source§

fn next_u32(&mut self) -> u32

Return the next random u32. Read more
source§

fn next_u64(&mut self) -> u64

Return the next random u64. Read more
source§

fn fill_bytes(&mut self, dest: &mut [u8])

Fill dest with random data. Read more
source§

fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error>

Fill dest entirely with random data. Read more
source§

impl<R: BlockRngCore + SeedableRng> SeedableRng for BlockRng<R>

source§

type Seed = <R as SeedableRng>::Seed

Seed type, which is restricted to types mutably-dereferenceable as u8 +arrays (we recommend [u8; N] for some N). Read more
source§

fn from_seed(seed: Self::Seed) -> Self

Create a new PRNG using the given seed. Read more
source§

fn seed_from_u64(seed: u64) -> Self

Create a new PRNG using a u64 seed. Read more
source§

fn from_rng<S: RngCore>(rng: S) -> Result<Self, Error>

Create a new PRNG seeded from another Rng. Read more
source§

impl<R: BlockRngCore + CryptoRng> CryptoRng for BlockRng<R>

Auto Trait Implementations§

§

impl<R> Freeze for BlockRng<R>
where + <R as BlockRngCore>::Results: Freeze, + R: Freeze + ?Sized,

§

impl<R> RefUnwindSafe for BlockRng<R>

§

impl<R> Send for BlockRng<R>
where + <R as BlockRngCore>::Results: Send, + R: Send + ?Sized,

§

impl<R> Sync for BlockRng<R>
where + <R as BlockRngCore>::Results: Sync, + R: Sync + ?Sized,

§

impl<R> Unpin for BlockRng<R>
where + <R as BlockRngCore>::Results: Unpin, + R: Unpin + ?Sized,

§

impl<R> UnwindSafe for BlockRng<R>
where + <R as BlockRngCore>::Results: UnwindSafe, + R: UnwindSafe + ?Sized,

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> CloneToUninit for T
where + T: Clone,

source§

unsafe fn clone_to_uninit(&self, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
source§

impl<T> CryptoRngCore for T
where + T: CryptoRng + RngCore,

source§

fn as_rngcore(&mut self) -> &mut dyn RngCore

Upcast to an RngCore trait object.
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

source§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/rand_core/block/struct.BlockRng64.html b/rand_core/block/struct.BlockRng64.html new file mode 100644 index 000000000..c62573aef --- /dev/null +++ b/rand_core/block/struct.BlockRng64.html @@ -0,0 +1,55 @@ +BlockRng64 in rand_core::block - Rust
rand_core::block

Struct BlockRng64

source
pub struct BlockRng64<R: BlockRngCore + ?Sized> {
+    pub core: R,
+    /* private fields */
+}
Expand description

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 u64s 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.

+

Fields§

§core: R

The core part of the RNG, implementing the generate function.

+

Implementations§

source§

impl<R: BlockRngCore> BlockRng64<R>

source

pub fn new(core: R) -> BlockRng64<R>

Create a new BlockRng from an existing RNG implementing +BlockRngCore. Results will be generated on first use.

+
source

pub fn index(&self) -> usize

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.

+
source

pub fn reset(&mut self)

Reset the number of available results. +This will force a new set of results to be generated on next use.

+
source

pub fn generate_and_set(&mut self, index: usize)

Generate a new set of results immediately, setting the index to the +given value.

+

Trait Implementations§

source§

impl<R: Clone + BlockRngCore + ?Sized> Clone for BlockRng64<R>
where + R::Results: Clone,

source§

fn clone(&self) -> BlockRng64<R>

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<R: BlockRngCore + Debug> Debug for BlockRng64<R>

source§

fn fmt(&self, fmt: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<R: BlockRngCore<Item = u64>> RngCore for BlockRng64<R>
where + <R as BlockRngCore>::Results: AsRef<[u64]> + AsMut<[u64]>,

source§

fn next_u32(&mut self) -> u32

Return the next random u32. Read more
source§

fn next_u64(&mut self) -> u64

Return the next random u64. Read more
source§

fn fill_bytes(&mut self, dest: &mut [u8])

Fill dest with random data. Read more
source§

fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error>

Fill dest entirely with random data. Read more
source§

impl<R: BlockRngCore + SeedableRng> SeedableRng for BlockRng64<R>

source§

type Seed = <R as SeedableRng>::Seed

Seed type, which is restricted to types mutably-dereferenceable as u8 +arrays (we recommend [u8; N] for some N). Read more
source§

fn from_seed(seed: Self::Seed) -> Self

Create a new PRNG using the given seed. Read more
source§

fn seed_from_u64(seed: u64) -> Self

Create a new PRNG using a u64 seed. Read more
source§

fn from_rng<S: RngCore>(rng: S) -> Result<Self, Error>

Create a new PRNG seeded from another Rng. Read more

Auto Trait Implementations§

§

impl<R> Freeze for BlockRng64<R>
where + <R as BlockRngCore>::Results: Freeze, + R: Freeze + ?Sized,

§

impl<R> RefUnwindSafe for BlockRng64<R>

§

impl<R> Send for BlockRng64<R>
where + <R as BlockRngCore>::Results: Send, + R: Send + ?Sized,

§

impl<R> Sync for BlockRng64<R>
where + <R as BlockRngCore>::Results: Sync, + R: Sync + ?Sized,

§

impl<R> Unpin for BlockRng64<R>
where + <R as BlockRngCore>::Results: Unpin, + R: Unpin + ?Sized,

§

impl<R> UnwindSafe for BlockRng64<R>
where + <R as BlockRngCore>::Results: UnwindSafe, + R: UnwindSafe + ?Sized,

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> CloneToUninit for T
where + T: Clone,

source§

unsafe fn clone_to_uninit(&self, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

source§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/rand_core/block/trait.BlockRngCore.html b/rand_core/block/trait.BlockRngCore.html new file mode 100644 index 000000000..e6af21097 --- /dev/null +++ b/rand_core/block/trait.BlockRngCore.html @@ -0,0 +1,15 @@ +BlockRngCore in rand_core::block - Rust
rand_core::block

Trait BlockRngCore

source
pub trait BlockRngCore {
+    type Item;
+    type Results: AsRef<[Self::Item]> + AsMut<[Self::Item]> + Default;
+
+    // Required method
+    fn generate(&mut self, results: &mut Self::Results);
+}
Expand description

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 documentation for details.

+

Required Associated Types§

source

type Item

Results element type, e.g. u32.

+
source

type Results: AsRef<[Self::Item]> + AsMut<[Self::Item]> + Default

Results type. This is the ‘block’ an RNG implementing BlockRngCore +generates, which will usually be an array like [u32; 16].

+

Required Methods§

source

fn generate(&mut self, results: &mut Self::Results)

Generate a new block of results.

+

Implementors§

\ No newline at end of file diff --git a/rand_core/error/struct.Error.html b/rand_core/error/struct.Error.html new file mode 100644 index 000000000..f6280b71f --- /dev/null +++ b/rand_core/error/struct.Error.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../rand_core/struct.Error.html...

+ + + \ No newline at end of file diff --git a/rand_core/impls/fn.fill_bytes_via_next.html b/rand_core/impls/fn.fill_bytes_via_next.html new file mode 100644 index 000000000..9c4411f27 --- /dev/null +++ b/rand_core/impls/fn.fill_bytes_via_next.html @@ -0,0 +1,6 @@ +fill_bytes_via_next in rand_core::impls - Rust
rand_core::impls

Function fill_bytes_via_next

source
pub fn fill_bytes_via_next<R: RngCore + ?Sized>(rng: &mut R, dest: &mut [u8])
Expand description

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.

+
\ No newline at end of file diff --git a/rand_core/impls/fn.fill_via_u32_chunks.html b/rand_core/impls/fn.fill_via_u32_chunks.html new file mode 100644 index 000000000..02a374c8b --- /dev/null +++ b/rand_core/impls/fn.fill_via_u32_chunks.html @@ -0,0 +1,26 @@ +fill_via_u32_chunks in rand_core::impls - Rust
rand_core::impls

Function fill_via_u32_chunks

source
pub fn fill_via_u32_chunks(src: &[u32], dest: &mut [u8]) -> (usize, usize)
Expand description

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)

+ +
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;
+    }
+}
+
\ No newline at end of file diff --git a/rand_core/impls/fn.fill_via_u64_chunks.html b/rand_core/impls/fn.fill_via_u64_chunks.html new file mode 100644 index 000000000..a5da0d1e3 --- /dev/null +++ b/rand_core/impls/fn.fill_via_u64_chunks.html @@ -0,0 +1,9 @@ +fill_via_u64_chunks in rand_core::impls - Rust
rand_core::impls

Function fill_via_u64_chunks

source
pub fn fill_via_u64_chunks(src: &[u64], dest: &mut [u8]) -> (usize, usize)
Expand description

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.

+
\ No newline at end of file diff --git a/rand_core/impls/fn.next_u32_via_fill.html b/rand_core/impls/fn.next_u32_via_fill.html new file mode 100644 index 000000000..72968b0d9 --- /dev/null +++ b/rand_core/impls/fn.next_u32_via_fill.html @@ -0,0 +1,2 @@ +next_u32_via_fill in rand_core::impls - Rust
rand_core::impls

Function next_u32_via_fill

source
pub fn next_u32_via_fill<R: RngCore + ?Sized>(rng: &mut R) -> u32
Expand description

Implement next_u32 via fill_bytes, little-endian order.

+
\ No newline at end of file diff --git a/rand_core/impls/fn.next_u64_via_fill.html b/rand_core/impls/fn.next_u64_via_fill.html new file mode 100644 index 000000000..d7af4d4b8 --- /dev/null +++ b/rand_core/impls/fn.next_u64_via_fill.html @@ -0,0 +1,2 @@ +next_u64_via_fill in rand_core::impls - Rust
rand_core::impls

Function next_u64_via_fill

source
pub fn next_u64_via_fill<R: RngCore + ?Sized>(rng: &mut R) -> u64
Expand description

Implement next_u64 via fill_bytes, little-endian order.

+
\ No newline at end of file diff --git a/rand_core/impls/fn.next_u64_via_u32.html b/rand_core/impls/fn.next_u64_via_u32.html new file mode 100644 index 000000000..630cfc738 --- /dev/null +++ b/rand_core/impls/fn.next_u64_via_u32.html @@ -0,0 +1,2 @@ +next_u64_via_u32 in rand_core::impls - Rust
rand_core::impls

Function next_u64_via_u32

source
pub fn next_u64_via_u32<R: RngCore + ?Sized>(rng: &mut R) -> u64
Expand description

Implement next_u64 via next_u32, little-endian order.

+
\ No newline at end of file diff --git a/rand_core/impls/index.html b/rand_core/impls/index.html new file mode 100644 index 000000000..ded868bab --- /dev/null +++ b/rand_core/impls/index.html @@ -0,0 +1,11 @@ +rand_core::impls - Rust
rand_core

Module impls

source
Expand description

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.

+

Functions§

\ No newline at end of file diff --git a/rand_core/impls/sidebar-items.js b/rand_core/impls/sidebar-items.js new file mode 100644 index 000000000..467bcb823 --- /dev/null +++ b/rand_core/impls/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"fn":["fill_bytes_via_next","fill_via_u32_chunks","fill_via_u64_chunks","next_u32_via_fill","next_u64_via_fill","next_u64_via_u32"]}; \ No newline at end of file diff --git a/rand_core/index.html b/rand_core/index.html new file mode 100644 index 000000000..584703fbd --- /dev/null +++ b/rand_core/index.html @@ -0,0 +1,15 @@ +rand_core - Rust

Crate rand_core

source
Expand description

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.

+

Modules§

  • The BlockRngCore trait and implementation helpers
  • Helper functions for implementing RngCore functions.
  • Little-Endian utilities

Structs§

  • Error type of random number generators

Traits§

\ No newline at end of file diff --git a/rand_core/le/fn.read_u32_into.html b/rand_core/le/fn.read_u32_into.html new file mode 100644 index 000000000..7d7fc3d62 --- /dev/null +++ b/rand_core/le/fn.read_u32_into.html @@ -0,0 +1,2 @@ +read_u32_into in rand_core::le - Rust
rand_core::le

Function read_u32_into

source
pub fn read_u32_into(src: &[u8], dst: &mut [u32])
Expand description

Reads unsigned 32 bit integers from src into dst.

+
\ No newline at end of file diff --git a/rand_core/le/fn.read_u64_into.html b/rand_core/le/fn.read_u64_into.html new file mode 100644 index 000000000..12bee3b86 --- /dev/null +++ b/rand_core/le/fn.read_u64_into.html @@ -0,0 +1,2 @@ +read_u64_into in rand_core::le - Rust
rand_core::le

Function read_u64_into

source
pub fn read_u64_into(src: &[u8], dst: &mut [u64])
Expand description

Reads unsigned 64 bit integers from src into dst.

+
\ No newline at end of file diff --git a/rand_core/le/index.html b/rand_core/le/index.html new file mode 100644 index 000000000..fea51f549 --- /dev/null +++ b/rand_core/le/index.html @@ -0,0 +1,4 @@ +rand_core::le - Rust
rand_core

Module le

source
Expand description

Little-Endian utilities

+

Little-Endian order has been chosen for internal usage; this makes some +useful functions available.

+

Functions§

\ No newline at end of file diff --git a/rand_core/le/sidebar-items.js b/rand_core/le/sidebar-items.js new file mode 100644 index 000000000..6243b30b9 --- /dev/null +++ b/rand_core/le/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"fn":["read_u32_into","read_u64_into"]}; \ No newline at end of file diff --git a/rand_core/sidebar-items.js b/rand_core/sidebar-items.js new file mode 100644 index 000000000..50189c92b --- /dev/null +++ b/rand_core/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"mod":["block","impls","le"],"struct":["Error"],"trait":["CryptoRng","CryptoRngCore","RngCore","SeedableRng"]}; \ No newline at end of file diff --git a/rand_core/struct.Error.html b/rand_core/struct.Error.html new file mode 100644 index 000000000..007d8c35f --- /dev/null +++ b/rand_core/struct.Error.html @@ -0,0 +1,32 @@ +Error in rand_core - Rust
rand_core

Struct Error

source
pub struct Error { /* private fields */ }
Expand description

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.

+

Implementations§

source§

impl Error

source

pub const CUSTOM_START: u32 = 3_221_225_472u32

Codes at or above this point can be used by users to define their own +custom errors.

+

This has a fixed value of (1 << 31) + (1 << 30) = 0xC000_0000, +therefore the number of values available for custom codes is 1 << 30.

+

This is identical to getrandom::Error::CUSTOM_START.

+
source

pub const INTERNAL_START: u32 = 2_147_483_648u32

Codes below this point represent OS Errors (i.e. positive i32 values). +Codes at or above this point, but below Error::CUSTOM_START are +reserved for use by the rand and getrandom crates.

+

This is identical to getrandom::Error::INTERNAL_START.

+
source

pub fn raw_os_error(&self) -> Option<i32>

Extract the raw OS error code (if this error came from the OS)

+

This method is identical to std::io::Error::raw_os_error(), except +that it works in no_std contexts. If this method returns None, the +error value can still be formatted via the Display implementation.

+
source

pub fn code(&self) -> Option<NonZeroU32>

Retrieve the error code, if any.

+

If this Error was constructed via From<NonZeroU32>, then this method +will return this NonZeroU32 code (for no_std this is always the +case). Otherwise, this method will return None.

+

Trait Implementations§

source§

impl Debug for Error

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Display for Error

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl From<NonZero<u32>> for Error

source§

fn from(code: NonZeroU32) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

§

impl Freeze for Error

§

impl RefUnwindSafe for Error

§

impl Send for Error

§

impl Sync for Error

§

impl Unpin for Error

§

impl UnwindSafe for Error

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

source§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/rand_core/trait.CryptoRng.html b/rand_core/trait.CryptoRng.html new file mode 100644 index 000000000..d159c6fc4 --- /dev/null +++ b/rand_core/trait.CryptoRng.html @@ -0,0 +1,17 @@ +CryptoRng in rand_core - Rust
rand_core

Trait CryptoRng

source
pub trait CryptoRng { }
Expand description

A marker trait used to indicate that an RngCore or BlockRngCore +implementation is supposed to be cryptographically secure.

+

Cryptographically secure generators, also known as CSPRNGs, should +satisfy an additional properties over other generators: given the first +k bits of an algorithm’s output +sequence, it should not be possible using polynomial-time algorithms to +predict the next bit with probability significantly greater than 50%.

+

Some generators may satisfy an additional property, however this is not +required by this trait: if the CSPRNG’s state is revealed, it should not be +computationally-feasible to reconstruct output prior to this. Some other +generators allow backwards-computation and are considered reversible.

+

Note that this trait is provided for guidance only and cannot guarantee +suitability for cryptographic applications. In general it should only be +implemented for well-reviewed code implementing well-regarded algorithms.

+

Note also that use of a CryptoRng does not protect against other +weaknesses such as seeding from a weak entropy source or leaking state.

+

Implementations on Foreign Types§

source§

impl<'a, R: CryptoRng + ?Sized> CryptoRng for &'a mut R

Implementors§

\ No newline at end of file diff --git a/rand_core/trait.CryptoRngCore.html b/rand_core/trait.CryptoRngCore.html new file mode 100644 index 000000000..7112b0250 --- /dev/null +++ b/rand_core/trait.CryptoRngCore.html @@ -0,0 +1,18 @@ +CryptoRngCore in rand_core - Rust
rand_core

Trait CryptoRngCore

source
pub trait CryptoRngCore: CryptoRng + RngCore {
+    // Required method
+    fn as_rngcore(&mut self) -> &mut dyn RngCore;
+}
Expand description

An extension trait that is automatically implemented for any type +implementing RngCore and CryptoRng.

+

It may be used as a trait object, and supports upcasting to RngCore via +the CryptoRngCore::as_rngcore method.

+

§Example

+
use rand_core::CryptoRngCore;
+
+#[allow(unused)]
+fn make_token(rng: &mut dyn CryptoRngCore) -> [u8; 32] {
+    let mut buf = [0u8; 32];
+    rng.fill_bytes(&mut buf);
+    buf
+}
+

Required Methods§

source

fn as_rngcore(&mut self) -> &mut dyn RngCore

Upcast to an RngCore trait object.

+

Implementors§

\ No newline at end of file diff --git a/rand_core/trait.RngCore.html b/rand_core/trait.RngCore.html new file mode 100644 index 000000000..f834b3023 --- /dev/null +++ b/rand_core/trait.RngCore.html @@ -0,0 +1,105 @@ +RngCore in rand_core - Rust
rand_core

Trait RngCore

source
pub trait RngCore {
+    // Required methods
+    fn next_u32(&mut self) -> u32;
+    fn next_u64(&mut self) -> u64;
+    fn fill_bytes(&mut self, dest: &mut [u8]);
+    fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error>;
+}
Expand description

The core of a random number generator.

+

This trait encapsulates the low-level functionality common to all +generators, and is the “back end”, to be implemented by generators. +End users should normally use the Rng trait from the rand crate, +which is automatically implemented for every type implementing RngCore.

+

Three different methods for generating random data are provided since the +optimal implementation of each is dependent on the type of generator. There +is no required relationship between the output of each; e.g. many +implementations of fill_bytes consume a whole number of u32 or u64 +values and drop any remaining unused bytes. The same can happen with the +next_u32 and next_u64 methods, implementations may discard some +random bits for efficiency.

+

The try_fill_bytes method is a variant of fill_bytes allowing error +handling; it is not deemed sufficiently useful to add equivalents for +next_u32 or next_u64 since the latter methods are almost always used +with algorithmic generators (PRNGs), which are normally infallible.

+

Implementers should produce bits uniformly. Pathological RNGs (e.g. always +returning the same value, or never setting certain bits) can break rejection +sampling used by random distributions, and also break other RNGs when +seeding them via SeedableRng::from_rng.

+

Algorithmic generators implementing SeedableRng should normally have +portable, reproducible output, i.e. fix Endianness when converting values +to avoid platform differences, and avoid making any changes which affect +output (except by communicating that the release has breaking changes).

+

Typically an RNG will implement only one of the methods available +in this trait directly, then use the helper functions from the +impls module to implement the other methods.

+

It is recommended that implementations also implement:

+
    +
  • Debug with a custom implementation which does not print any internal +state (at least, CryptoRngs 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))
+    }
+}
+

Required Methods§

source

fn next_u32(&mut self) -> u32

Return the next random u32.

+

RNGs must implement at least one method from this trait directly. In +the case this method is not implemented directly, it can be implemented +using self.next_u64() as u32 or via impls::next_u32_via_fill.

+
source

fn next_u64(&mut self) -> u64

Return the next random u64.

+

RNGs must implement at least one method from this trait directly. In +the case this method is not implemented directly, it can be implemented +via impls::next_u64_via_u32 or via impls::next_u64_via_fill.

+
source

fn fill_bytes(&mut self, dest: &mut [u8])

Fill dest with random data.

+

RNGs must implement at least one method from this trait directly. In +the case this method is not implemented directly, it can be implemented +via impls::fill_bytes_via_next or +via RngCore::try_fill_bytes; if this generator can +fail the implementation must choose how best to handle errors here +(e.g. panic with a descriptive message or log a warning and retry a few +times).

+

This method should guarantee that dest is entirely filled +with new data, and may panic if this is impossible +(e.g. reading past the end of a file that is being used as the +source of randomness).

+
source

fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error>

Fill dest entirely with random data.

+

This is the only method which allows an RNG to report errors while +generating random data thus making this the primary method implemented +by external (true) RNGs (e.g. OsRng) which can fail. It may be used +directly to generate keys and to seed (infallible) PRNGs.

+

Other than error handling, this method is identical to RngCore::fill_bytes; +thus this may be implemented using Ok(self.fill_bytes(dest)) or +fill_bytes may be implemented with +self.try_fill_bytes(dest).unwrap() or more specific error handling.

+

Implementations on Foreign Types§

source§

impl<'a, R: RngCore + ?Sized> RngCore for &'a mut R

source§

fn next_u32(&mut self) -> u32

source§

fn next_u64(&mut self) -> u64

source§

fn fill_bytes(&mut self, dest: &mut [u8])

source§

fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error>

Implementors§

source§

impl<R: BlockRngCore<Item = u32>> RngCore for BlockRng<R>
where + <R as BlockRngCore>::Results: AsRef<[u32]> + AsMut<[u32]>,

source§

impl<R: BlockRngCore<Item = u64>> RngCore for BlockRng64<R>
where + <R as BlockRngCore>::Results: AsRef<[u64]> + AsMut<[u64]>,

\ No newline at end of file diff --git a/rand_core/trait.SeedableRng.html b/rand_core/trait.SeedableRng.html new file mode 100644 index 000000000..ef24c7248 --- /dev/null +++ b/rand_core/trait.SeedableRng.html @@ -0,0 +1,101 @@ +SeedableRng in rand_core - Rust
rand_core

Trait SeedableRng

source
pub trait SeedableRng: Sized {
+    type Seed: Sized + Default + AsMut<[u8]>;
+
+    // Required method
+    fn from_seed(seed: Self::Seed) -> Self;
+
+    // Provided methods
+    fn seed_from_u64(state: u64) -> Self { ... }
+    fn from_rng<R: RngCore>(rng: R) -> Result<Self, Error> { ... }
+}
Expand description

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).

+

Required Associated Types§

source

type Seed: Sized + Default + AsMut<[u8]>

Seed type, which is restricted to types mutably-dereferenceable as u8 +arrays (we recommend [u8; N] for some N).

+

It is recommended to seed PRNGs with a seed of at least circa 100 bits, +which means an array of [u8; 12] or greater to avoid picking RNGs with +partially overlapping periods.

+

For cryptographic RNG’s a seed of 256 bits is recommended, [u8; 32].

+
§Implementing SeedableRng for RNGs with large seeds
+

Note that the required traits core::default::Default and +core::convert::AsMut<u8> are not implemented for large arrays +[u8; N] with N > 32. To be able to implement the traits required by +SeedableRng for RNGs with such large seeds, the newtype pattern can be +used:

+ +
use rand_core::SeedableRng;
+
+const N: usize = 64;
+pub struct MyRngSeed(pub [u8; N]);
+pub struct MyRng(MyRngSeed);
+
+impl Default for MyRngSeed {
+    fn default() -> MyRngSeed {
+        MyRngSeed([0; N])
+    }
+}
+
+impl AsMut<[u8]> for MyRngSeed {
+    fn as_mut(&mut self) -> &mut [u8] {
+        &mut self.0
+    }
+}
+
+impl SeedableRng for MyRng {
+    type Seed = MyRngSeed;
+
+    fn from_seed(seed: MyRngSeed) -> MyRng {
+        MyRng(seed)
+    }
+}
+

Required Methods§

source

fn from_seed(seed: Self::Seed) -> Self

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.

+

Provided Methods§

source

fn seed_from_u64(state: u64) -> 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.

+
source

fn from_rng<R: RngCore>(rng: R) -> Result<Self, Error>

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).

+

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§

\ No newline at end of file diff --git a/rand_mt/all.html b/rand_mt/all.html new file mode 100644 index 000000000..884795abb --- /dev/null +++ b/rand_mt/all.html @@ -0,0 +1 @@ +List of all items in this crate

List of all items

Structs

Enums

Type Aliases

\ No newline at end of file diff --git a/rand_mt/enum.RecoverRngError.html b/rand_mt/enum.RecoverRngError.html new file mode 100644 index 000000000..f6bb8c931 --- /dev/null +++ b/rand_mt/enum.RecoverRngError.html @@ -0,0 +1,32 @@ +RecoverRngError in rand_mt - Rust
rand_mt

Enum RecoverRngError

source
#[non_exhaustive]
pub enum RecoverRngError { + TooFewSamples(usize), + TooManySamples(usize), +}
Expand description

Error returned from fallible Mersenne Twister recovery constructors.

+

When the std feature is enabled, this type implements std::error::Error.

+

Variants (Non-exhaustive)§

This enum is marked as non-exhaustive
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
§

TooFewSamples(usize)

Attempted to recover an RNG with too many samples.

+

Recover constructors require an exact number of samples to ensure the +recovered RNG matches the state of the RNG that supplied all of the +samples.

+
§

TooManySamples(usize)

Attempted to recover an RNG with too few samples.

+

Too few samples leaves the internal state buffer partially +uninitialized.

+

Recover constructors require an exact number of samples to ensure the +recovered RNG matches the state of the RNG that supplied all of the +samples.

+

Trait Implementations§

source§

impl Clone for RecoverRngError

source§

fn clone(&self) -> RecoverRngError

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for RecoverRngError

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Display for RecoverRngError

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Error for RecoverRngError

1.30.0 · source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.0.0 · source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
1.0.0 · source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
source§

impl Hash for RecoverRngError

source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where + H: Hasher, + Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
source§

impl PartialEq for RecoverRngError

source§

fn eq(&self, other: &RecoverRngError) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, +and should not be overridden without very good reason.
source§

impl Copy for RecoverRngError

source§

impl Eq for RecoverRngError

source§

impl StructuralPartialEq for RecoverRngError

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> CloneToUninit for T
where + T: Clone,

source§

unsafe fn clone_to_uninit(&self, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> ToOwned for T
where + T: Clone,

source§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T> ToString for T
where + T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

source§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/rand_mt/index.html b/rand_mt/index.html new file mode 100644 index 000000000..628621c3e --- /dev/null +++ b/rand_mt/index.html @@ -0,0 +1,48 @@ +rand_mt - Rust

Crate rand_mt

source
Expand description

Mersenne Twister random number generators.

+

This is a native Rust implementation of a selection of Mersenne Twister +generators. Mersenne Twister is not suitable for cryptographic use.

+

This crate provides:

+
    +
  • Mt19937GenRand32, the original reference Mersenne Twister +implementation known as MT19937. This is a good choice on both 32-bit +and 64-bit CPUs (for 32-bit output).
  • +
  • Mt19937GenRand64, the 64-bit variant of MT19937 known as +MT19937-64. This algorithm produces a different output stream than +MT19937 and produces 64-bit output. This is a good choice on 64-bit +CPUs.
  • +
+

Both of these RNGs use approximately 2.5 kilobytes of state. +Mt19937GenRand32 uses a 32-bit seed. Mt19937GenRand64 uses a 64-bit +seed. Both can be seeded from an iterator of seeds.

+

Both RNGs implement a recover constructor which can reconstruct the RNG +state from a sequence of output samples.

+

§Usage

+

You can seed a RNG and begin sampling it:

+ +
// Create the RNG.
+let mut rng = Mt64::new(0x1234_567_89ab_cdef_u64);
+// start grabbing randomness from rng...
+let mut buf = vec![0; 512];
+rng.fill_bytes(&mut buf);
+

Or if you want to use the default (fixed) seeds that are specified in the +reference implementations:

+ +
let default = Mt::default();
+let mt = Mt::new_unseeded();
+assert_eq!(default, mt);
+

§Crate Features

+

rand_mt is no_std compatible. rand_mt has several optional features +that are enabled by default:

+
    +
  • rand-traits - Enables a dependency on rand_core. Activating this +feature implements RngCore and SeedableRng on the RNGs in this crate.
  • +
  • std - Enables a dependency on the Rust Standard Library. Activating +this feature enables std::error::Error impls on error types in this +crate.
  • +
+

Mersenne Twister requires approximately 2.5 kilobytes of internal state. To +make the RNGs implemented in this crate practical to embed in other structs, +you may wish to store the RNG in a Box.

+

Structs§

  • The 32-bit flavor of the Mersenne Twister pseudorandom number +generator.
  • The 64-bit flavor of the Mersenne Twister pseudorandom number +generator.

Enums§

  • Error returned from fallible Mersenne Twister recovery constructors.

Type Aliases§

\ No newline at end of file diff --git a/rand_mt/mt/struct.Mt19937GenRand32.html b/rand_mt/mt/struct.Mt19937GenRand32.html new file mode 100644 index 000000000..fa671e612 --- /dev/null +++ b/rand_mt/mt/struct.Mt19937GenRand32.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../rand_mt/struct.Mt19937GenRand32.html...

+ + + \ No newline at end of file diff --git a/rand_mt/mt64/struct.Mt19937GenRand64.html b/rand_mt/mt64/struct.Mt19937GenRand64.html new file mode 100644 index 000000000..53dd4eb5a --- /dev/null +++ b/rand_mt/mt64/struct.Mt19937GenRand64.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../rand_mt/struct.Mt19937GenRand64.html...

+ + + \ No newline at end of file diff --git a/rand_mt/sidebar-items.js b/rand_mt/sidebar-items.js new file mode 100644 index 000000000..407f0bd34 --- /dev/null +++ b/rand_mt/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"enum":["RecoverRngError"],"struct":["Mt19937GenRand32","Mt19937GenRand64"],"type":["Mt","Mt64"]}; \ No newline at end of file diff --git a/rand_mt/struct.Mt19937GenRand32.html b/rand_mt/struct.Mt19937GenRand32.html new file mode 100644 index 000000000..94fd525af --- /dev/null +++ b/rand_mt/struct.Mt19937GenRand32.html @@ -0,0 +1,221 @@ +Mt19937GenRand32 in rand_mt - Rust
rand_mt

Struct Mt19937GenRand32

source
pub struct Mt19937GenRand32 { /* private fields */ }
Expand description

The 32-bit flavor of the Mersenne Twister pseudorandom number +generator.

+

The official name of this RNG is MT19937. It natively outputs u32.

+

§Size

+

Mt19937GenRand32 requires approximately 2.5 kilobytes of internal state.

+

You may wish to store an Mt19937GenRand32 on the heap in a Box to make +it easier to embed in another struct.

+

Mt19937GenRand32 is also the same size as +Mt19937GenRand64.

+ +
assert_eq!(2504, mem::size_of::<Mt19937GenRand32>());
+assert_eq!(mem::size_of::<Mt19937GenRand64>(), mem::size_of::<Mt19937GenRand32>());
+

Implementations§

source§

impl Mt19937GenRand32

source

pub const DEFAULT_SEED: u32 = 5_489u32

Default seed used by Mt19937GenRand32::new_unseeded.

+
source

pub fn new(seed: u32) -> Self

Create a new Mersenne Twister random number generator using the given +seed.

+
§Examples
§Constructing with a u32 seed
+
let seed = 123_456_789_u32;
+let mt1 = Mt19937GenRand32::new(seed);
+let mt2 = Mt19937GenRand32::from(seed.to_le_bytes());
+assert_eq!(mt1, mt2);
+
§Constructing with default seed
+
let mt1 = Mt19937GenRand32::new(Mt19937GenRand32::DEFAULT_SEED);
+let mt2 = Mt19937GenRand32::new_unseeded();
+assert_eq!(mt1, mt2);
+
source

pub fn new_with_key<I>(key: I) -> Self
where + I: IntoIterator<Item = u32>, + I::IntoIter: Clone,

Create a new Mersenne Twister random number generator using the given +key.

+

Key can have any length.

+
source

pub fn new_unseeded() -> Self

Create a new Mersenne Twister random number generator using the default +fixed seed.

+
§Examples
+
// Default MT seed
+let seed = 5489_u32;
+let mt = Mt19937GenRand32::new(seed);
+let unseeded = Mt19937GenRand32::new_unseeded();
+assert_eq!(mt, unseeded);
+
source

pub fn next_u64(&mut self) -> u64

Generate next u64 output.

+

This function is implemented by generating two u32s from the RNG and +performing shifting and masking to turn them into a u64 output.

+
§Examples
+
let mut mt = Mt19937GenRand32::new_unseeded();
+assert_ne!(mt.next_u64(), mt.next_u64());
+
source

pub fn next_u32(&mut self) -> u32

Generate next u32 output.

+

u32 is the native output of the generator. This function advances the +RNG step counter by one.

+
§Examples
+
let mut mt = Mt19937GenRand32::new_unseeded();
+assert_ne!(mt.next_u32(), mt.next_u32());
+
source

pub fn fill_bytes(&mut self, dest: &mut [u8])

Fill a buffer with bytes generated from the RNG.

+

This method generates random u32s (the native output unit of the RNG) +until dest is filled.

+

This method may discard some output bits if dest.len() is not a +multiple of 4.

+
§Examples
+
let mut mt = Mt19937GenRand32::new_unseeded();
+let mut buf = [0; 32];
+mt.fill_bytes(&mut buf);
+assert_ne!([0; 32], buf);
+let mut buf = [0; 31];
+mt.fill_bytes(&mut buf);
+assert_ne!([0; 31], buf);
+
source

pub fn recover<I>(key: I) -> Result<Self, RecoverRngError>
where + I: IntoIterator<Item = u32>,

Attempt to recover the internal state of a Mersenne Twister using the +past 624 samples.

+

This conversion takes a history of samples from a RNG and returns a +RNG that will produce identical output to the RNG that supplied the +samples.

+

This constructor is also available as a TryFrom implementation for +&[u32].

+
§Errors
+

If key has less than 624 elements, an error is returned because there +is not enough data to fully initialize the RNG.

+

If key has more than 624 elements, an error is returned because the +recovered RNG will not produce identical output to the RNG that supplied +the samples.

+
source

pub fn reseed(&mut self, seed: u32)

Reseed a Mersenne Twister from a single u32.

+
§Examples
+
// Default MT seed
+let mut mt = Mt19937GenRand32::new_unseeded();
+let first = mt.next_u32();
+mt.fill_bytes(&mut [0; 512]);
+// Default MT seed
+mt.reseed(5489_u32);
+assert_eq!(first, mt.next_u32());
+
source

pub fn reseed_with_key<I>(&mut self, key: I)
where + I: IntoIterator<Item = u32>, + I::IntoIter: Clone,

Reseed a Mersenne Twister from am iterator of u32s.

+

Key can have any length.

+

Trait Implementations§

source§

impl Clone for Mt19937GenRand32

source§

fn clone(&self) -> Mt19937GenRand32

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for Mt19937GenRand32

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Default for Mt19937GenRand32

source§

fn default() -> Self

Return a new Mt19937GenRand32 with the default seed.

+

Equivalent to calling Mt19937GenRand32::new_unseeded.

+
source§

impl From<[u32; 624]> for Mt19937GenRand32

source§

fn from(key: [u32; 624]) -> Self

Recover the internal state of a Mersenne Twister using the past 624 +samples.

+

This conversion takes a history of samples from a RNG and returns a +RNG that will produce identical output to the RNG that supplied the +samples.

+
source§

impl From<[u8; 4]> for Mt19937GenRand32

source§

fn from(seed: [u8; 4]) -> Self

Construct a Mersenne Twister RNG from 4 bytes.

+

The given bytes are treated as a little endian encoded u32.

+
§Examples
+
// Default MT seed
+let seed = 5489_u32.to_le_bytes();
+let mut mt = Mt19937GenRand32::from(seed);
+assert_ne!(mt.next_u32(), mt.next_u32());
+

This constructor is equivalent to passing a little endian encoded u32.

+ +
// Default MT seed
+let seed = 5489_u32.to_le_bytes();
+let mt1 = Mt19937GenRand32::from(seed);
+let mt2 = Mt19937GenRand32::new(5489_u32);
+assert_eq!(mt1, mt2);
+
source§

impl From<u32> for Mt19937GenRand32

source§

fn from(seed: u32) -> Self

Construct a Mersenne Twister RNG from a u32 seed.

+

This function is equivalent to new.

+
§Examples
+
// Default MT seed
+let seed = 5489_u32;
+let mt1 = Mt19937GenRand32::from(seed);
+let mt2 = Mt19937GenRand32::new(seed);
+assert_eq!(mt1, mt2);
+
+// Non-default MT seed
+let seed = 9927_u32;
+let mt1 = Mt19937GenRand32::from(seed);
+let mt2 = Mt19937GenRand32::new(seed);
+assert_eq!(mt1, mt2);
+
source§

impl Hash for Mt19937GenRand32

source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where + H: Hasher, + Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
source§

impl Ord for Mt19937GenRand32

source§

fn cmp(&self, other: &Mt19937GenRand32) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · source§

fn max(self, other: Self) -> Self
where + Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · source§

fn min(self, other: Self) -> Self
where + Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · source§

fn clamp(self, min: Self, max: Self) -> Self
where + Self: Sized,

Restrict a value to a certain interval. Read more
source§

impl PartialEq for Mt19937GenRand32

source§

fn eq(&self, other: &Mt19937GenRand32) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, +and should not be overridden without very good reason.
source§

impl PartialOrd for Mt19937GenRand32

source§

fn partial_cmp(&self, other: &Mt19937GenRand32) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the +<= operator. Read more
1.0.0 · source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > +operator. Read more
1.0.0 · source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by +the >= operator. Read more
source§

impl RngCore for Mt19937GenRand32

source§

fn next_u64(&mut self) -> u64

Generate next u64 output.

+

This function is implemented by generating two u32s from the RNG and +performing shifting and masking to turn them into a u64 output.

+
§Examples
+
use rand_core::RngCore;
+use rand_mt::Mt19937GenRand32;
+
+let mut rng = Mt19937GenRand32::new_unseeded();
+assert_ne!(rng.next_u64(), rng.next_u64());
+
source§

fn next_u32(&mut self) -> u32

Generate next u32 output.

+

u32 is the native output of the generator. This function advances the +RNG step counter by one.

+
§Examples
+
use rand_core::RngCore;
+use rand_mt::Mt19937GenRand32;
+
+let mut rng = Mt19937GenRand32::new_unseeded();
+assert_ne!(rng.next_u32(), rng.next_u32());
+
source§

fn fill_bytes(&mut self, dest: &mut [u8])

Fill a buffer with bytes generated from the RNG.

+

This method generates random u32s (the native output unit of the RNG) +until dest is filled.

+

This method may discard some output bits if dest.len() is not a +multiple of 4.

+
§Examples
+
use rand_core::RngCore;
+use rand_mt::Mt19937GenRand32;
+
+let mut rng = Mt19937GenRand32::new_unseeded();
+let mut buf = [0; 32];
+rng.fill_bytes(&mut buf);
+assert_ne!([0; 32], buf);
+let mut buf = [0; 31];
+rng.fill_bytes(&mut buf);
+assert_ne!([0; 31], buf);
+
source§

fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error>

Fill a buffer with bytes generated from the RNG.

+

This method generates random u32s (the native output unit of the RNG) +until dest is filled.

+

This method may discard some output bits if dest.len() is not a +multiple of 4.

+

try_fill_bytes is implemented with fill_bytes +and is infallible.

+
§Examples
+
use rand_core::RngCore;
+use rand_mt::Mt19937GenRand32;
+
+let mut rng = Mt19937GenRand32::new_unseeded();
+let mut buf = [0; 32];
+rng.try_fill_bytes(&mut buf)?;
+assert_ne!([0; 32], buf);
+let mut buf = [0; 31];
+rng.try_fill_bytes(&mut buf)?;
+assert_ne!([0; 31], buf);
+
source§

impl SeedableRng for Mt19937GenRand32

source§

fn from_seed(seed: Self::Seed) -> Self

Reseed from a little endian encoded u32.

+
§Examples
+
use rand_core::{RngCore, SeedableRng};
+use rand_mt::Mt19937GenRand32;
+
+// Default MT seed
+let seed = 5489_u32.to_le_bytes();
+let mut rng = Mt19937GenRand32::from_seed(seed);
+assert_ne!(rng.next_u32(), rng.next_u32());
+
source§

type Seed = [u8; 4]

Seed type, which is restricted to types mutably-dereferenceable as u8 +arrays (we recommend [u8; N] for some N). Read more
source§

fn seed_from_u64(state: u64) -> Self

Create a new PRNG using a u64 seed. Read more
source§

fn from_rng<R>(rng: R) -> Result<Self, Error>
where + R: RngCore,

Create a new PRNG seeded from another Rng. Read more
source§

impl TryFrom<&[u32]> for Mt19937GenRand32

source§

fn try_from(key: &[u32]) -> Result<Self, Self::Error>

Attempt to recover the internal state of a Mersenne Twister using the +past 624 samples.

+

This conversion takes a history of samples from a RNG and returns a +RNG that will produce identical output to the RNG that supplied the +samples.

+

This conversion is implemented with Mt19937GenRand32::recover.

+
§Errors
+

If key has less than 624 elements, an error is returned because there +is not enough data to fully initialize the RNG.

+

If key has more than 624 elements, an error is returned because the +recovered RNG will not produce identical output to the RNG that supplied +the samples.

+
source§

type Error = RecoverRngError

The type returned in the event of a conversion error.
source§

impl Eq for Mt19937GenRand32

source§

impl StructuralPartialEq for Mt19937GenRand32

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> CloneToUninit for T
where + T: Clone,

source§

unsafe fn clone_to_uninit(&self, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> ToOwned for T
where + T: Clone,

source§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

source§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/rand_mt/struct.Mt19937GenRand64.html b/rand_mt/struct.Mt19937GenRand64.html new file mode 100644 index 000000000..bd317b739 --- /dev/null +++ b/rand_mt/struct.Mt19937GenRand64.html @@ -0,0 +1,209 @@ +Mt19937GenRand64 in rand_mt - Rust
rand_mt

Struct Mt19937GenRand64

source
pub struct Mt19937GenRand64 { /* private fields */ }
Expand description

The 64-bit flavor of the Mersenne Twister pseudorandom number +generator.

+

§Size

+

Mt19937GenRand64 requires approximately 2.5 kilobytes of internal state.

+

You may wish to store an Mt19937GenRand64 on the heap in a Box to make it +easier to embed in another struct.

+

Mt19937GenRand64 is also the same size as +Mt19937GenRand32.

+ +
assert_eq!(2504, mem::size_of::<Mt19937GenRand64>());
+assert_eq!(mem::size_of::<Mt19937GenRand32>(), mem::size_of::<Mt19937GenRand64>());
+

Implementations§

source§

impl Mt19937GenRand64

source

pub const DEFAULT_SEED: u64 = 5_489u64

Default seed used by Mt19937GenRand64::new_unseeded.

+
source

pub fn new(seed: u64) -> Self

Create a new Mersenne Twister random number generator using the given +seed.

+
§Examples
§Constructing with a u64 seed
+
let seed = 123_456_789_u64;
+let mt1 = Mt19937GenRand64::new(seed);
+let mt2 = Mt19937GenRand64::from(seed.to_le_bytes());
+assert_eq!(mt1, mt2);
+
§Constructing with default seed
+
let mt1 = Mt19937GenRand64::new(Mt19937GenRand64::DEFAULT_SEED);
+let mt2 = Mt19937GenRand64::new_unseeded();
+assert_eq!(mt1, mt2);
+
source

pub fn new_with_key<I>(key: I) -> Self
where + I: IntoIterator<Item = u64>, + I::IntoIter: Clone,

Create a new Mersenne Twister random number generator using the given +key.

+

Key can have any length.

+
source

pub fn new_unseeded() -> Self

Create a new Mersenne Twister random number generator using the default +fixed seed.

+
§Examples
+
// Default MT seed
+let seed = 5489_u64;
+let mt = Mt19937GenRand64::new(seed);
+let unseeded = Mt19937GenRand64::new_unseeded();
+assert_eq!(mt, unseeded);
+
source

pub fn next_u64(&mut self) -> u64

Generate next u64 output.

+

u64 is the native output of the generator. This function advances the +RNG step counter by one.

+
§Examples
+
let mut mt = Mt19937GenRand64::new_unseeded();
+assert_ne!(mt.next_u64(), mt.next_u64());
+
source

pub fn next_u32(&mut self) -> u32

Generate next u32 output.

+

This function is implemented by generating one u64 from the RNG and +performing shifting and masking to turn it into a u32 output.

+
§Examples
+
let mut mt = Mt19937GenRand64::new_unseeded();
+assert_ne!(mt.next_u32(), mt.next_u32());
+
source

pub fn fill_bytes(&mut self, dest: &mut [u8])

Fill a buffer with bytes generated from the RNG.

+

This method generates random u64s (the native output unit of the RNG) +until dest is filled.

+

This method may discard some output bits if dest.len() is not a +multiple of 8.

+
§Examples
+
let mut mt = Mt19937GenRand64::new_unseeded();
+let mut buf = [0; 32];
+mt.fill_bytes(&mut buf);
+assert_ne!([0; 32], buf);
+let mut buf = [0; 31];
+mt.fill_bytes(&mut buf);
+assert_ne!([0; 31], buf);
+
source

pub fn recover<I>(key: I) -> Result<Self, RecoverRngError>
where + I: IntoIterator<Item = u64>,

Attempt to recover the internal state of a Mersenne Twister using the +past 312 samples.

+

This conversion takes a history of samples from a RNG and returns a +RNG that will produce identical output to the RNG that supplied the +samples.

+

This constructor is also available as a TryFrom implementation for +&[u32].

+
§Errors
+

If key has less than 312 elements, an error is returned because there +is not enough data to fully initialize the RNG.

+

If key has more than 312 elements, an error is returned because the +recovered RNG will not produce identical output to the RNG that supplied +the samples.

+
source

pub fn reseed(&mut self, seed: u64)

Reseed a Mersenne Twister from a single u64.

+
§Examples
+
// Default MT seed
+let mut mt = Mt19937GenRand64::new_unseeded();
+let first = mt.next_u64();
+mt.fill_bytes(&mut [0; 512]);
+// Default MT seed
+mt.reseed(5489_u64);
+assert_eq!(first, mt.next_u64());
+
source

pub fn reseed_with_key<I>(&mut self, key: I)
where + I: IntoIterator<Item = u64>, + I::IntoIter: Clone,

Reseed a Mersenne Twister from am iterator of u64s.

+

Key can have any length.

+

Trait Implementations§

source§

impl Clone for Mt19937GenRand64

source§

fn clone(&self) -> Mt19937GenRand64

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for Mt19937GenRand64

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Default for Mt19937GenRand64

source§

fn default() -> Self

Return a new Mt19937GenRand64 with the default seed.

+

Equivalent to calling Mt19937GenRand64::new_unseeded.

+
source§

impl From<[u64; 312]> for Mt19937GenRand64

source§

fn from(key: [u64; 312]) -> Self

Recover the internal state of a Mersenne Twister using the past 312 +samples.

+

This conversion takes a history of samples from a RNG and returns a +RNG that will produce identical output to the RNG that supplied the +samples.

+
source§

impl From<[u8; 8]> for Mt19937GenRand64

source§

fn from(seed: [u8; 8]) -> Self

Construct a Mersenne Twister RNG from 8 bytes.

+
§Examples
+
// Default MT seed
+let seed = 5489_u64.to_le_bytes();
+let mut mt = Mt19937GenRand64::from(seed);
+assert_ne!(mt.next_u64(), mt.next_u64());
+
source§

impl From<u64> for Mt19937GenRand64

source§

fn from(seed: u64) -> Self

Construct a Mersenne Twister RNG from a u64 seed.

+

This function is equivalent to new.

+
§Examples
+
// Default MT seed
+let seed = 5489_u64;
+let mt1 = Mt19937GenRand64::from(seed);
+let mt2 = Mt19937GenRand64::new(seed);
+assert_eq!(mt1, mt2);
+
+// Non-default MT seed
+let seed = 9927_u64;
+let mt1 = Mt19937GenRand64::from(seed);
+let mt2 = Mt19937GenRand64::new(seed);
+assert_eq!(mt1, mt2);
+
source§

impl Hash for Mt19937GenRand64

source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where + H: Hasher, + Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
source§

impl Ord for Mt19937GenRand64

source§

fn cmp(&self, other: &Mt19937GenRand64) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · source§

fn max(self, other: Self) -> Self
where + Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · source§

fn min(self, other: Self) -> Self
where + Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · source§

fn clamp(self, min: Self, max: Self) -> Self
where + Self: Sized,

Restrict a value to a certain interval. Read more
source§

impl PartialEq for Mt19937GenRand64

source§

fn eq(&self, other: &Mt19937GenRand64) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, +and should not be overridden without very good reason.
source§

impl PartialOrd for Mt19937GenRand64

source§

fn partial_cmp(&self, other: &Mt19937GenRand64) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the +<= operator. Read more
1.0.0 · source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > +operator. Read more
1.0.0 · source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by +the >= operator. Read more
source§

impl RngCore for Mt19937GenRand64

source§

fn next_u64(&mut self) -> u64

Generate next u64 output.

+

u64 is the native output of the generator. This function advances the +RNG step counter by one.

+
§Examples
+
use rand_core::RngCore;
+use rand_mt::Mt19937GenRand64;
+
+let mut rng = Mt19937GenRand64::new_unseeded();
+assert_ne!(rng.next_u64(), rng.next_u64());
+
source§

fn next_u32(&mut self) -> u32

Generate next u32 output.

+

This function is implemented by generating one u64 from the RNG and +performing shifting and masking to turn it into a u32 output.

+
§Examples
+
use rand_core::RngCore;
+use rand_mt::Mt19937GenRand64;
+
+let mut rng = Mt19937GenRand64::new_unseeded();
+assert_ne!(rng.next_u32(), rng.next_u32());
+
source§

fn fill_bytes(&mut self, dest: &mut [u8])

Fill a buffer with bytes generated from the RNG.

+

This method generates random u64s (the native output unit of the RNG) +until dest is filled.

+

This method may discard some output bits if dest.len() is not a +multiple of 8.

+
§Examples
+
use rand_core::RngCore;
+use rand_mt::Mt19937GenRand64;
+
+let mut rng = Mt19937GenRand64::new_unseeded();
+let mut buf = [0; 32];
+rng.fill_bytes(&mut buf);
+assert_ne!([0; 32], buf);
+let mut buf = [0; 31];
+rng.fill_bytes(&mut buf);
+assert_ne!([0; 31], buf);
+
source§

fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error>

Fill a buffer with bytes generated from the RNG.

+

This method generates random u64s (the native output unit of the RNG) +until dest is filled.

+

This method may discard some output bits if dest.len() is not a +multiple of 8.

+

try_fill_bytes is implemented with fill_bytes +and is infallible.

+
§Examples
+
use rand_core::RngCore;
+use rand_mt::Mt19937GenRand64;
+
+let mut rng = Mt19937GenRand64::new_unseeded();
+let mut buf = [0; 32];
+rng.try_fill_bytes(&mut buf)?;
+assert_ne!([0; 32], buf);
+let mut buf = [0; 31];
+rng.try_fill_bytes(&mut buf)?;
+assert_ne!([0; 31], buf);
+
source§

impl SeedableRng for Mt19937GenRand64

source§

fn from_seed(seed: Self::Seed) -> Self

Reseed from a little endian encoded u64.

+
§Examples
+
// Default MT seed
+let seed = 5489_u64.to_le_bytes();
+let mut mt = Mt19937GenRand64::from_seed(seed);
+assert_ne!(mt.next_u64(), mt.next_u64());
+
source§

type Seed = [u8; 8]

Seed type, which is restricted to types mutably-dereferenceable as u8 +arrays (we recommend [u8; N] for some N). Read more
source§

fn seed_from_u64(state: u64) -> Self

Create a new PRNG using a u64 seed. Read more
source§

fn from_rng<R>(rng: R) -> Result<Self, Error>
where + R: RngCore,

Create a new PRNG seeded from another Rng. Read more
source§

impl TryFrom<&[u64]> for Mt19937GenRand64

source§

fn try_from(key: &[u64]) -> Result<Self, Self::Error>

Attempt to recover the internal state of a Mersenne Twister using the +past 312 samples.

+

This conversion takes a history of samples from a RNG and returns a +RNG that will produce identical output to the RNG that supplied the +samples.

+

This conversion is implemented with Mt19937GenRand64::recover.

+
§Errors
+

If key has less than 312 elements, an error is returned because there +is not enough data to fully initialize the RNG.

+

If key has more than 312 elements, an error is returned because the +recovered RNG will not produce identical output to the RNG that supplied +the samples.

+
source§

type Error = RecoverRngError

The type returned in the event of a conversion error.
source§

impl Eq for Mt19937GenRand64

source§

impl StructuralPartialEq for Mt19937GenRand64

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> CloneToUninit for T
where + T: Clone,

source§

unsafe fn clone_to_uninit(&self, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> ToOwned for T
where + T: Clone,

source§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

source§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/rand_mt/type.Mt.html b/rand_mt/type.Mt.html new file mode 100644 index 000000000..76938e62c --- /dev/null +++ b/rand_mt/type.Mt.html @@ -0,0 +1,2 @@ +Mt in rand_mt - Rust
rand_mt

Type Alias Mt

source
pub type Mt = Mt19937GenRand32;
Expand description

A type alias for Mt19937GenRand32, 32-bit Mersenne Twister.

+

Aliased Type§

struct Mt { /* private fields */ }
\ No newline at end of file diff --git a/rand_mt/type.Mt64.html b/rand_mt/type.Mt64.html new file mode 100644 index 000000000..2b6fa2480 --- /dev/null +++ b/rand_mt/type.Mt64.html @@ -0,0 +1,2 @@ +Mt64 in rand_mt - Rust
rand_mt

Type Alias Mt64

source
pub type Mt64 = Mt19937GenRand64;
Expand description

A type alias for Mt19937GenRand64, 64-bit Mersenne Twister.

+

Aliased Type§

struct Mt64 { /* private fields */ }
\ No newline at end of file diff --git a/search-index.js b/search-index.js new file mode 100644 index 000000000..9c5fe25ae --- /dev/null +++ b/search-index.js @@ -0,0 +1,4 @@ +var searchIndex = new Map(JSON.parse('[["rand_core",{"t":"TKKFTKRKMCNNNMNNNNNMCNCMMNNMNNNFFKRRNNNNNNNNNOONNNNNNNNNNMNNNNNNNNNNNNNNNNNNNNNNNNHHHHHHHH","n":["CUSTOM_START","CryptoRng","CryptoRngCore","Error","INTERNAL_START","RngCore","Seed","SeedableRng","as_rngcore","block","borrow","borrow_mut","code","fill_bytes","fmt","","from","","from_rng","from_seed","impls","into","le","next_u32","next_u64","raw_os_error","seed_from_u64","try_fill_bytes","try_from","try_into","type_id","BlockRng","BlockRng64","BlockRngCore","Item","Results","as_rngcore","borrow","","borrow_mut","","clone","","clone_to_uninit","","core","","fill_bytes","","fmt","","from","","from_rng","","from_seed","","generate","generate_and_set","","index","","into","","new","","next_u32","","next_u64","","reset","","seed_from_u64","","try_fill_bytes","","try_from","","try_into","","type_id","","fill_bytes_via_next","fill_via_u32_chunks","fill_via_u64_chunks","next_u32_via_fill","next_u64_via_fill","next_u64_via_u32","read_u32_into","read_u64_into"],"q":[[0,"rand_core"],[31,"rand_core::block"],[82,"rand_core::impls"],[88,"rand_core::le"],[90,"rand_core::error"],[91,"core::num::nonzero"],[92,"core::option"],[93,"core::fmt"],[94,"core::result"],[95,"core::marker"],[96,"core::default"],[97,"core::convert"],[98,"core::any"],[99,"core::clone"]],"i":"j```0`Al`d`222h333322`3`00320333```Cb0Bn0Cd1010101010101010102101010101010101010101010````````","f":"````````{{{f{bd}}}{{f{bh}}}}`{f{{f{c}}}{}}{{{f{b}}}{{f{bc}}}{}}{{{f{j}}}{{n{l}}}}{{{f{bh}}{f{b{Ab{A`}}}}}Ad}{{{f{j}}{f{bAf}}}Ah}0{lj}{cc{}}{c{{An{{Al{}{{Aj{e}}}}j}}}h{B`Bb{Bd{{Ab{A`}}}}}}{c{{Al{}{{Aj{c}}}}}{B`Bb{Bd{{Ab{A`}}}}}}`{{}c{}}`{{{f{bh}}}Bf}{{{f{bh}}}Bh}{{{f{j}}}{{n{Bj}}}}{Bh{{Al{}{{Aj{c}}}}}{B`Bb{Bd{{Ab{A`}}}}}}{{{f{bh}}{f{b{Ab{A`}}}}}{{An{Adj}}}}{c{{An{e}}}{}{}}{{}{{An{c}}}{}}{fBl}`````{{{f{b}}}{{f{bh}}}}{f{{f{c}}}{}}0{{{f{b}}}{{f{bc}}}{}}0{{{f{{Bn{c}}}}}{{Bn{c}}}{C`CbB`}}{{{f{{Cd{c}}}}}{{Cd{c}}}{C`CbB`}}{fAd}0``{{{f{b{Bn{c}}}}{f{b{Ab{A`}}}}}Ad{{Cb{}{{Cf{Bf}}}}}}{{{f{b{Cd{c}}}}{f{b{Ab{A`}}}}}Ad{{Cb{}{{Cf{Bh}}}}}}{{{f{{Bn{c}}}}{f{bAf}}}Ah{CbCh}}{{{f{{Cd{c}}}}{f{bAf}}}Ah{CbCh}}{cc{}}0{c{{An{{Bn{e}}j}}}h{CbAl}}{c{{An{{Cd{e}}j}}}h{CbAl}}{c{{Bn{e}}}{}{CbAl}}{c{{Cd{e}}}{}{CbAl}}{{{f{b{Cb{}{{Cf{c}}{Cj{e}}}}}}{f{be}}}Ad{}{{Cl{{Ab{c}}}}{Bd{{Ab{c}}}}Bb}}{{{f{b{Bn{c}}}}Cn}AdCb}{{{f{b{Cd{c}}}}Cn}AdCb}{{{f{{Bn{c}}}}}CnCb}{{{f{{Cd{c}}}}}CnCb}{{}c{}}0{c{{Bn{c}}}Cb}{c{{Cd{c}}}Cb}{{{f{b{Bn{c}}}}}Bf{{Cb{}{{Cf{Bf}}}}}}{{{f{b{Cd{c}}}}}Bf{{Cb{}{{Cf{Bh}}}}}}{{{f{b{Bn{c}}}}}Bh{{Cb{}{{Cf{Bf}}}}}}{{{f{b{Cd{c}}}}}Bh{{Cb{}{{Cf{Bh}}}}}}{{{f{b{Bn{c}}}}}AdCb}{{{f{b{Cd{c}}}}}AdCb}{Bh{{Bn{c}}}{CbAl}}{Bh{{Cd{c}}}{CbAl}}{{{f{b{Bn{c}}}}{f{b{Ab{A`}}}}}{{An{Adj}}}{{Cb{}{{Cf{Bf}}}}}}{{{f{b{Cd{c}}}}{f{b{Ab{A`}}}}}{{An{Adj}}}{{Cb{}{{Cf{Bh}}}}}}{c{{An{e}}}{}{}}0{{}{{An{c}}}{}}0{fBl}0{{{f{bc}}{f{b{Ab{A`}}}}}Ad{hB`}}{{{f{{Ab{Bf}}}}{f{b{Ab{A`}}}}}{{D`{CnCn}}}}{{{f{{Ab{Bh}}}}{f{b{Ab{A`}}}}}{{D`{CnCn}}}}{{{f{bc}}}Bf{hB`}}{{{f{bc}}}Bh{hB`}}0{{{f{{Ab{A`}}}}{f{b{Ab{Bf}}}}}Ad}{{{f{{Ab{A`}}}}{f{b{Ab{Bh}}}}}Ad}","D":"Fh","p":[[0,"mut"],[10,"CryptoRngCore",0],[1,"reference"],[10,"RngCore",0],[5,"Error",0,90],[8,"NonZeroU32",91],[6,"Option",92],[1,"u8"],[1,"slice"],[1,"unit"],[5,"Formatter",93],[8,"Result",93],[17,"Seed"],[10,"SeedableRng",0],[6,"Result",94],[10,"Sized",95],[10,"Default",96],[10,"AsMut",97],[1,"u32"],[1,"u64"],[1,"i32"],[5,"TypeId",98],[5,"BlockRng",31],[10,"Clone",99],[10,"BlockRngCore",31],[5,"BlockRng64",31],[17,"Item"],[10,"Debug",93],[17,"Results"],[10,"AsRef",97],[1,"usize"],[1,"tuple"]],"r":[[3,90]],"b":[[14,"impl-Display-for-Error"],[15,"impl-Debug-for-Error"]],"c":"OjAAAAAAAAA=","e":"OzAAAAEAACYACAALAAEADwACAB0AAgAlAAgAMAADADYAAwBDAAMASQAJAA=="}],["rand_mt",{"t":"TTIFFIGPPNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN","n":["DEFAULT_SEED","","Mt","Mt19937GenRand32","Mt19937GenRand64","Mt64","RecoverRngError","TooFewSamples","TooManySamples","borrow","","","borrow_mut","","","clone","","","clone_into","","","clone_to_uninit","","","cmp","","default","","eq","","","fill_bytes","","","","fmt","","","","from","","","","","","","","","from_seed","","hash","","","into","","","new","","new_unseeded","","new_with_key","","next_u32","","","","next_u64","","","","partial_cmp","","recover","","reseed","","reseed_with_key","","to_owned","","","to_string","try_fill_bytes","","try_from","","","","","try_into","","","type_id","",""],"q":[[0,"rand_mt"],[95,"rand_mt::mt"],[96,"rand_mt::mt64"],[97,"core::cmp"],[98,"core::fmt"],[99,"core::hash"],[100,"core::iter::traits::collect"],[101,"core::option"],[102,"core::result"],[103,"alloc::string"],[104,"rand_core::error"],[105,"core::any"]],"i":"fh`````j021021021021021021212102211210022221111021210210212121221122112121212121002122110210210","f":"`````````{b{{b{c}}}{}}00{{{b{d}}}{{b{dc}}}{}}00{{{b{f}}}f}{{{b{h}}}h}{{{b{j}}}j}{{b{b{dc}}}l{}}00{bl}00{{{b{f}}{b{f}}}n}{{{b{h}}{b{h}}}n}{{}f}{{}h}{{{b{f}}{b{f}}}A`}{{{b{h}}{b{h}}}A`}{{{b{j}}{b{j}}}A`}{{{b{df}}{b{d{Ad{Ab}}}}}l}0{{{b{dh}}{b{d{Ad{Ab}}}}}l}0{{{b{f}}{b{dAf}}}Ah}{{{b{h}}{b{dAf}}}Ah}{{{b{j}}{b{dAf}}}Ah}0{Ajf}{{{Al{Aj}}}f}{cc{}}{{{Al{Ab}}}f}1{{{Al{An}}}h}{Anh}{{{Al{Ab}}}h}4{cf{}}{ch{}}{{{b{f}}{b{dc}}}lB`}{{{b{h}}{b{dc}}}lB`}{{{b{j}}{b{dc}}}lB`}{{}c{}}00<7{{}f}{{}h}{cf{{Bd{}{{Bb{Aj}}}}}}{ch{{Bd{}{{Bb{An}}}}}}{{{b{df}}}Aj}0{{{b{dh}}}Aj}0{{{b{df}}}An}0{{{b{dh}}}An}0{{{b{f}}{b{f}}}{{Bf{n}}}}{{{b{h}}{b{h}}}{{Bf{n}}}}{c{{Bh{fj}}}{{Bd{}{{Bb{Aj}}}}}}{c{{Bh{hj}}}{{Bd{}{{Bb{An}}}}}}{{{b{df}}Aj}l}{{{b{dh}}An}l}{{{b{df}}c}l{{Bd{}{{Bb{Aj}}}}}}{{{b{dh}}c}l{{Bd{}{{Bb{An}}}}}}{bc{}}00{bBj}{{{b{df}}{b{d{Ad{Ab}}}}}{{Bh{lBl}}}}{{{b{dh}}{b{d{Ad{Ab}}}}}{{Bh{lBl}}}}{{{b{{Ad{Aj}}}}}{{Bh{fc}}}{}}{c{{Bh{e}}}{}{}}0{{{b{{Ad{An}}}}}{{Bh{hc}}}{}}1{{}{{Bh{c}}}{}}00{bBn}00","D":"Fl","p":[[1,"reference"],[0,"mut"],[5,"Mt19937GenRand32",0,95],[5,"Mt19937GenRand64",0,96],[6,"RecoverRngError",0],[1,"unit"],[6,"Ordering",97],[1,"bool"],[1,"u8"],[1,"slice"],[5,"Formatter",98],[8,"Result",98],[1,"u32"],[1,"array"],[1,"u64"],[10,"Hasher",99],[17,"Item"],[10,"IntoIterator",100],[6,"Option",101],[6,"Result",102],[5,"String",103],[5,"Error",104],[5,"TypeId",105]],"r":[[3,95],[4,96]],"b":[[31,"impl-RngCore-for-Mt19937GenRand32"],[32,"impl-Mt19937GenRand32"],[33,"impl-RngCore-for-Mt19937GenRand64"],[34,"impl-Mt19937GenRand64"],[37,"impl-Debug-for-RecoverRngError"],[38,"impl-Display-for-RecoverRngError"],[39,"impl-From%3Cu32%3E-for-Mt19937GenRand32"],[40,"impl-From%3C%5Bu32;+N%5D%3E-for-Mt19937GenRand32"],[42,"impl-From%3C%5Bu8;+4%5D%3E-for-Mt19937GenRand32"],[44,"impl-From%3C%5Bu64;+NN%5D%3E-for-Mt19937GenRand64"],[45,"impl-From%3Cu64%3E-for-Mt19937GenRand64"],[46,"impl-From%3C%5Bu8;+8%5D%3E-for-Mt19937GenRand64"],[62,"impl-Mt19937GenRand32"],[63,"impl-RngCore-for-Mt19937GenRand32"],[64,"impl-Mt19937GenRand64"],[65,"impl-RngCore-for-Mt19937GenRand64"],[66,"impl-Mt19937GenRand32"],[67,"impl-RngCore-for-Mt19937GenRand32"],[68,"impl-RngCore-for-Mt19937GenRand64"],[69,"impl-Mt19937GenRand64"]],"c":"OjAAAAAAAAA=","e":"OzAAAAEAACkACAAKABAAHQACACQAAwAzAAIARwABAE8AAwBWAAEAWQAGAA=="}]]')); +if (typeof exports !== 'undefined') exports.searchIndex = searchIndex; +else if (window.initSearch) window.initSearch(searchIndex); +//{"start":39,"fragment_lengths":[3655,3370]} \ No newline at end of file diff --git a/search.desc/rand_core/rand_core-desc-0-.js b/search.desc/rand_core/rand_core-desc-0-.js new file mode 100644 index 000000000..d266e7434 --- /dev/null +++ b/search.desc/rand_core/rand_core-desc-0-.js @@ -0,0 +1 @@ +searchState.loadedDescShard("rand_core", 0, "Random number generation traits\nCodes at or above this point can be used by users to …\nA marker trait used to indicate that an RngCore or …\nAn extension trait that is automatically implemented for …\nError type of random number generators\nCodes below this point represent OS Errors (i.e. positive …\nThe core of a random number generator.\nSeed type, which is restricted to types …\nA random number generator that can be explicitly seeded.\nUpcast to an RngCore trait object.\nThe BlockRngCore trait and implementation helpers\nRetrieve the error code, if any.\nFill dest with random data.\nReturns the argument unchanged.\nCreate a new PRNG seeded from another Rng.\nCreate a new PRNG using the given seed.\nHelper functions for implementing RngCore functions.\nCalls U::from(self).\nLittle-Endian utilities\nReturn the next random u32.\nReturn the next random u64.\nExtract the raw OS error code (if this error came from the …\nCreate a new PRNG using a u64 seed.\nFill dest entirely with random data.\nA wrapper type implementing RngCore for some type …\nA wrapper type implementing RngCore for some type …\nA trait for RNGs which do not generate random numbers …\nResults element type, e.g. u32.\nResults type. This is the ‘block’ an RNG implementing …\nThe core part of the RNG, implementing the generate …\nThe core part of the RNG, implementing the generate …\nReturns the argument unchanged.\nReturns the argument unchanged.\nGenerate a new block of results.\nGenerate a new set of results immediately, setting the …\nGenerate a new set of results immediately, setting the …\nGet the index into the result buffer.\nGet the index into the result buffer.\nCalls U::from(self).\nCalls U::from(self).\nCreate a new BlockRng from an existing RNG implementing …\nCreate a new BlockRng from an existing RNG implementing …\nReset the number of available results. This will force a …\nReset the number of available results. This will force a …\nImplement fill_bytes via next_u64 and next_u32, …\nImplement fill_bytes by reading chunks from the output …\nImplement fill_bytes by reading chunks from the output …\nImplement next_u32 via fill_bytes, little-endian order.\nImplement next_u64 via fill_bytes, little-endian order.\nImplement next_u64 via next_u32, little-endian order.\nReads unsigned 32 bit integers from src into dst.\nReads unsigned 64 bit integers from src into dst.") \ No newline at end of file diff --git a/search.desc/rand_mt/rand_mt-desc-0-.js b/search.desc/rand_mt/rand_mt-desc-0-.js new file mode 100644 index 000000000..bcea1d585 --- /dev/null +++ b/search.desc/rand_mt/rand_mt-desc-0-.js @@ -0,0 +1 @@ +searchState.loadedDescShard("rand_mt", 0, "Mersenne Twister random number generators.\nDefault seed used by Mt19937GenRand32::new_unseeded.\nDefault seed used by Mt19937GenRand64::new_unseeded.\nA type alias for Mt19937GenRand32, 32-bit Mersenne Twister.\nThe 32-bit flavor of the Mersenne Twister pseudorandom …\nThe 64-bit flavor of the Mersenne Twister pseudorandom …\nA type alias for Mt19937GenRand64, 64-bit Mersenne Twister.\nError returned from fallible Mersenne Twister recovery …\nAttempted to recover an RNG with too many samples.\nAttempted to recover an RNG with too few samples.\nReturn a new Mt19937GenRand32 with the default seed.\nReturn a new Mt19937GenRand64 with the default seed.\nFill a buffer with bytes generated from the RNG.\nFill a buffer with bytes generated from the RNG.\nFill a buffer with bytes generated from the RNG.\nFill a buffer with bytes generated from the RNG.\nConstruct a Mersenne Twister RNG from a u32 seed.\nRecover the internal state of a Mersenne Twister using the …\nReturns the argument unchanged.\nConstruct a Mersenne Twister RNG from 4 bytes.\nReturns the argument unchanged.\nRecover the internal state of a Mersenne Twister using the …\nConstruct a Mersenne Twister RNG from a u64 seed.\nConstruct a Mersenne Twister RNG from 8 bytes.\nReturns the argument unchanged.\nReseed from a little endian encoded u32.\nReseed from a little endian encoded u64.\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCreate a new Mersenne Twister random number generator …\nCreate a new Mersenne Twister random number generator …\nCreate a new Mersenne Twister random number generator …\nCreate a new Mersenne Twister random number generator …\nCreate a new Mersenne Twister random number generator …\nCreate a new Mersenne Twister random number generator …\nGenerate next u32 output.\nGenerate next u32 output.\nGenerate next u32 output.\nGenerate next u32 output.\nGenerate next u64 output.\nGenerate next u64 output.\nGenerate next u64 output.\nGenerate next u64 output.\nAttempt to recover the internal state of a Mersenne …\nAttempt to recover the internal state of a Mersenne …\nReseed a Mersenne Twister from a single u32.\nReseed a Mersenne Twister from a single u64.\nReseed a Mersenne Twister from am iterator of u32s.\nReseed a Mersenne Twister from am iterator of u64s.\nFill a buffer with bytes generated from the RNG.\nFill a buffer with bytes generated from the RNG.\nAttempt to recover the internal state of a Mersenne …\nAttempt to recover the internal state of a Mersenne …") \ No newline at end of file diff --git a/settings.html b/settings.html new file mode 100644 index 000000000..853b591c7 --- /dev/null +++ b/settings.html @@ -0,0 +1 @@ +Settings

Rustdoc settings

Back
\ No newline at end of file diff --git a/src-files.js b/src-files.js new file mode 100644 index 000000000..f59c0d9c5 --- /dev/null +++ b/src-files.js @@ -0,0 +1,3 @@ +var srcIndex = new Map(JSON.parse('[["rand_core",["",[],["block.rs","error.rs","impls.rs","le.rs","lib.rs"]]],["rand_mt",["",[["mt",[],["rand.rs"]],["mt64",[],["rand.rs"]]],["lib.rs","mt.rs","mt64.rs"]]]]')); +createSrcSidebar(); +//{"start":36,"fragment_lengths":[73,94]} \ No newline at end of file diff --git a/src/rand_core/block.rs.html b/src/rand_core/block.rs.html new file mode 100644 index 000000000..c1d6fb50c --- /dev/null +++ b/src/rand_core/block.rs.html @@ -0,0 +1,1079 @@ +block.rs - source

rand_core/
block.rs

+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
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
+224
+225
+226
+227
+228
+229
+230
+231
+232
+233
+234
+235
+236
+237
+238
+239
+240
+241
+242
+243
+244
+245
+246
+247
+248
+249
+250
+251
+252
+253
+254
+255
+256
+257
+258
+259
+260
+261
+262
+263
+264
+265
+266
+267
+268
+269
+270
+271
+272
+273
+274
+275
+276
+277
+278
+279
+280
+281
+282
+283
+284
+285
+286
+287
+288
+289
+290
+291
+292
+293
+294
+295
+296
+297
+298
+299
+300
+301
+302
+303
+304
+305
+306
+307
+308
+309
+310
+311
+312
+313
+314
+315
+316
+317
+318
+319
+320
+321
+322
+323
+324
+325
+326
+327
+328
+329
+330
+331
+332
+333
+334
+335
+336
+337
+338
+339
+340
+341
+342
+343
+344
+345
+346
+347
+348
+349
+350
+351
+352
+353
+354
+355
+356
+357
+358
+359
+360
+361
+362
+363
+364
+365
+366
+367
+368
+369
+370
+371
+372
+373
+374
+375
+376
+377
+378
+379
+380
+381
+382
+383
+384
+385
+386
+387
+388
+389
+390
+391
+392
+393
+394
+395
+396
+397
+398
+399
+400
+401
+402
+403
+404
+405
+406
+407
+408
+409
+410
+411
+412
+413
+414
+415
+416
+417
+418
+419
+420
+421
+422
+423
+424
+425
+426
+427
+428
+429
+430
+431
+432
+433
+434
+435
+436
+437
+438
+439
+440
+441
+442
+443
+444
+445
+446
+447
+448
+449
+450
+451
+452
+453
+454
+455
+456
+457
+458
+459
+460
+461
+462
+463
+464
+465
+466
+467
+468
+469
+470
+471
+472
+473
+474
+475
+476
+477
+478
+479
+480
+481
+482
+483
+484
+485
+486
+487
+488
+489
+490
+491
+492
+493
+494
+495
+496
+497
+498
+499
+500
+501
+502
+503
+504
+505
+506
+507
+508
+509
+510
+511
+512
+513
+514
+515
+516
+517
+518
+519
+520
+521
+522
+523
+524
+525
+526
+527
+528
+529
+530
+531
+532
+533
+534
+535
+536
+537
+538
+539
// Copyright 2018 Developers of the Rand project.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+//! The `BlockRngCore` trait and implementation helpers
+//!
+//! The [`BlockRngCore`] trait exists to assist in the implementation of RNGs
+//! which generate a block of data in a cache instead of returning generated
+//! values directly.
+//!
+//! Usage of this trait is optional, but provides two advantages:
+//! implementations only need to concern themselves with generation of the
+//! block, not the various [`RngCore`] methods (especially [`fill_bytes`], where
+//! the optimal implementations are not trivial), and this allows
+//! `ReseedingRng` (see [`rand`](https://docs.rs/rand) crate) perform periodic
+//! reseeding with very low overhead.
+//!
+//! # Example
+//!
+//! ```no_run
+//! use rand_core::{RngCore, SeedableRng};
+//! use rand_core::block::{BlockRngCore, BlockRng};
+//!
+//! struct MyRngCore;
+//!
+//! impl BlockRngCore for MyRngCore {
+//!     type Item = u32;
+//!     type Results = [u32; 16];
+//!
+//!     fn generate(&mut self, results: &mut Self::Results) {
+//!         unimplemented!()
+//!     }
+//! }
+//!
+//! impl SeedableRng for MyRngCore {
+//!     type Seed = [u8; 32];
+//!     fn from_seed(seed: Self::Seed) -> Self {
+//!         unimplemented!()
+//!     }
+//! }
+//!
+//! // optionally, also implement CryptoRng for MyRngCore
+//!
+//! // Final RNG.
+//! let mut rng = BlockRng::<MyRngCore>::seed_from_u64(0);
+//! println!("First value: {}", rng.next_u32());
+//! ```
+//!
+//! [`BlockRngCore`]: crate::block::BlockRngCore
+//! [`fill_bytes`]: RngCore::fill_bytes
+
+use crate::impls::{fill_via_u32_chunks, fill_via_u64_chunks};
+use crate::{CryptoRng, Error, RngCore, SeedableRng};
+use core::convert::AsRef;
+use core::fmt;
+#[cfg(feature = "serde1")]
+use serde::{Deserialize, Serialize};
+
+/// A trait for RNGs which do not generate random numbers individually, but in
+/// blocks (typically `[u32; N]`). This technique is commonly used by
+/// cryptographic RNGs to improve performance.
+///
+/// See the [module][crate::block] documentation for details.
+pub trait BlockRngCore {
+    /// Results element type, e.g. `u32`.
+    type Item;
+
+    /// Results type. This is the 'block' an RNG implementing `BlockRngCore`
+    /// generates, which will usually be an array like `[u32; 16]`.
+    type Results: AsRef<[Self::Item]> + AsMut<[Self::Item]> + Default;
+
+    /// Generate a new block of results.
+    fn generate(&mut self, results: &mut Self::Results);
+}
+
+/// A wrapper type implementing [`RngCore`] for some type implementing
+/// [`BlockRngCore`] with `u32` array buffer; i.e. this can be used to implement
+/// a full RNG from just a `generate` function.
+///
+/// The `core` field may be accessed directly but the results buffer may not.
+/// PRNG implementations can simply use a type alias
+/// (`pub type MyRng = BlockRng<MyRngCore>;`) but might prefer to use a
+/// wrapper type (`pub struct MyRng(BlockRng<MyRngCore>);`); the latter must
+/// re-implement `RngCore` but hides the implementation details and allows
+/// extra functionality to be defined on the RNG
+/// (e.g. `impl MyRng { fn set_stream(...){...} }`).
+///
+/// `BlockRng` has heavily optimized implementations of the [`RngCore`] methods
+/// reading values from the results buffer, as well as
+/// calling [`BlockRngCore::generate`] directly on the output array when
+/// [`fill_bytes`] / [`try_fill_bytes`] is called on a large array. These methods
+/// also handle the bookkeeping of when to generate a new batch of values.
+///
+/// No whole generated `u32` values are thrown away and all values are consumed
+/// in-order. [`next_u32`] simply takes the next available `u32` value.
+/// [`next_u64`] is implemented by combining two `u32` values, least
+/// significant first. [`fill_bytes`] and [`try_fill_bytes`] consume a whole
+/// number of `u32` values, converting each `u32` to a byte slice in
+/// little-endian order. If the requested byte length is not a multiple of 4,
+/// some bytes will be discarded.
+///
+/// See also [`BlockRng64`] which uses `u64` array buffers. Currently there is
+/// no direct support for other buffer types.
+///
+/// For easy initialization `BlockRng` also implements [`SeedableRng`].
+///
+/// [`next_u32`]: RngCore::next_u32
+/// [`next_u64`]: RngCore::next_u64
+/// [`fill_bytes`]: RngCore::fill_bytes
+/// [`try_fill_bytes`]: RngCore::try_fill_bytes
+#[derive(Clone)]
+#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[cfg_attr(
+    feature = "serde1",
+    serde(
+        bound = "for<'x> R: Serialize + Deserialize<'x> + Sized, for<'x> R::Results: Serialize + Deserialize<'x>"
+    )
+)]
+pub struct BlockRng<R: BlockRngCore + ?Sized> {
+    results: R::Results,
+    index: usize,
+    /// The *core* part of the RNG, implementing the `generate` function.
+    pub core: R,
+}
+
+// Custom Debug implementation that does not expose the contents of `results`.
+impl<R: BlockRngCore + fmt::Debug> fmt::Debug for BlockRng<R> {
+    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+        fmt.debug_struct("BlockRng")
+            .field("core", &self.core)
+            .field("result_len", &self.results.as_ref().len())
+            .field("index", &self.index)
+            .finish()
+    }
+}
+
+impl<R: BlockRngCore> BlockRng<R> {
+    /// Create a new `BlockRng` from an existing RNG implementing
+    /// `BlockRngCore`. Results will be generated on first use.
+    #[inline]
+    pub fn new(core: R) -> BlockRng<R> {
+        let results_empty = R::Results::default();
+        BlockRng {
+            core,
+            index: results_empty.as_ref().len(),
+            results: results_empty,
+        }
+    }
+
+    /// Get the index into the result buffer.
+    ///
+    /// If this is equal to or larger than the size of the result buffer then
+    /// the buffer is "empty" and `generate()` must be called to produce new
+    /// results.
+    #[inline(always)]
+    pub fn index(&self) -> usize {
+        self.index
+    }
+
+    /// Reset the number of available results.
+    /// This will force a new set of results to be generated on next use.
+    #[inline]
+    pub fn reset(&mut self) {
+        self.index = self.results.as_ref().len();
+    }
+
+    /// Generate a new set of results immediately, setting the index to the
+    /// given value.
+    #[inline]
+    pub fn generate_and_set(&mut self, index: usize) {
+        assert!(index < self.results.as_ref().len());
+        self.core.generate(&mut self.results);
+        self.index = index;
+    }
+}
+
+impl<R: BlockRngCore<Item = u32>> RngCore for BlockRng<R>
+where
+    <R as BlockRngCore>::Results: AsRef<[u32]> + AsMut<[u32]>,
+{
+    #[inline]
+    fn next_u32(&mut self) -> u32 {
+        if self.index >= self.results.as_ref().len() {
+            self.generate_and_set(0);
+        }
+
+        let value = self.results.as_ref()[self.index];
+        self.index += 1;
+        value
+    }
+
+    #[inline]
+    fn next_u64(&mut self) -> u64 {
+        let read_u64 = |results: &[u32], index| {
+            let data = &results[index..=index + 1];
+            u64::from(data[1]) << 32 | u64::from(data[0])
+        };
+
+        let len = self.results.as_ref().len();
+
+        let index = self.index;
+        if index < len - 1 {
+            self.index += 2;
+            // Read an u64 from the current index
+            read_u64(self.results.as_ref(), index)
+        } else if index >= len {
+            self.generate_and_set(2);
+            read_u64(self.results.as_ref(), 0)
+        } else {
+            let x = u64::from(self.results.as_ref()[len - 1]);
+            self.generate_and_set(1);
+            let y = u64::from(self.results.as_ref()[0]);
+            (y << 32) | x
+        }
+    }
+
+    #[inline]
+    fn fill_bytes(&mut self, dest: &mut [u8]) {
+        let mut read_len = 0;
+        while read_len < dest.len() {
+            if self.index >= self.results.as_ref().len() {
+                self.generate_and_set(0);
+            }
+            let (consumed_u32, filled_u8) =
+                fill_via_u32_chunks(&self.results.as_ref()[self.index..], &mut dest[read_len..]);
+
+            self.index += consumed_u32;
+            read_len += filled_u8;
+        }
+    }
+
+    #[inline(always)]
+    fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
+        self.fill_bytes(dest);
+        Ok(())
+    }
+}
+
+impl<R: BlockRngCore + SeedableRng> SeedableRng for BlockRng<R> {
+    type Seed = R::Seed;
+
+    #[inline(always)]
+    fn from_seed(seed: Self::Seed) -> Self {
+        Self::new(R::from_seed(seed))
+    }
+
+    #[inline(always)]
+    fn seed_from_u64(seed: u64) -> Self {
+        Self::new(R::seed_from_u64(seed))
+    }
+
+    #[inline(always)]
+    fn from_rng<S: RngCore>(rng: S) -> Result<Self, Error> {
+        Ok(Self::new(R::from_rng(rng)?))
+    }
+}
+
+/// A wrapper type implementing [`RngCore`] for some type implementing
+/// [`BlockRngCore`] with `u64` array buffer; i.e. this can be used to implement
+/// a full RNG from just a `generate` function.
+///
+/// This is similar to [`BlockRng`], but specialized for algorithms that operate
+/// on `u64` values.
+///
+/// No whole generated `u64` values are thrown away and all values are consumed
+/// in-order. [`next_u64`] simply takes the next available `u64` value.
+/// [`next_u32`] is however a bit special: half of a `u64` is consumed, leaving
+/// the other half in the buffer. If the next function called is [`next_u32`]
+/// then the other half is then consumed, however both [`next_u64`] and
+/// [`fill_bytes`] discard the rest of any half-consumed `u64`s when called.
+///
+/// [`fill_bytes`] and [`try_fill_bytes`] consume a whole number of `u64`
+/// values. If the requested length is not a multiple of 8, some bytes will be
+/// discarded.
+///
+/// [`next_u32`]: RngCore::next_u32
+/// [`next_u64`]: RngCore::next_u64
+/// [`fill_bytes`]: RngCore::fill_bytes
+/// [`try_fill_bytes`]: RngCore::try_fill_bytes
+#[derive(Clone)]
+#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+pub struct BlockRng64<R: BlockRngCore + ?Sized> {
+    results: R::Results,
+    index: usize,
+    half_used: bool, // true if only half of the previous result is used
+    /// The *core* part of the RNG, implementing the `generate` function.
+    pub core: R,
+}
+
+// Custom Debug implementation that does not expose the contents of `results`.
+impl<R: BlockRngCore + fmt::Debug> fmt::Debug for BlockRng64<R> {
+    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+        fmt.debug_struct("BlockRng64")
+            .field("core", &self.core)
+            .field("result_len", &self.results.as_ref().len())
+            .field("index", &self.index)
+            .field("half_used", &self.half_used)
+            .finish()
+    }
+}
+
+impl<R: BlockRngCore> BlockRng64<R> {
+    /// Create a new `BlockRng` from an existing RNG implementing
+    /// `BlockRngCore`. Results will be generated on first use.
+    #[inline]
+    pub fn new(core: R) -> BlockRng64<R> {
+        let results_empty = R::Results::default();
+        BlockRng64 {
+            core,
+            index: results_empty.as_ref().len(),
+            half_used: false,
+            results: results_empty,
+        }
+    }
+
+    /// Get the index into the result buffer.
+    ///
+    /// If this is equal to or larger than the size of the result buffer then
+    /// the buffer is "empty" and `generate()` must be called to produce new
+    /// results.
+    #[inline(always)]
+    pub fn index(&self) -> usize {
+        self.index
+    }
+
+    /// Reset the number of available results.
+    /// This will force a new set of results to be generated on next use.
+    #[inline]
+    pub fn reset(&mut self) {
+        self.index = self.results.as_ref().len();
+        self.half_used = false;
+    }
+
+    /// Generate a new set of results immediately, setting the index to the
+    /// given value.
+    #[inline]
+    pub fn generate_and_set(&mut self, index: usize) {
+        assert!(index < self.results.as_ref().len());
+        self.core.generate(&mut self.results);
+        self.index = index;
+        self.half_used = false;
+    }
+}
+
+impl<R: BlockRngCore<Item = u64>> RngCore for BlockRng64<R>
+where
+    <R as BlockRngCore>::Results: AsRef<[u64]> + AsMut<[u64]>,
+{
+    #[inline]
+    fn next_u32(&mut self) -> u32 {
+        let mut index = self.index - self.half_used as usize;
+        if index >= self.results.as_ref().len() {
+            self.core.generate(&mut self.results);
+            self.index = 0;
+            index = 0;
+            // `self.half_used` is by definition `false`
+            self.half_used = false;
+        }
+
+        let shift = 32 * (self.half_used as usize);
+
+        self.half_used = !self.half_used;
+        self.index += self.half_used as usize;
+
+        (self.results.as_ref()[index] >> shift) as u32
+    }
+
+    #[inline]
+    fn next_u64(&mut self) -> u64 {
+        if self.index >= self.results.as_ref().len() {
+            self.core.generate(&mut self.results);
+            self.index = 0;
+        }
+
+        let value = self.results.as_ref()[self.index];
+        self.index += 1;
+        self.half_used = false;
+        value
+    }
+
+    #[inline]
+    fn fill_bytes(&mut self, dest: &mut [u8]) {
+        let mut read_len = 0;
+        self.half_used = false;
+        while read_len < dest.len() {
+            if self.index as usize >= self.results.as_ref().len() {
+                self.core.generate(&mut self.results);
+                self.index = 0;
+            }
+
+            let (consumed_u64, filled_u8) = fill_via_u64_chunks(
+                &self.results.as_ref()[self.index as usize..],
+                &mut dest[read_len..],
+            );
+
+            self.index += consumed_u64;
+            read_len += filled_u8;
+        }
+    }
+
+    #[inline(always)]
+    fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
+        self.fill_bytes(dest);
+        Ok(())
+    }
+}
+
+impl<R: BlockRngCore + SeedableRng> SeedableRng for BlockRng64<R> {
+    type Seed = R::Seed;
+
+    #[inline(always)]
+    fn from_seed(seed: Self::Seed) -> Self {
+        Self::new(R::from_seed(seed))
+    }
+
+    #[inline(always)]
+    fn seed_from_u64(seed: u64) -> Self {
+        Self::new(R::seed_from_u64(seed))
+    }
+
+    #[inline(always)]
+    fn from_rng<S: RngCore>(rng: S) -> Result<Self, Error> {
+        Ok(Self::new(R::from_rng(rng)?))
+    }
+}
+
+impl<R: BlockRngCore + CryptoRng> CryptoRng for BlockRng<R> {}
+
+#[cfg(test)]
+mod test {
+    use crate::{SeedableRng, RngCore};
+    use crate::block::{BlockRng, BlockRng64, BlockRngCore};
+
+    #[derive(Debug, Clone)]
+    struct DummyRng {
+        counter: u32,
+    }
+
+    impl BlockRngCore for DummyRng {
+        type Item = u32;
+
+        type Results = [u32; 16];
+
+        fn generate(&mut self, results: &mut Self::Results) {
+            for r in results {
+                *r = self.counter;
+                self.counter = self.counter.wrapping_add(3511615421);
+            }
+        }
+    }
+
+    impl SeedableRng for DummyRng {
+        type Seed = [u8; 4];
+
+        fn from_seed(seed: Self::Seed) -> Self {
+            DummyRng { counter: u32::from_le_bytes(seed) }
+        }
+    }
+
+    #[test]
+    fn blockrng_next_u32_vs_next_u64() {
+        let mut rng1 = BlockRng::<DummyRng>::from_seed([1, 2, 3, 4]);
+        let mut rng2 = rng1.clone();
+        let mut rng3 = rng1.clone();
+
+        let mut a = [0; 16];
+        (&mut a[..4]).copy_from_slice(&rng1.next_u32().to_le_bytes());
+        (&mut a[4..12]).copy_from_slice(&rng1.next_u64().to_le_bytes());
+        (&mut a[12..]).copy_from_slice(&rng1.next_u32().to_le_bytes());
+
+        let mut b = [0; 16];
+        (&mut b[..4]).copy_from_slice(&rng2.next_u32().to_le_bytes());
+        (&mut b[4..8]).copy_from_slice(&rng2.next_u32().to_le_bytes());
+        (&mut b[8..]).copy_from_slice(&rng2.next_u64().to_le_bytes());
+        assert_eq!(a, b);
+
+        let mut c = [0; 16];
+        (&mut c[..8]).copy_from_slice(&rng3.next_u64().to_le_bytes());
+        (&mut c[8..12]).copy_from_slice(&rng3.next_u32().to_le_bytes());
+        (&mut c[12..]).copy_from_slice(&rng3.next_u32().to_le_bytes());
+        assert_eq!(a, c);
+    }
+
+    #[derive(Debug, Clone)]
+    struct DummyRng64 {
+        counter: u64,
+    }
+
+    impl BlockRngCore for DummyRng64 {
+        type Item = u64;
+
+        type Results = [u64; 8];
+
+        fn generate(&mut self, results: &mut Self::Results) {
+            for r in results {
+                *r = self.counter;
+                self.counter = self.counter.wrapping_add(2781463553396133981);
+            }
+        }
+    }
+
+    impl SeedableRng for DummyRng64 {
+        type Seed = [u8; 8];
+
+        fn from_seed(seed: Self::Seed) -> Self {
+            DummyRng64 { counter: u64::from_le_bytes(seed) }
+        }
+    }
+
+    #[test]
+    fn blockrng64_next_u32_vs_next_u64() {
+        let mut rng1 = BlockRng64::<DummyRng64>::from_seed([1, 2, 3, 4, 5, 6, 7, 8]);
+        let mut rng2 = rng1.clone();
+        let mut rng3 = rng1.clone();
+
+        let mut a = [0; 16];
+        (&mut a[..4]).copy_from_slice(&rng1.next_u32().to_le_bytes());
+        (&mut a[4..12]).copy_from_slice(&rng1.next_u64().to_le_bytes());
+        (&mut a[12..]).copy_from_slice(&rng1.next_u32().to_le_bytes());
+
+        let mut b = [0; 16];
+        (&mut b[..4]).copy_from_slice(&rng2.next_u32().to_le_bytes());
+        (&mut b[4..8]).copy_from_slice(&rng2.next_u32().to_le_bytes());
+        (&mut b[8..]).copy_from_slice(&rng2.next_u64().to_le_bytes());
+        assert_ne!(a, b);
+        assert_eq!(&a[..4], &b[..4]);
+        assert_eq!(&a[4..12], &b[8..]);
+
+        let mut c = [0; 16];
+        (&mut c[..8]).copy_from_slice(&rng3.next_u64().to_le_bytes());
+        (&mut c[8..12]).copy_from_slice(&rng3.next_u32().to_le_bytes());
+        (&mut c[12..]).copy_from_slice(&rng3.next_u32().to_le_bytes());
+        assert_eq!(b, c);
+    }
+}
+
\ No newline at end of file diff --git a/src/rand_core/error.rs.html b/src/rand_core/error.rs.html new file mode 100644 index 000000000..cde6c5f85 --- /dev/null +++ b/src/rand_core/error.rs.html @@ -0,0 +1,457 @@ +error.rs - source

rand_core/
error.rs

+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
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
+224
+225
+226
+227
+228
// Copyright 2018 Developers of the Rand project.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+//! Error types
+
+use core::fmt;
+use core::num::NonZeroU32;
+
+#[cfg(feature = "std")] use std::boxed::Box;
+
+/// Error type of random number generators
+///
+/// In order to be compatible with `std` and `no_std`, this type has two
+/// possible implementations: with `std` a boxed `Error` trait object is stored,
+/// while with `no_std` we merely store an error code.
+pub struct Error {
+    #[cfg(feature = "std")]
+    inner: Box<dyn std::error::Error + Send + Sync + 'static>,
+    #[cfg(not(feature = "std"))]
+    code: NonZeroU32,
+}
+
+impl Error {
+    /// Codes at or above this point can be used by users to define their own
+    /// custom errors.
+    ///
+    /// This has a fixed value of `(1 << 31) + (1 << 30) = 0xC000_0000`,
+    /// therefore the number of values available for custom codes is `1 << 30`.
+    ///
+    /// This is identical to [`getrandom::Error::CUSTOM_START`](https://docs.rs/getrandom/latest/getrandom/struct.Error.html#associatedconstant.CUSTOM_START).
+    pub const CUSTOM_START: u32 = (1 << 31) + (1 << 30);
+    /// Codes below this point represent OS Errors (i.e. positive i32 values).
+    /// Codes at or above this point, but below [`Error::CUSTOM_START`] are
+    /// reserved for use by the `rand` and `getrandom` crates.
+    ///
+    /// This is identical to [`getrandom::Error::INTERNAL_START`](https://docs.rs/getrandom/latest/getrandom/struct.Error.html#associatedconstant.INTERNAL_START).
+    pub const INTERNAL_START: u32 = 1 << 31;
+
+    /// Construct from any type supporting `std::error::Error`
+    ///
+    /// Available only when configured with `std`.
+    ///
+    /// See also `From<NonZeroU32>`, which is available with and without `std`.
+    #[cfg(feature = "std")]
+    #[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]
+    #[inline]
+    pub fn new<E>(err: E) -> Self
+    where
+        E: Into<Box<dyn std::error::Error + Send + Sync + 'static>>,
+    {
+        Error { inner: err.into() }
+    }
+
+    /// Reference the inner error (`std` only)
+    ///
+    /// When configured with `std`, this is a trivial operation and never
+    /// panics. Without `std`, this method is simply unavailable.
+    #[cfg(feature = "std")]
+    #[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]
+    #[inline]
+    pub fn inner(&self) -> &(dyn std::error::Error + Send + Sync + 'static) {
+        &*self.inner
+    }
+
+    /// Unwrap the inner error (`std` only)
+    ///
+    /// When configured with `std`, this is a trivial operation and never
+    /// panics. Without `std`, this method is simply unavailable.
+    #[cfg(feature = "std")]
+    #[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]
+    #[inline]
+    pub fn take_inner(self) -> Box<dyn std::error::Error + Send + Sync + 'static> {
+        self.inner
+    }
+
+    /// Extract the raw OS error code (if this error came from the OS)
+    ///
+    /// This method is identical to `std::io::Error::raw_os_error()`, except
+    /// that it works in `no_std` contexts. If this method returns `None`, the
+    /// error value can still be formatted via the `Display` implementation.
+    #[inline]
+    pub fn raw_os_error(&self) -> Option<i32> {
+        #[cfg(feature = "std")]
+        {
+            if let Some(e) = self.inner.downcast_ref::<std::io::Error>() {
+                return e.raw_os_error();
+            }
+        }
+        match self.code() {
+            Some(code) if u32::from(code) < Self::INTERNAL_START => Some(u32::from(code) as i32),
+            _ => None,
+        }
+    }
+
+    /// Retrieve the error code, if any.
+    ///
+    /// If this `Error` was constructed via `From<NonZeroU32>`, then this method
+    /// will return this `NonZeroU32` code (for `no_std` this is always the
+    /// case). Otherwise, this method will return `None`.
+    #[inline]
+    pub fn code(&self) -> Option<NonZeroU32> {
+        #[cfg(feature = "std")]
+        {
+            self.inner.downcast_ref::<ErrorCode>().map(|c| c.0)
+        }
+        #[cfg(not(feature = "std"))]
+        {
+            Some(self.code)
+        }
+    }
+}
+
+impl fmt::Debug for Error {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        #[cfg(feature = "std")]
+        {
+            write!(f, "Error {{ inner: {:?} }}", self.inner)
+        }
+        #[cfg(all(feature = "getrandom", not(feature = "std")))]
+        {
+            getrandom::Error::from(self.code).fmt(f)
+        }
+        #[cfg(not(feature = "getrandom"))]
+        {
+            write!(f, "Error {{ code: {} }}", self.code)
+        }
+    }
+}
+
+impl fmt::Display for Error {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        #[cfg(feature = "std")]
+        {
+            write!(f, "{}", self.inner)
+        }
+        #[cfg(all(feature = "getrandom", not(feature = "std")))]
+        {
+            getrandom::Error::from(self.code).fmt(f)
+        }
+        #[cfg(not(feature = "getrandom"))]
+        {
+            write!(f, "error code {}", self.code)
+        }
+    }
+}
+
+impl From<NonZeroU32> for Error {
+    #[inline]
+    fn from(code: NonZeroU32) -> Self {
+        #[cfg(feature = "std")]
+        {
+            Error {
+                inner: Box::new(ErrorCode(code)),
+            }
+        }
+        #[cfg(not(feature = "std"))]
+        {
+            Error { code }
+        }
+    }
+}
+
+#[cfg(feature = "getrandom")]
+impl From<getrandom::Error> for Error {
+    #[inline]
+    fn from(error: getrandom::Error) -> Self {
+        #[cfg(feature = "std")]
+        {
+            Error {
+                inner: Box::new(error),
+            }
+        }
+        #[cfg(not(feature = "std"))]
+        {
+            Error { code: error.code() }
+        }
+    }
+}
+
+#[cfg(feature = "std")]
+impl std::error::Error for Error {
+    #[inline]
+    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
+        self.inner.source()
+    }
+}
+
+#[cfg(feature = "std")]
+impl From<Error> for std::io::Error {
+    #[inline]
+    fn from(error: Error) -> Self {
+        if let Some(code) = error.raw_os_error() {
+            std::io::Error::from_raw_os_error(code)
+        } else {
+            std::io::Error::new(std::io::ErrorKind::Other, error)
+        }
+    }
+}
+
+#[cfg(feature = "std")]
+#[derive(Debug, Copy, Clone)]
+struct ErrorCode(NonZeroU32);
+
+#[cfg(feature = "std")]
+impl fmt::Display for ErrorCode {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        write!(f, "error code {}", self.0)
+    }
+}
+
+#[cfg(feature = "std")]
+impl std::error::Error for ErrorCode {}
+
+#[cfg(test)]
+mod test {
+    #[cfg(feature = "getrandom")]
+    #[test]
+    fn test_error_codes() {
+        // Make sure the values are the same as in `getrandom`.
+        assert_eq!(super::Error::CUSTOM_START, getrandom::Error::CUSTOM_START);
+        assert_eq!(super::Error::INTERNAL_START, getrandom::Error::INTERNAL_START);
+    }
+}
+
\ No newline at end of file diff --git a/src/rand_core/impls.rs.html b/src/rand_core/impls.rs.html new file mode 100644 index 000000000..162b1e2aa --- /dev/null +++ b/src/rand_core/impls.rs.html @@ -0,0 +1,415 @@ +impls.rs - source

rand_core/
impls.rs

+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
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
// Copyright 2018 Developers of the Rand project.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+//! Helper functions for implementing `RngCore` functions.
+//!
+//! For cross-platform reproducibility, these functions all use Little Endian:
+//! least-significant part first. For example, `next_u64_via_u32` takes `u32`
+//! values `x, y`, then outputs `(y << 32) | x`. To implement `next_u32`
+//! from `next_u64` in little-endian order, one should use `next_u64() as u32`.
+//!
+//! Byte-swapping (like the std `to_le` functions) is only needed to convert
+//! to/from byte sequences, and since its purpose is reproducibility,
+//! non-reproducible sources (e.g. `OsRng`) need not bother with it.
+
+use crate::RngCore;
+use core::cmp::min;
+
+/// Implement `next_u64` via `next_u32`, little-endian order.
+pub fn next_u64_via_u32<R: RngCore + ?Sized>(rng: &mut R) -> u64 {
+    // Use LE; we explicitly generate one value before the next.
+    let x = u64::from(rng.next_u32());
+    let y = u64::from(rng.next_u32());
+    (y << 32) | x
+}
+
+/// Implement `fill_bytes` via `next_u64` and `next_u32`, little-endian order.
+///
+/// The fastest way to fill a slice is usually to work as long as possible with
+/// integers. That is why this method mostly uses `next_u64`, and only when
+/// there are 4 or less bytes remaining at the end of the slice it uses
+/// `next_u32` once.
+pub fn fill_bytes_via_next<R: RngCore + ?Sized>(rng: &mut R, dest: &mut [u8]) {
+    let mut left = dest;
+    while left.len() >= 8 {
+        let (l, r) = { left }.split_at_mut(8);
+        left = r;
+        let chunk: [u8; 8] = rng.next_u64().to_le_bytes();
+        l.copy_from_slice(&chunk);
+    }
+    let n = left.len();
+    if n > 4 {
+        let chunk: [u8; 8] = rng.next_u64().to_le_bytes();
+        left.copy_from_slice(&chunk[..n]);
+    } else if n > 0 {
+        let chunk: [u8; 4] = rng.next_u32().to_le_bytes();
+        left.copy_from_slice(&chunk[..n]);
+    }
+}
+
+trait Observable: Copy {
+    type Bytes: AsRef<[u8]>;
+    fn to_le_bytes(self) -> Self::Bytes;
+
+    // Contract: observing self is memory-safe (implies no uninitialised padding)
+    fn as_byte_slice(x: &[Self]) -> &[u8];
+}
+impl Observable for u32 {
+    type Bytes = [u8; 4];
+    fn to_le_bytes(self) -> Self::Bytes {
+        self.to_le_bytes()
+    }
+    fn as_byte_slice(x: &[Self]) -> &[u8] {
+        let ptr = x.as_ptr() as *const u8;
+        let len = x.len() * core::mem::size_of::<Self>();
+        unsafe { core::slice::from_raw_parts(ptr, len) }
+    }
+}
+impl Observable for u64 {
+    type Bytes = [u8; 8];
+    fn to_le_bytes(self) -> Self::Bytes {
+        self.to_le_bytes()
+    }
+    fn as_byte_slice(x: &[Self]) -> &[u8] {
+        let ptr = x.as_ptr() as *const u8;
+        let len = x.len() * core::mem::size_of::<Self>();
+        unsafe { core::slice::from_raw_parts(ptr, len) }
+    }
+}
+
+fn fill_via_chunks<T: Observable>(src: &[T], dest: &mut [u8]) -> (usize, usize) {
+    let size = core::mem::size_of::<T>();
+    let byte_len = min(src.len() * size, dest.len());
+    let num_chunks = (byte_len + size - 1) / size;
+
+    if cfg!(target_endian = "little") {
+        // On LE we can do a simple copy, which is 25-50% faster:
+        dest[..byte_len].copy_from_slice(&T::as_byte_slice(&src[..num_chunks])[..byte_len]);
+    } else {
+        // This code is valid on all arches, but slower than the above:
+        let mut i = 0;
+        let mut iter = dest[..byte_len].chunks_exact_mut(size);
+        for chunk in &mut iter {
+            chunk.copy_from_slice(src[i].to_le_bytes().as_ref());
+            i += 1;
+        }
+        let chunk = iter.into_remainder();
+        if !chunk.is_empty() {
+            chunk.copy_from_slice(&src[i].to_le_bytes().as_ref()[..chunk.len()]);
+        }
+    }
+
+    (num_chunks, byte_len)
+}
+
+/// Implement `fill_bytes` by reading chunks from the output buffer of a block
+/// based RNG.
+///
+/// The return values are `(consumed_u32, filled_u8)`.
+///
+/// `filled_u8` is the number of filled bytes in `dest`, which may be less than
+/// the length of `dest`.
+/// `consumed_u32` is the number of words consumed from `src`, which is the same
+/// as `filled_u8 / 4` rounded up.
+///
+/// # Example
+/// (from `IsaacRng`)
+///
+/// ```ignore
+/// fn fill_bytes(&mut self, dest: &mut [u8]) {
+///     let mut read_len = 0;
+///     while read_len < dest.len() {
+///         if self.index >= self.rsl.len() {
+///             self.isaac();
+///         }
+///
+///         let (consumed_u32, filled_u8) =
+///             impls::fill_via_u32_chunks(&mut self.rsl[self.index..],
+///                                        &mut dest[read_len..]);
+///
+///         self.index += consumed_u32;
+///         read_len += filled_u8;
+///     }
+/// }
+/// ```
+pub fn fill_via_u32_chunks(src: &[u32], dest: &mut [u8]) -> (usize, usize) {
+    fill_via_chunks(src, dest)
+}
+
+/// Implement `fill_bytes` by reading chunks from the output buffer of a block
+/// based RNG.
+///
+/// The return values are `(consumed_u64, filled_u8)`.
+/// `filled_u8` is the number of filled bytes in `dest`, which may be less than
+/// the length of `dest`.
+/// `consumed_u64` is the number of words consumed from `src`, which is the same
+/// as `filled_u8 / 8` rounded up.
+///
+/// See `fill_via_u32_chunks` for an example.
+pub fn fill_via_u64_chunks(src: &[u64], dest: &mut [u8]) -> (usize, usize) {
+    fill_via_chunks(src, dest)
+}
+
+/// Implement `next_u32` via `fill_bytes`, little-endian order.
+pub fn next_u32_via_fill<R: RngCore + ?Sized>(rng: &mut R) -> u32 {
+    let mut buf = [0; 4];
+    rng.fill_bytes(&mut buf);
+    u32::from_le_bytes(buf)
+}
+
+/// Implement `next_u64` via `fill_bytes`, little-endian order.
+pub fn next_u64_via_fill<R: RngCore + ?Sized>(rng: &mut R) -> u64 {
+    let mut buf = [0; 8];
+    rng.fill_bytes(&mut buf);
+    u64::from_le_bytes(buf)
+}
+
+#[cfg(test)]
+mod test {
+    use super::*;
+
+    #[test]
+    fn test_fill_via_u32_chunks() {
+        let src = [1, 2, 3];
+        let mut dst = [0u8; 11];
+        assert_eq!(fill_via_u32_chunks(&src, &mut dst), (3, 11));
+        assert_eq!(dst, [1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0]);
+
+        let mut dst = [0u8; 13];
+        assert_eq!(fill_via_u32_chunks(&src, &mut dst), (3, 12));
+        assert_eq!(dst, [1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 0]);
+
+        let mut dst = [0u8; 5];
+        assert_eq!(fill_via_u32_chunks(&src, &mut dst), (2, 5));
+        assert_eq!(dst, [1, 0, 0, 0, 2]);
+    }
+
+    #[test]
+    fn test_fill_via_u64_chunks() {
+        let src = [1, 2];
+        let mut dst = [0u8; 11];
+        assert_eq!(fill_via_u64_chunks(&src, &mut dst), (2, 11));
+        assert_eq!(dst, [1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0]);
+
+        let mut dst = [0u8; 17];
+        assert_eq!(fill_via_u64_chunks(&src, &mut dst), (2, 16));
+        assert_eq!(dst, [1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0]);
+
+        let mut dst = [0u8; 5];
+        assert_eq!(fill_via_u64_chunks(&src, &mut dst), (1, 5));
+        assert_eq!(dst, [1, 0, 0, 0, 0]);
+    }
+}
+
\ No newline at end of file diff --git a/src/rand_core/le.rs.html b/src/rand_core/le.rs.html new file mode 100644 index 000000000..87e7c730b --- /dev/null +++ b/src/rand_core/le.rs.html @@ -0,0 +1,113 @@ +le.rs - source

rand_core/
le.rs

+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
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
// Copyright 2018 Developers of the Rand project.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+//! Little-Endian utilities
+//!
+//! Little-Endian order has been chosen for internal usage; this makes some
+//! useful functions available.
+
+use core::convert::TryInto;
+
+/// Reads unsigned 32 bit integers from `src` into `dst`.
+#[inline]
+pub fn read_u32_into(src: &[u8], dst: &mut [u32]) {
+    assert!(src.len() >= 4 * dst.len());
+    for (out, chunk) in dst.iter_mut().zip(src.chunks_exact(4)) {
+        *out = u32::from_le_bytes(chunk.try_into().unwrap());
+    }
+}
+
+/// Reads unsigned 64 bit integers from `src` into `dst`.
+#[inline]
+pub fn read_u64_into(src: &[u8], dst: &mut [u64]) {
+    assert!(src.len() >= 8 * dst.len());
+    for (out, chunk) in dst.iter_mut().zip(src.chunks_exact(8)) {
+        *out = u64::from_le_bytes(chunk.try_into().unwrap());
+    }
+}
+
+#[test]
+fn test_read() {
+    let bytes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
+
+    let mut buf = [0u32; 4];
+    read_u32_into(&bytes, &mut buf);
+    assert_eq!(buf[0], 0x04030201);
+    assert_eq!(buf[3], 0x100F0E0D);
+
+    let mut buf = [0u32; 3];
+    read_u32_into(&bytes[1..13], &mut buf); // unaligned
+    assert_eq!(buf[0], 0x05040302);
+    assert_eq!(buf[2], 0x0D0C0B0A);
+
+    let mut buf = [0u64; 2];
+    read_u64_into(&bytes, &mut buf);
+    assert_eq!(buf[0], 0x0807060504030201);
+    assert_eq!(buf[1], 0x100F0E0D0C0B0A09);
+
+    let mut buf = [0u64; 1];
+    read_u64_into(&bytes[7..15], &mut buf); // unaligned
+    assert_eq!(buf[0], 0x0F0E0D0C0B0A0908);
+}
+
\ No newline at end of file diff --git a/src/rand_core/lib.rs.html b/src/rand_core/lib.rs.html new file mode 100644 index 000000000..a55870324 --- /dev/null +++ b/src/rand_core/lib.rs.html @@ -0,0 +1,1063 @@ +lib.rs - source

rand_core/
lib.rs

+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
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
+224
+225
+226
+227
+228
+229
+230
+231
+232
+233
+234
+235
+236
+237
+238
+239
+240
+241
+242
+243
+244
+245
+246
+247
+248
+249
+250
+251
+252
+253
+254
+255
+256
+257
+258
+259
+260
+261
+262
+263
+264
+265
+266
+267
+268
+269
+270
+271
+272
+273
+274
+275
+276
+277
+278
+279
+280
+281
+282
+283
+284
+285
+286
+287
+288
+289
+290
+291
+292
+293
+294
+295
+296
+297
+298
+299
+300
+301
+302
+303
+304
+305
+306
+307
+308
+309
+310
+311
+312
+313
+314
+315
+316
+317
+318
+319
+320
+321
+322
+323
+324
+325
+326
+327
+328
+329
+330
+331
+332
+333
+334
+335
+336
+337
+338
+339
+340
+341
+342
+343
+344
+345
+346
+347
+348
+349
+350
+351
+352
+353
+354
+355
+356
+357
+358
+359
+360
+361
+362
+363
+364
+365
+366
+367
+368
+369
+370
+371
+372
+373
+374
+375
+376
+377
+378
+379
+380
+381
+382
+383
+384
+385
+386
+387
+388
+389
+390
+391
+392
+393
+394
+395
+396
+397
+398
+399
+400
+401
+402
+403
+404
+405
+406
+407
+408
+409
+410
+411
+412
+413
+414
+415
+416
+417
+418
+419
+420
+421
+422
+423
+424
+425
+426
+427
+428
+429
+430
+431
+432
+433
+434
+435
+436
+437
+438
+439
+440
+441
+442
+443
+444
+445
+446
+447
+448
+449
+450
+451
+452
+453
+454
+455
+456
+457
+458
+459
+460
+461
+462
+463
+464
+465
+466
+467
+468
+469
+470
+471
+472
+473
+474
+475
+476
+477
+478
+479
+480
+481
+482
+483
+484
+485
+486
+487
+488
+489
+490
+491
+492
+493
+494
+495
+496
+497
+498
+499
+500
+501
+502
+503
+504
+505
+506
+507
+508
+509
+510
+511
+512
+513
+514
+515
+516
+517
+518
+519
+520
+521
+522
+523
+524
+525
+526
+527
+528
+529
+530
+531
// Copyright 2018 Developers of the Rand project.
+// Copyright 2017-2018 The Rust Project Developers.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+//! Random number generation traits
+//!
+//! This crate is mainly of interest to crates publishing implementations of
+//! [`RngCore`]. Other users are encouraged to use the [`rand`] crate instead
+//! which re-exports the main traits and error types.
+//!
+//! [`RngCore`] is the core trait implemented by algorithmic pseudo-random number
+//! generators and external random-number sources.
+//!
+//! [`SeedableRng`] is an extension trait for construction from fixed seeds and
+//! other random number generators.
+//!
+//! [`Error`] is provided for error-handling. It is safe to use in `no_std`
+//! environments.
+//!
+//! The [`impls`] and [`le`] sub-modules include a few small functions to assist
+//! implementation of [`RngCore`].
+//!
+//! [`rand`]: https://docs.rs/rand
+
+#![doc(
+    html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png",
+    html_favicon_url = "https://www.rust-lang.org/favicon.ico",
+    html_root_url = "https://rust-random.github.io/rand/"
+)]
+#![deny(missing_docs)]
+#![deny(missing_debug_implementations)]
+#![doc(test(attr(allow(unused_variables), deny(warnings))))]
+#![cfg_attr(doc_cfg, feature(doc_cfg))]
+#![no_std]
+
+use core::convert::AsMut;
+use core::default::Default;
+
+#[cfg(feature = "std")] extern crate std;
+#[cfg(feature = "alloc")] extern crate alloc;
+#[cfg(feature = "alloc")] use alloc::boxed::Box;
+
+pub use error::Error;
+#[cfg(feature = "getrandom")] pub use os::OsRng;
+
+
+pub mod block;
+mod error;
+pub mod impls;
+pub mod le;
+#[cfg(feature = "getrandom")] mod os;
+
+
+/// The core of a random number generator.
+///
+/// This trait encapsulates the low-level functionality common to all
+/// generators, and is the "back end", to be implemented by generators.
+/// End users should normally use the `Rng` trait from the [`rand`] crate,
+/// which is automatically implemented for every type implementing `RngCore`.
+///
+/// Three different methods for generating random data are provided since the
+/// optimal implementation of each is dependent on the type of generator. There
+/// is no required relationship between the output of each; e.g. many
+/// implementations of [`fill_bytes`] consume a whole number of `u32` or `u64`
+/// values and drop any remaining unused bytes. The same can happen with the
+/// [`next_u32`] and [`next_u64`] methods, implementations may discard some
+/// random bits for efficiency.
+///
+/// The [`try_fill_bytes`] method is a variant of [`fill_bytes`] allowing error
+/// handling; it is not deemed sufficiently useful to add equivalents for
+/// [`next_u32`] or [`next_u64`] since the latter methods are almost always used
+/// with algorithmic generators (PRNGs), which are normally infallible.
+///
+/// Implementers should produce bits uniformly. Pathological RNGs (e.g. always
+/// returning the same value, or never setting certain bits) can break rejection
+/// sampling used by random distributions, and also break other RNGs when
+/// seeding them via [`SeedableRng::from_rng`].
+///
+/// Algorithmic generators implementing [`SeedableRng`] should normally have
+/// *portable, reproducible* output, i.e. fix Endianness when converting values
+/// to avoid platform differences, and avoid making any changes which affect
+/// output (except by communicating that the release has breaking changes).
+///
+/// Typically an RNG will implement only one of the methods available
+/// in this trait directly, then use the helper functions from the
+/// [`impls`] module to implement the other methods.
+///
+/// It is recommended that implementations also implement:
+///
+/// - `Debug` with a custom implementation which *does not* print any internal
+///   state (at least, [`CryptoRng`]s should not risk leaking state through
+///   `Debug`).
+/// - `Serialize` and `Deserialize` (from Serde), preferably making Serde
+///   support optional at the crate level in PRNG libs.
+/// - `Clone`, if possible.
+/// - *never* implement `Copy` (accidental copies may cause repeated values).
+/// - *do not* implement `Default` for pseudorandom generators, but instead
+///   implement [`SeedableRng`], to guide users towards proper seeding.
+///   External / hardware RNGs can choose to implement `Default`.
+/// - `Eq` and `PartialEq` could be implemented, but are probably not useful.
+///
+/// # Example
+///
+/// A simple example, obviously not generating very *random* output:
+///
+/// ```
+/// #![allow(dead_code)]
+/// use rand_core::{RngCore, Error, impls};
+///
+/// struct CountingRng(u64);
+///
+/// impl RngCore for CountingRng {
+///     fn next_u32(&mut self) -> u32 {
+///         self.next_u64() as u32
+///     }
+///
+///     fn next_u64(&mut self) -> u64 {
+///         self.0 += 1;
+///         self.0
+///     }
+///
+///     fn fill_bytes(&mut self, dest: &mut [u8]) {
+///         impls::fill_bytes_via_next(self, dest)
+///     }
+///
+///     fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
+///         Ok(self.fill_bytes(dest))
+///     }
+/// }
+/// ```
+///
+/// [`rand`]: https://docs.rs/rand
+/// [`try_fill_bytes`]: RngCore::try_fill_bytes
+/// [`fill_bytes`]: RngCore::fill_bytes
+/// [`next_u32`]: RngCore::next_u32
+/// [`next_u64`]: RngCore::next_u64
+pub trait RngCore {
+    /// Return the next random `u32`.
+    ///
+    /// RNGs must implement at least one method from this trait directly. In
+    /// the case this method is not implemented directly, it can be implemented
+    /// using `self.next_u64() as u32` or via [`impls::next_u32_via_fill`].
+    fn next_u32(&mut self) -> u32;
+
+    /// Return the next random `u64`.
+    ///
+    /// RNGs must implement at least one method from this trait directly. In
+    /// the case this method is not implemented directly, it can be implemented
+    /// via [`impls::next_u64_via_u32`] or via [`impls::next_u64_via_fill`].
+    fn next_u64(&mut self) -> u64;
+
+    /// Fill `dest` with random data.
+    ///
+    /// RNGs must implement at least one method from this trait directly. In
+    /// the case this method is not implemented directly, it can be implemented
+    /// via [`impls::fill_bytes_via_next`] or
+    /// via [`RngCore::try_fill_bytes`]; if this generator can
+    /// fail the implementation must choose how best to handle errors here
+    /// (e.g. panic with a descriptive message or log a warning and retry a few
+    /// times).
+    ///
+    /// This method should guarantee that `dest` is entirely filled
+    /// with new data, and may panic if this is impossible
+    /// (e.g. reading past the end of a file that is being used as the
+    /// source of randomness).
+    fn fill_bytes(&mut self, dest: &mut [u8]);
+
+    /// Fill `dest` entirely with random data.
+    ///
+    /// This is the only method which allows an RNG to report errors while
+    /// generating random data thus making this the primary method implemented
+    /// by external (true) RNGs (e.g. `OsRng`) which can fail. It may be used
+    /// directly to generate keys and to seed (infallible) PRNGs.
+    ///
+    /// Other than error handling, this method is identical to [`RngCore::fill_bytes`];
+    /// thus this may be implemented using `Ok(self.fill_bytes(dest))` or
+    /// `fill_bytes` may be implemented with
+    /// `self.try_fill_bytes(dest).unwrap()` or more specific error handling.
+    fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error>;
+}
+
+/// A marker trait used to indicate that an [`RngCore`] or [`BlockRngCore`]
+/// implementation is supposed to be cryptographically secure.
+///
+/// *Cryptographically secure generators*, also known as *CSPRNGs*, should
+/// satisfy an additional properties over other generators: given the first
+/// *k* bits of an algorithm's output
+/// sequence, it should not be possible using polynomial-time algorithms to
+/// predict the next bit with probability significantly greater than 50%.
+///
+/// Some generators may satisfy an additional property, however this is not
+/// required by this trait: if the CSPRNG's state is revealed, it should not be
+/// computationally-feasible to reconstruct output prior to this. Some other
+/// generators allow backwards-computation and are considered *reversible*.
+///
+/// Note that this trait is provided for guidance only and cannot guarantee
+/// suitability for cryptographic applications. In general it should only be
+/// implemented for well-reviewed code implementing well-regarded algorithms.
+///
+/// Note also that use of a `CryptoRng` does not protect against other
+/// weaknesses such as seeding from a weak entropy source or leaking state.
+///
+/// [`BlockRngCore`]: block::BlockRngCore
+pub trait CryptoRng {}
+
+/// An extension trait that is automatically implemented for any type
+/// implementing [`RngCore`] and [`CryptoRng`].
+///
+/// It may be used as a trait object, and supports upcasting to [`RngCore`] via
+/// the [`CryptoRngCore::as_rngcore`] method.
+///
+/// # Example
+///
+/// ```
+/// use rand_core::CryptoRngCore;
+///
+/// #[allow(unused)]
+/// fn make_token(rng: &mut dyn CryptoRngCore) -> [u8; 32] {
+///     let mut buf = [0u8; 32];
+///     rng.fill_bytes(&mut buf);
+///     buf
+/// }
+/// ```
+pub trait CryptoRngCore: CryptoRng + RngCore {
+    /// Upcast to an [`RngCore`] trait object.
+    fn as_rngcore(&mut self) -> &mut dyn RngCore;
+}
+
+impl<T: CryptoRng + RngCore> CryptoRngCore for T {
+    fn as_rngcore(&mut self) -> &mut dyn RngCore {
+        self
+    }
+}
+
+/// A random number generator that can be explicitly seeded.
+///
+/// This trait encapsulates the low-level functionality common to all
+/// pseudo-random number generators (PRNGs, or algorithmic generators).
+///
+/// [`rand`]: https://docs.rs/rand
+pub trait SeedableRng: Sized {
+    /// Seed type, which is restricted to types mutably-dereferenceable as `u8`
+    /// arrays (we recommend `[u8; N]` for some `N`).
+    ///
+    /// It is recommended to seed PRNGs with a seed of at least circa 100 bits,
+    /// which means an array of `[u8; 12]` or greater to avoid picking RNGs with
+    /// partially overlapping periods.
+    ///
+    /// For cryptographic RNG's a seed of 256 bits is recommended, `[u8; 32]`.
+    ///
+    ///
+    /// # Implementing `SeedableRng` for RNGs with large seeds
+    ///
+    /// Note that the required traits `core::default::Default` and
+    /// `core::convert::AsMut<u8>` are not implemented for large arrays
+    /// `[u8; N]` with `N` > 32. To be able to implement the traits required by
+    /// `SeedableRng` for RNGs with such large seeds, the newtype pattern can be
+    /// used:
+    ///
+    /// ```
+    /// use rand_core::SeedableRng;
+    ///
+    /// const N: usize = 64;
+    /// pub struct MyRngSeed(pub [u8; N]);
+    /// pub struct MyRng(MyRngSeed);
+    ///
+    /// impl Default for MyRngSeed {
+    ///     fn default() -> MyRngSeed {
+    ///         MyRngSeed([0; N])
+    ///     }
+    /// }
+    ///
+    /// impl AsMut<[u8]> for MyRngSeed {
+    ///     fn as_mut(&mut self) -> &mut [u8] {
+    ///         &mut self.0
+    ///     }
+    /// }
+    ///
+    /// impl SeedableRng for MyRng {
+    ///     type Seed = MyRngSeed;
+    ///
+    ///     fn from_seed(seed: MyRngSeed) -> MyRng {
+    ///         MyRng(seed)
+    ///     }
+    /// }
+    /// ```
+    type Seed: Sized + Default + AsMut<[u8]>;
+
+    /// Create a new PRNG using the given seed.
+    ///
+    /// PRNG implementations are allowed to assume that bits in the seed are
+    /// well distributed. That means usually that the number of one and zero
+    /// bits are roughly equal, and values like 0, 1 and (size - 1) are unlikely.
+    /// Note that many non-cryptographic PRNGs will show poor quality output
+    /// if this is not adhered to. If you wish to seed from simple numbers, use
+    /// `seed_from_u64` instead.
+    ///
+    /// All PRNG implementations should be reproducible unless otherwise noted:
+    /// given a fixed `seed`, the same sequence of output should be produced
+    /// on all runs, library versions and architectures (e.g. check endianness).
+    /// Any "value-breaking" changes to the generator should require bumping at
+    /// least the minor version and documentation of the change.
+    ///
+    /// It is not required that this function yield the same state as a
+    /// reference implementation of the PRNG given equivalent seed; if necessary
+    /// another constructor replicating behaviour from a reference
+    /// implementation can be added.
+    ///
+    /// PRNG implementations should make sure `from_seed` never panics. In the
+    /// case that some special values (like an all zero seed) are not viable
+    /// seeds it is preferable to map these to alternative constant value(s),
+    /// for example `0xBAD5EEDu32` or `0x0DDB1A5E5BAD5EEDu64` ("odd biases? bad
+    /// seed"). This is assuming only a small number of values must be rejected.
+    fn from_seed(seed: Self::Seed) -> Self;
+
+    /// Create a new PRNG using a `u64` seed.
+    ///
+    /// This is a convenience-wrapper around `from_seed` to allow construction
+    /// of any `SeedableRng` from a simple `u64` value. It is designed such that
+    /// low Hamming Weight numbers like 0 and 1 can be used and should still
+    /// result in good, independent seeds to the PRNG which is returned.
+    ///
+    /// This **is not suitable for cryptography**, as should be clear given that
+    /// the input size is only 64 bits.
+    ///
+    /// Implementations for PRNGs *may* provide their own implementations of
+    /// this function, but the default implementation should be good enough for
+    /// all purposes. *Changing* the implementation of this function should be
+    /// considered a value-breaking change.
+    fn seed_from_u64(mut state: u64) -> Self {
+        // We use PCG32 to generate a u32 sequence, and copy to the seed
+        fn pcg32(state: &mut u64) -> [u8; 4] {
+            const MUL: u64 = 6364136223846793005;
+            const INC: u64 = 11634580027462260723;
+
+            // We advance the state first (to get away from the input value,
+            // in case it has low Hamming Weight).
+            *state = state.wrapping_mul(MUL).wrapping_add(INC);
+            let state = *state;
+
+            // Use PCG output function with to_le to generate x:
+            let xorshifted = (((state >> 18) ^ state) >> 27) as u32;
+            let rot = (state >> 59) as u32;
+            let x = xorshifted.rotate_right(rot);
+            x.to_le_bytes()
+        }
+
+        let mut seed = Self::Seed::default();
+        let mut iter = seed.as_mut().chunks_exact_mut(4);
+        for chunk in &mut iter {
+            chunk.copy_from_slice(&pcg32(&mut state));
+        }
+        let rem = iter.into_remainder();
+        if !rem.is_empty() {
+            rem.copy_from_slice(&pcg32(&mut state)[..rem.len()]);
+        }
+
+        Self::from_seed(seed)
+    }
+
+    /// Create a new PRNG seeded from another `Rng`.
+    ///
+    /// This may be useful when needing to rapidly seed many PRNGs from a master
+    /// PRNG, and to allow forking of PRNGs. It may be considered deterministic.
+    ///
+    /// The master PRNG should be at least as high quality as the child PRNGs.
+    /// When seeding non-cryptographic child PRNGs, we recommend using a
+    /// different algorithm for the master PRNG (ideally a CSPRNG) to avoid
+    /// correlations between the child PRNGs. If this is not possible (e.g.
+    /// forking using small non-crypto PRNGs) ensure that your PRNG has a good
+    /// mixing function on the output or consider use of a hash function with
+    /// `from_seed`.
+    ///
+    /// Note that seeding `XorShiftRng` from another `XorShiftRng` provides an
+    /// extreme example of what can go wrong: the new PRNG will be a clone
+    /// of the parent.
+    ///
+    /// PRNG implementations are allowed to assume that a good RNG is provided
+    /// for seeding, and that it is cryptographically secure when appropriate.
+    /// As of `rand` 0.7 / `rand_core` 0.5, implementations overriding this
+    /// method should ensure the implementation satisfies reproducibility
+    /// (in prior versions this was not required).
+    ///
+    /// [`rand`]: https://docs.rs/rand
+    fn from_rng<R: RngCore>(mut rng: R) -> Result<Self, Error> {
+        let mut seed = Self::Seed::default();
+        rng.try_fill_bytes(seed.as_mut())?;
+        Ok(Self::from_seed(seed))
+    }
+
+    /// Creates a new instance of the RNG seeded via [`getrandom`].
+    ///
+    /// This method is the recommended way to construct non-deterministic PRNGs
+    /// since it is convenient and secure.
+    ///
+    /// In case the overhead of using [`getrandom`] to seed *many* PRNGs is an
+    /// issue, one may prefer to seed from a local PRNG, e.g.
+    /// `from_rng(thread_rng()).unwrap()`.
+    ///
+    /// # Panics
+    ///
+    /// If [`getrandom`] is unable to provide secure entropy this method will panic.
+    ///
+    /// [`getrandom`]: https://docs.rs/getrandom
+    #[cfg(feature = "getrandom")]
+    #[cfg_attr(doc_cfg, doc(cfg(feature = "getrandom")))]
+    fn from_entropy() -> Self {
+        let mut seed = Self::Seed::default();
+        if let Err(err) = getrandom::getrandom(seed.as_mut()) {
+            panic!("from_entropy failed: {}", err);
+        }
+        Self::from_seed(seed)
+    }
+}
+
+// Implement `RngCore` for references to an `RngCore`.
+// Force inlining all functions, so that it is up to the `RngCore`
+// implementation and the optimizer to decide on inlining.
+impl<'a, R: RngCore + ?Sized> RngCore for &'a mut R {
+    #[inline(always)]
+    fn next_u32(&mut self) -> u32 {
+        (**self).next_u32()
+    }
+
+    #[inline(always)]
+    fn next_u64(&mut self) -> u64 {
+        (**self).next_u64()
+    }
+
+    #[inline(always)]
+    fn fill_bytes(&mut self, dest: &mut [u8]) {
+        (**self).fill_bytes(dest)
+    }
+
+    #[inline(always)]
+    fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
+        (**self).try_fill_bytes(dest)
+    }
+}
+
+// Implement `RngCore` for boxed references to an `RngCore`.
+// Force inlining all functions, so that it is up to the `RngCore`
+// implementation and the optimizer to decide on inlining.
+#[cfg(feature = "alloc")]
+impl<R: RngCore + ?Sized> RngCore for Box<R> {
+    #[inline(always)]
+    fn next_u32(&mut self) -> u32 {
+        (**self).next_u32()
+    }
+
+    #[inline(always)]
+    fn next_u64(&mut self) -> u64 {
+        (**self).next_u64()
+    }
+
+    #[inline(always)]
+    fn fill_bytes(&mut self, dest: &mut [u8]) {
+        (**self).fill_bytes(dest)
+    }
+
+    #[inline(always)]
+    fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
+        (**self).try_fill_bytes(dest)
+    }
+}
+
+#[cfg(feature = "std")]
+impl std::io::Read for dyn RngCore {
+    fn read(&mut self, buf: &mut [u8]) -> Result<usize, std::io::Error> {
+        self.try_fill_bytes(buf)?;
+        Ok(buf.len())
+    }
+}
+
+// Implement `CryptoRng` for references to a `CryptoRng`.
+impl<'a, R: CryptoRng + ?Sized> CryptoRng for &'a mut R {}
+
+// Implement `CryptoRng` for boxed references to a `CryptoRng`.
+#[cfg(feature = "alloc")]
+impl<R: CryptoRng + ?Sized> CryptoRng for Box<R> {}
+
+#[cfg(test)]
+mod test {
+    use super::*;
+
+    #[test]
+    fn test_seed_from_u64() {
+        struct SeedableNum(u64);
+        impl SeedableRng for SeedableNum {
+            type Seed = [u8; 8];
+
+            fn from_seed(seed: Self::Seed) -> Self {
+                let mut x = [0u64; 1];
+                le::read_u64_into(&seed, &mut x);
+                SeedableNum(x[0])
+            }
+        }
+
+        const N: usize = 8;
+        const SEEDS: [u64; N] = [0u64, 1, 2, 3, 4, 8, 16, -1i64 as u64];
+        let mut results = [0u64; N];
+        for (i, seed) in SEEDS.iter().enumerate() {
+            let SeedableNum(x) = SeedableNum::seed_from_u64(*seed);
+            results[i] = x;
+        }
+
+        for (i1, r1) in results.iter().enumerate() {
+            let weight = r1.count_ones();
+            // This is the binomial distribution B(64, 0.5), so chance of
+            // weight < 20 is binocdf(19, 64, 0.5) = 7.8e-4, and same for
+            // weight > 44.
+            assert!((20..=44).contains(&weight));
+
+            for (i2, r2) in results.iter().enumerate() {
+                if i1 == i2 {
+                    continue;
+                }
+                let diff_weight = (r1 ^ r2).count_ones();
+                assert!(diff_weight >= 20);
+            }
+        }
+
+        // value-breakage test:
+        assert_eq!(results[0], 5029875928683246316);
+    }
+}
+
\ No newline at end of file diff --git a/src/rand_mt/lib.rs.html b/src/rand_mt/lib.rs.html new file mode 100644 index 000000000..4dc1e63a5 --- /dev/null +++ b/src/rand_mt/lib.rs.html @@ -0,0 +1,417 @@ +lib.rs - source

rand_mt/
lib.rs

+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
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
// src/lib.rs
+//
+// Copyright (c) 2015,2017 rust-mersenne-twister developers
+// Copyright (c) 2020 Ryan Lopopolo <rjl@hyperbo.la>
+//
+// Licensed under the Apache License, Version 2.0
+// <LICENSE-APACHE> or <http://www.apache.org/licenses/LICENSE-2.0> or the MIT
+// license <LICENSE-MIT> or <http://opensource.org/licenses/MIT>, at your
+// option. All files in the project carrying such notice may not be copied,
+// modified, or distributed except according to those terms.
+
+#![deny(clippy::all)]
+#![deny(clippy::pedantic)]
+#![deny(clippy::cargo)]
+#![allow(unknown_lints)]
+#![deny(missing_debug_implementations)]
+#![warn(missing_docs)]
+#![warn(rust_2018_idioms)]
+#![warn(trivial_casts, trivial_numeric_casts)]
+#![warn(unused_qualifications)]
+#![warn(variant_size_differences)]
+#![forbid(unsafe_code)]
+// Enable feature callouts in generated documentation:
+// https://doc.rust-lang.org/beta/unstable-book/language-features/doc-cfg.html
+//
+// This approach is borrowed from tokio.
+#![cfg_attr(docsrs, feature(doc_cfg))]
+#![cfg_attr(docsrs, feature(doc_alias))]
+
+//! Mersenne Twister random number generators.
+//!
+//! This is a native Rust implementation of a selection of Mersenne Twister
+//! generators. Mersenne Twister is not suitable for cryptographic use.
+//!
+//! This crate provides:
+//!
+//! - [`Mt19937GenRand32`], the original reference Mersenne Twister
+//!   implementation known as `MT19937`. This is a good choice on both 32-bit
+//!   and 64-bit CPUs (for 32-bit output).
+//! - [`Mt19937GenRand64`], the 64-bit variant of `MT19937` known as
+//!   `MT19937-64`. This algorithm produces a different output stream than
+//!   `MT19937` and produces 64-bit output. This is a good choice on 64-bit
+//!   CPUs.
+//!
+//! Both of these RNGs use approximately 2.5 kilobytes of state.
+//! [`Mt19937GenRand32`] uses a 32-bit seed. [`Mt19937GenRand64`] uses a 64-bit
+//! seed. Both can be seeded from an iterator of seeds.
+//!
+//! Both RNGs implement a `recover` constructor which can reconstruct the RNG
+//! state from a sequence of output samples.
+//!
+//! # Usage
+//!
+//! You can seed a RNG and begin sampling it:
+//!
+//! ```
+//! # use rand_mt::Mt64;
+//! // Create the RNG.
+//! let mut rng = Mt64::new(0x1234_567_89ab_cdef_u64);
+//! // start grabbing randomness from rng...
+//! let mut buf = vec![0; 512];
+//! rng.fill_bytes(&mut buf);
+//! ```
+//!
+//! Or if you want to use the default (fixed) seeds that are specified in the
+//! reference implementations:
+//!
+//! ```
+//! # use rand_mt::Mt;
+//! let default = Mt::default();
+//! let mt = Mt::new_unseeded();
+//! assert_eq!(default, mt);
+//! ```
+//!
+//! # Crate Features
+//!
+//! `rand_mt` is `no_std` compatible. `rand_mt` has several optional features
+//! that are enabled by default:
+//!
+//! - **rand-traits** - Enables a dependency on [`rand_core`]. Activating this
+//!   feature implements `RngCore` and `SeedableRng` on the RNGs in this crate.
+//! - **std** - Enables a dependency on the Rust Standard Library. Activating
+//!   this feature enables [`std::error::Error`] impls on error types in this
+//!   crate.
+//!
+//! Mersenne Twister requires approximately 2.5 kilobytes of internal state. To
+//! make the RNGs implemented in this crate practical to embed in other structs,
+//! you may wish to store the RNG in a [`Box`].
+//!
+#![cfg_attr(
+    not(feature = "std"),
+    doc = "[`std::error::Error`]: https://doc.rust-lang.org/std/error/trait.Error.html"
+)]
+#![cfg_attr(feature = "std", doc = "[`Box`]: std::boxed::Box")]
+#![cfg_attr(
+    not(feature = "std"),
+    doc = "[`Box`]: https://doc.rust-lang.org/std/boxed/struct.Box.html"
+)]
+#![cfg_attr(
+    not(feature = "rand_core"),
+    doc = "[`rand_core`]: https://crates.io/crates/rand_core"
+)]
+//!
+
+#![doc(html_root_url = "https://docs.rs/rand_mt/4.2.2")]
+#![no_std]
+
+#[cfg(feature = "std")]
+extern crate std;
+
+use core::fmt;
+
+pub use crate::mt::Mt19937GenRand32;
+pub use crate::mt64::Mt19937GenRand64;
+
+mod mt;
+mod mt64;
+#[cfg(test)]
+mod vectors;
+
+/// A type alias for [`Mt19937GenRand32`], 32-bit Mersenne Twister.
+pub type Mt = Mt19937GenRand32;
+
+/// A type alias for [`Mt19937GenRand64`], 64-bit Mersenne Twister.
+pub type Mt64 = Mt19937GenRand64;
+
+/// Error returned from fallible Mersenne Twister recovery constructors.
+///
+/// When the `std` feature is enabled, this type implements `std::error::Error`.
+#[non_exhaustive]
+#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
+pub enum RecoverRngError {
+    /// Attempted to recover an RNG with too many samples.
+    ///
+    /// Recover constructors require an exact number of samples to ensure the
+    /// recovered RNG matches the state of the RNG that supplied all of the
+    /// samples.
+    TooFewSamples(usize),
+    /// Attempted to recover an RNG with too few samples.
+    ///
+    /// Too few samples leaves the internal state buffer partially
+    /// uninitialized.
+    ///
+    /// Recover constructors require an exact number of samples to ensure the
+    /// recovered RNG matches the state of the RNG that supplied all of the
+    /// samples.
+    TooManySamples(usize),
+}
+
+impl fmt::Display for RecoverRngError {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        match self {
+            Self::TooFewSamples(expected) => {
+                write!(f, "Too few samples given to recover: expected {}", expected)
+            }
+            Self::TooManySamples(expected) => write!(
+                f,
+                "Too many samples given to recover: expected {}",
+                expected
+            ),
+        }
+    }
+}
+
+#[cfg(feature = "std")]
+impl std::error::Error for RecoverRngError {}
+
+#[cfg(test)]
+mod tests {
+    #[cfg(feature = "std")]
+    use super::RecoverRngError;
+
+    #[test]
+    #[cfg(feature = "std")]
+    fn error_display_is_not_empty() {
+        use core::fmt::Write as _;
+        use std::string::String;
+
+        let test_cases = [
+            RecoverRngError::TooFewSamples(0),
+            RecoverRngError::TooFewSamples(124),
+            RecoverRngError::TooManySamples(0),
+            RecoverRngError::TooManySamples(987),
+        ];
+        for tc in test_cases {
+            let mut buf = String::new();
+            write!(&mut buf, "{}", tc).unwrap();
+            assert!(!buf.is_empty());
+        }
+    }
+}
+
+// Ensure code blocks in `README.md` compile.
+//
+// This module and macro declaration should be kept at the end of the file, in
+// order to not interfere with code coverage.
+#[cfg(doctest)]
+macro_rules! readme {
+    ($x:expr) => {
+        #[doc = $x]
+        mod readme {}
+    };
+    () => {
+        readme!(include_str!("../README.md"));
+    };
+}
+#[cfg(doctest)]
+readme!();
+
\ No newline at end of file diff --git a/src/rand_mt/mt.rs.html b/src/rand_mt/mt.rs.html new file mode 100644 index 000000000..3cbf00509 --- /dev/null +++ b/src/rand_mt/mt.rs.html @@ -0,0 +1,1395 @@ +mt.rs - source

rand_mt/
mt.rs

+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
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
+224
+225
+226
+227
+228
+229
+230
+231
+232
+233
+234
+235
+236
+237
+238
+239
+240
+241
+242
+243
+244
+245
+246
+247
+248
+249
+250
+251
+252
+253
+254
+255
+256
+257
+258
+259
+260
+261
+262
+263
+264
+265
+266
+267
+268
+269
+270
+271
+272
+273
+274
+275
+276
+277
+278
+279
+280
+281
+282
+283
+284
+285
+286
+287
+288
+289
+290
+291
+292
+293
+294
+295
+296
+297
+298
+299
+300
+301
+302
+303
+304
+305
+306
+307
+308
+309
+310
+311
+312
+313
+314
+315
+316
+317
+318
+319
+320
+321
+322
+323
+324
+325
+326
+327
+328
+329
+330
+331
+332
+333
+334
+335
+336
+337
+338
+339
+340
+341
+342
+343
+344
+345
+346
+347
+348
+349
+350
+351
+352
+353
+354
+355
+356
+357
+358
+359
+360
+361
+362
+363
+364
+365
+366
+367
+368
+369
+370
+371
+372
+373
+374
+375
+376
+377
+378
+379
+380
+381
+382
+383
+384
+385
+386
+387
+388
+389
+390
+391
+392
+393
+394
+395
+396
+397
+398
+399
+400
+401
+402
+403
+404
+405
+406
+407
+408
+409
+410
+411
+412
+413
+414
+415
+416
+417
+418
+419
+420
+421
+422
+423
+424
+425
+426
+427
+428
+429
+430
+431
+432
+433
+434
+435
+436
+437
+438
+439
+440
+441
+442
+443
+444
+445
+446
+447
+448
+449
+450
+451
+452
+453
+454
+455
+456
+457
+458
+459
+460
+461
+462
+463
+464
+465
+466
+467
+468
+469
+470
+471
+472
+473
+474
+475
+476
+477
+478
+479
+480
+481
+482
+483
+484
+485
+486
+487
+488
+489
+490
+491
+492
+493
+494
+495
+496
+497
+498
+499
+500
+501
+502
+503
+504
+505
+506
+507
+508
+509
+510
+511
+512
+513
+514
+515
+516
+517
+518
+519
+520
+521
+522
+523
+524
+525
+526
+527
+528
+529
+530
+531
+532
+533
+534
+535
+536
+537
+538
+539
+540
+541
+542
+543
+544
+545
+546
+547
+548
+549
+550
+551
+552
+553
+554
+555
+556
+557
+558
+559
+560
+561
+562
+563
+564
+565
+566
+567
+568
+569
+570
+571
+572
+573
+574
+575
+576
+577
+578
+579
+580
+581
+582
+583
+584
+585
+586
+587
+588
+589
+590
+591
+592
+593
+594
+595
+596
+597
+598
+599
+600
+601
+602
+603
+604
+605
+606
+607
+608
+609
+610
+611
+612
+613
+614
+615
+616
+617
+618
+619
+620
+621
+622
+623
+624
+625
+626
+627
+628
+629
+630
+631
+632
+633
+634
+635
+636
+637
+638
+639
+640
+641
+642
+643
+644
+645
+646
+647
+648
+649
+650
+651
+652
+653
+654
+655
+656
+657
+658
+659
+660
+661
+662
+663
+664
+665
+666
+667
+668
+669
+670
+671
+672
+673
+674
+675
+676
+677
+678
+679
+680
+681
+682
+683
+684
+685
+686
+687
+688
+689
+690
+691
+692
+693
+694
+695
+696
+697
// src/mt.rs
+//
+// Copyright (c) 2015,2017 rust-mersenne-twister developers
+// Copyright (c) 2020 Ryan Lopopolo <rjl@hyperbo.la>
+//
+// Licensed under the Apache License, Version 2.0
+// <LICENSE-APACHE> or <http://www.apache.org/licenses/LICENSE-2.0> or the MIT
+// license <LICENSE-MIT> or <http://opensource.org/licenses/MIT>, at your
+// option. All files in the project carrying such notice may not be copied,
+// modified, or distributed except according to those terms.
+
+use core::convert::TryFrom;
+use core::fmt;
+use core::mem::size_of;
+use core::num::Wrapping;
+
+use crate::RecoverRngError;
+
+#[cfg(feature = "rand-traits")]
+mod rand;
+
+const N: usize = 624;
+const M: usize = 397;
+const ONE: Wrapping<u32> = Wrapping(1);
+const MATRIX_A: Wrapping<u32> = Wrapping(0x9908_b0df);
+const UPPER_MASK: Wrapping<u32> = Wrapping(0x8000_0000);
+const LOWER_MASK: Wrapping<u32> = Wrapping(0x7fff_ffff);
+
+/// The 32-bit flavor of the Mersenne Twister pseudorandom number
+/// generator.
+///
+/// The official name of this RNG is `MT19937`. It natively outputs `u32`.
+///
+/// # Size
+///
+/// `Mt19937GenRand32` requires approximately 2.5 kilobytes of internal state.
+///
+/// You may wish to store an `Mt19937GenRand32` on the heap in a [`Box`] to make
+/// it easier to embed in another struct.
+///
+/// `Mt19937GenRand32` is also the same size as
+/// [`Mt19937GenRand64`](crate::Mt19937GenRand64).
+///
+/// ```
+/// # use core::mem;
+/// # use rand_mt::{Mt19937GenRand32, Mt19937GenRand64};
+/// assert_eq!(2504, mem::size_of::<Mt19937GenRand32>());
+/// assert_eq!(mem::size_of::<Mt19937GenRand64>(), mem::size_of::<Mt19937GenRand32>());
+/// ```
+#[cfg_attr(feature = "std", doc = "[`Box`]: std::boxed::Box")]
+#[cfg_attr(
+    not(feature = "std"),
+    doc = "[`Box`]: https://doc.rust-lang.org/std/boxed/struct.Box.html"
+)]
+#[derive(Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
+#[allow(clippy::module_name_repetitions)]
+pub struct Mt19937GenRand32 {
+    idx: usize,
+    state: [Wrapping<u32>; N],
+}
+
+impl fmt::Debug for Mt19937GenRand32 {
+    #[inline]
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        f.write_str("Mt19937GenRand32 {}")
+    }
+}
+
+impl Default for Mt19937GenRand32 {
+    /// Return a new `Mt19937GenRand32` with the default seed.
+    ///
+    /// Equivalent to calling [`Mt19937GenRand32::new_unseeded`].
+    #[inline]
+    fn default() -> Self {
+        Self::new_unseeded()
+    }
+}
+
+impl From<[u8; 4]> for Mt19937GenRand32 {
+    /// Construct a Mersenne Twister RNG from 4 bytes.
+    ///
+    /// The given bytes are treated as a little endian encoded `u32`.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use rand_mt::Mt19937GenRand32;
+    /// // Default MT seed
+    /// let seed = 5489_u32.to_le_bytes();
+    /// let mut mt = Mt19937GenRand32::from(seed);
+    /// assert_ne!(mt.next_u32(), mt.next_u32());
+    /// ```
+    ///
+    /// This constructor is equivalent to passing a little endian encoded `u32`.
+    ///
+    /// ```
+    /// # use rand_mt::Mt19937GenRand32;
+    /// // Default MT seed
+    /// let seed = 5489_u32.to_le_bytes();
+    /// let mt1 = Mt19937GenRand32::from(seed);
+    /// let mt2 = Mt19937GenRand32::new(5489_u32);
+    /// assert_eq!(mt1, mt2);
+    /// ```
+    #[inline]
+    fn from(seed: [u8; 4]) -> Self {
+        Self::new(u32::from_le_bytes(seed))
+    }
+}
+
+impl From<u32> for Mt19937GenRand32 {
+    /// Construct a Mersenne Twister RNG from a `u32` seed.
+    ///
+    /// This function is equivalent to [`new`].
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use rand_mt::Mt19937GenRand32;
+    /// // Default MT seed
+    /// let seed = 5489_u32;
+    /// let mt1 = Mt19937GenRand32::from(seed);
+    /// let mt2 = Mt19937GenRand32::new(seed);
+    /// assert_eq!(mt1, mt2);
+    ///
+    /// // Non-default MT seed
+    /// let seed = 9927_u32;
+    /// let mt1 = Mt19937GenRand32::from(seed);
+    /// let mt2 = Mt19937GenRand32::new(seed);
+    /// assert_eq!(mt1, mt2);
+    /// ```
+    ///
+    /// [`new`]: Self::new
+    #[inline]
+    fn from(seed: u32) -> Self {
+        Self::new(seed)
+    }
+}
+
+impl From<[u32; N]> for Mt19937GenRand32 {
+    /// Recover the internal state of a Mersenne Twister using the past 624
+    /// samples.
+    ///
+    /// This conversion takes a history of samples from a RNG and returns a
+    /// RNG that will produce identical output to the RNG that supplied the
+    /// samples.
+    #[inline]
+    fn from(key: [u32; N]) -> Self {
+        let mut mt = Self {
+            idx: N,
+            state: [Wrapping(0); N],
+        };
+        for (sample, out) in key.iter().copied().zip(mt.state.iter_mut()) {
+            *out = Wrapping(untemper(sample));
+        }
+        mt
+    }
+}
+
+impl TryFrom<&[u32]> for Mt19937GenRand32 {
+    type Error = RecoverRngError;
+
+    /// Attempt to recover the internal state of a Mersenne Twister using the
+    /// past 624 samples.
+    ///
+    /// This conversion takes a history of samples from a RNG and returns a
+    /// RNG that will produce identical output to the RNG that supplied the
+    /// samples.
+    ///
+    /// This conversion is implemented with [`Mt19937GenRand32::recover`].
+    ///
+    /// # Errors
+    ///
+    /// If `key` has less than 624 elements, an error is returned because there
+    /// is not enough data to fully initialize the RNG.
+    ///
+    /// If `key` has more than 624 elements, an error is returned because the
+    /// recovered RNG will not produce identical output to the RNG that supplied
+    /// the samples.
+    #[inline]
+    fn try_from(key: &[u32]) -> Result<Self, Self::Error> {
+        Self::recover(key.iter().copied())
+    }
+}
+
+impl Mt19937GenRand32 {
+    /// Default seed used by [`Mt19937GenRand32::new_unseeded`].
+    pub const DEFAULT_SEED: u32 = 5489_u32;
+
+    /// Create a new Mersenne Twister random number generator using the given
+    /// seed.
+    ///
+    /// # Examples
+    ///
+    /// ## Constructing with a `u32` seed
+    ///
+    /// ```
+    /// # use rand_mt::Mt19937GenRand32;
+    /// let seed = 123_456_789_u32;
+    /// let mt1 = Mt19937GenRand32::new(seed);
+    /// let mt2 = Mt19937GenRand32::from(seed.to_le_bytes());
+    /// assert_eq!(mt1, mt2);
+    /// ```
+    ///
+    /// ## Constructing with default seed
+    ///
+    /// ```
+    /// # use rand_mt::Mt19937GenRand32;
+    /// let mt1 = Mt19937GenRand32::new(Mt19937GenRand32::DEFAULT_SEED);
+    /// let mt2 = Mt19937GenRand32::new_unseeded();
+    /// assert_eq!(mt1, mt2);
+    /// ```
+    #[inline]
+    #[must_use]
+    pub fn new(seed: u32) -> Self {
+        let mut mt = Self {
+            idx: 0,
+            state: [Wrapping(0); N],
+        };
+        mt.reseed(seed);
+        mt
+    }
+
+    /// Create a new Mersenne Twister random number generator using the given
+    /// key.
+    ///
+    /// Key can have any length.
+    #[inline]
+    #[must_use]
+    pub fn new_with_key<I>(key: I) -> Self
+    where
+        I: IntoIterator<Item = u32>,
+        I::IntoIter: Clone,
+    {
+        let mut mt = Self {
+            idx: 0,
+            state: [Wrapping(0); N],
+        };
+        mt.reseed_with_key(key);
+        mt
+    }
+
+    /// Create a new Mersenne Twister random number generator using the default
+    /// fixed seed.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use rand_mt::Mt19937GenRand32;
+    /// // Default MT seed
+    /// let seed = 5489_u32;
+    /// let mt = Mt19937GenRand32::new(seed);
+    /// let unseeded = Mt19937GenRand32::new_unseeded();
+    /// assert_eq!(mt, unseeded);
+    /// ```
+    #[inline]
+    #[must_use]
+    pub fn new_unseeded() -> Self {
+        Self::new(Self::DEFAULT_SEED)
+    }
+
+    /// Generate next `u64` output.
+    ///
+    /// This function is implemented by generating two `u32`s from the RNG and
+    /// performing shifting and masking to turn them into a `u64` output.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use rand_mt::Mt19937GenRand32;
+    /// let mut mt = Mt19937GenRand32::new_unseeded();
+    /// assert_ne!(mt.next_u64(), mt.next_u64());
+    /// ```
+    #[inline]
+    pub fn next_u64(&mut self) -> u64 {
+        let out = u64::from(self.next_u32());
+        let out = out << 32;
+        out | u64::from(self.next_u32())
+    }
+
+    /// Generate next `u32` output.
+    ///
+    /// `u32` is the native output of the generator. This function advances the
+    /// RNG step counter by one.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use rand_mt::Mt19937GenRand32;
+    /// let mut mt = Mt19937GenRand32::new_unseeded();
+    /// assert_ne!(mt.next_u32(), mt.next_u32());
+    /// ```
+    #[inline]
+    pub fn next_u32(&mut self) -> u32 {
+        // Failing this check indicates that, somehow, the structure
+        // was not initialized.
+        debug_assert!(self.idx != 0);
+        if self.idx >= N {
+            fill_next_state(self);
+        }
+        let Wrapping(x) = self.state[self.idx];
+        self.idx += 1;
+        temper(x)
+    }
+
+    /// Fill a buffer with bytes generated from the RNG.
+    ///
+    /// This method generates random `u32`s (the native output unit of the RNG)
+    /// until `dest` is filled.
+    ///
+    /// This method may discard some output bits if `dest.len()` is not a
+    /// multiple of 4.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use rand_mt::Mt19937GenRand32;
+    /// let mut mt = Mt19937GenRand32::new_unseeded();
+    /// let mut buf = [0; 32];
+    /// mt.fill_bytes(&mut buf);
+    /// assert_ne!([0; 32], buf);
+    /// let mut buf = [0; 31];
+    /// mt.fill_bytes(&mut buf);
+    /// assert_ne!([0; 31], buf);
+    /// ```
+    #[inline]
+    pub fn fill_bytes(&mut self, dest: &mut [u8]) {
+        const CHUNK: usize = size_of::<u32>();
+        let mut dest_chunks = dest.chunks_exact_mut(CHUNK);
+
+        for next in &mut dest_chunks {
+            let chunk: [u8; CHUNK] = self.next_u32().to_le_bytes();
+            next.copy_from_slice(&chunk);
+        }
+
+        let remainder = dest_chunks.into_remainder();
+        if remainder.is_empty() {
+            return;
+        }
+        remainder
+            .iter_mut()
+            .zip(self.next_u32().to_le_bytes().iter())
+            .for_each(|(cell, &byte)| {
+                *cell = byte;
+            });
+    }
+
+    /// Attempt to recover the internal state of a Mersenne Twister using the
+    /// past 624 samples.
+    ///
+    /// This conversion takes a history of samples from a RNG and returns a
+    /// RNG that will produce identical output to the RNG that supplied the
+    /// samples.
+    ///
+    /// This constructor is also available as a [`TryFrom`] implementation for
+    /// `&[u32]`.
+    ///
+    /// # Errors
+    ///
+    /// If `key` has less than 624 elements, an error is returned because there
+    /// is not enough data to fully initialize the RNG.
+    ///
+    /// If `key` has more than 624 elements, an error is returned because the
+    /// recovered RNG will not produce identical output to the RNG that supplied
+    /// the samples.
+    #[inline]
+    pub fn recover<I>(key: I) -> Result<Self, RecoverRngError>
+    where
+        I: IntoIterator<Item = u32>,
+    {
+        let mut mt = Self {
+            idx: N,
+            state: [Wrapping(0); N],
+        };
+        let mut state = mt.state.iter_mut();
+        for sample in key {
+            let out = state.next().ok_or(RecoverRngError::TooManySamples(N))?;
+            *out = Wrapping(untemper(sample));
+        }
+        // If the state iterator still has unfilled cells, the given iterator
+        // was too short. If there are no additional cells, return the
+        // initialized RNG.
+        if state.next().is_none() {
+            Ok(mt)
+        } else {
+            Err(RecoverRngError::TooFewSamples(N))
+        }
+    }
+
+    /// Reseed a Mersenne Twister from a single `u32`.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use rand_mt::Mt19937GenRand32;
+    /// // Default MT seed
+    /// let mut mt = Mt19937GenRand32::new_unseeded();
+    /// let first = mt.next_u32();
+    /// mt.fill_bytes(&mut [0; 512]);
+    /// // Default MT seed
+    /// mt.reseed(5489_u32);
+    /// assert_eq!(first, mt.next_u32());
+    /// ```
+    #[inline]
+    #[allow(clippy::cast_possible_truncation)]
+    pub fn reseed(&mut self, seed: u32) {
+        self.idx = N;
+        self.state[0] = Wrapping(seed);
+        for i in 1..N {
+            self.state[i] = Wrapping(1_812_433_253)
+                * (self.state[i - 1] ^ (self.state[i - 1] >> 30))
+                + Wrapping(i as u32);
+        }
+    }
+
+    /// Reseed a Mersenne Twister from am iterator of `u32`s.
+    ///
+    /// Key can have any length.
+    #[inline]
+    #[allow(clippy::cast_possible_truncation)]
+    pub fn reseed_with_key<I>(&mut self, key: I)
+    where
+        I: IntoIterator<Item = u32>,
+        I::IntoIter: Clone,
+    {
+        self.reseed(19_650_218_u32);
+        let mut i = 1_usize;
+        for (j, piece) in key.into_iter().enumerate().cycle().take(N) {
+            self.state[i] = (self.state[i]
+                ^ ((self.state[i - 1] ^ (self.state[i - 1] >> 30)) * Wrapping(1_664_525)))
+                + Wrapping(piece)
+                + Wrapping(j as u32);
+            i += 1;
+            if i >= N {
+                self.state[0] = self.state[N - 1];
+                i = 1;
+            }
+        }
+        for _ in 0..N - 1 {
+            self.state[i] = (self.state[i]
+                ^ ((self.state[i - 1] ^ (self.state[i - 1] >> 30)) * Wrapping(1_566_083_941)))
+                - Wrapping(i as u32);
+            i += 1;
+            if i >= N {
+                self.state[0] = self.state[N - 1];
+                i = 1;
+            }
+        }
+        self.state[0] = Wrapping(1 << 31);
+    }
+}
+
+#[inline]
+fn temper(mut x: u32) -> u32 {
+    x ^= x >> 11;
+    x ^= (x << 7) & 0x9d2c_5680;
+    x ^= (x << 15) & 0xefc6_0000;
+    x ^= x >> 18;
+    x
+}
+
+#[inline]
+fn untemper(mut x: u32) -> u32 {
+    // reverse `x ^=  x>>18;`
+    x ^= x >> 18;
+
+    // reverse `x ^= (x<<15) & 0xefc6_0000;`
+    x ^= (x << 15) & 0x2fc6_0000;
+    x ^= (x << 15) & 0xc000_0000;
+
+    // reverse `x ^= (x<< 7) & 0x9d2c_5680;`
+    x ^= (x << 7) & 0x0000_1680;
+    x ^= (x << 7) & 0x000c_4000;
+    x ^= (x << 7) & 0x0d20_0000;
+    x ^= (x << 7) & 0x9000_0000;
+
+    // reverse `x ^=  x>>11;`
+    x ^= x >> 11;
+    x ^= x >> 22;
+
+    x
+}
+
+#[inline]
+fn fill_next_state(rng: &mut Mt19937GenRand32) {
+    for i in 0..N - M {
+        let x = (rng.state[i] & UPPER_MASK) | (rng.state[i + 1] & LOWER_MASK);
+        rng.state[i] = rng.state[i + M] ^ (x >> 1) ^ ((x & ONE) * MATRIX_A);
+    }
+    for i in N - M..N - 1 {
+        let x = (rng.state[i] & UPPER_MASK) | (rng.state[i + 1] & LOWER_MASK);
+        rng.state[i] = rng.state[i + M - N] ^ (x >> 1) ^ ((x & ONE) * MATRIX_A);
+    }
+    let x = (rng.state[N - 1] & UPPER_MASK) | (rng.state[0] & LOWER_MASK);
+    rng.state[N - 1] = rng.state[M - 1] ^ (x >> 1) ^ ((x & ONE) * MATRIX_A);
+    rng.idx = 0;
+}
+
+#[cfg(test)]
+mod tests {
+    use core::convert::TryFrom;
+    use core::iter;
+    use core::num::Wrapping;
+
+    use super::{Mt19937GenRand32, N};
+    use crate::vectors::mt::{STATE_SEEDED_BY_SLICE, STATE_SEEDED_BY_U32, TEST_OUTPUT};
+    use crate::RecoverRngError;
+
+    #[test]
+    fn seeded_state_from_u32_seed() {
+        let mt = Mt19937GenRand32::new(0x1234_5678_u32);
+        let mt_from_seed = Mt19937GenRand32::from(0x1234_5678_u32.to_le_bytes());
+        assert_eq!(mt.state, mt_from_seed.state);
+        for (&Wrapping(x), &y) in mt.state.iter().zip(STATE_SEEDED_BY_U32.iter()) {
+            assert_eq!(x, y);
+        }
+        for (&Wrapping(x), &y) in mt_from_seed.state.iter().zip(STATE_SEEDED_BY_U32.iter()) {
+            assert_eq!(x, y);
+        }
+    }
+
+    #[test]
+    fn seeded_state_from_u32_slice_key() {
+        let key = [0x123_u32, 0x234_u32, 0x345_u32, 0x456_u32];
+        let mt = Mt19937GenRand32::new_with_key(key.iter().copied());
+        for (&Wrapping(x), &y) in mt.state.iter().zip(STATE_SEEDED_BY_SLICE.iter()) {
+            assert_eq!(x, y);
+        }
+    }
+
+    #[test]
+    fn seed_with_empty_iter_returns() {
+        let _rng = Mt19937GenRand32::new_with_key(iter::empty());
+    }
+
+    #[test]
+    fn output_from_u32_slice_key() {
+        let key = [0x123_u32, 0x234_u32, 0x345_u32, 0x456_u32];
+        let mut mt = Mt19937GenRand32::new_with_key(key.iter().copied());
+        for &x in &TEST_OUTPUT {
+            assert_eq!(x, mt.next_u32());
+        }
+    }
+
+    #[test]
+    fn temper_untemper_is_identity() {
+        let mut buf = [0; 4];
+        for _ in 0..10_000 {
+            getrandom::getrandom(&mut buf).unwrap();
+            let x = u32::from_le_bytes(buf);
+            assert_eq!(x, super::untemper(super::temper(x)));
+            let x = u32::from_be_bytes(buf);
+            assert_eq!(x, super::untemper(super::temper(x)));
+        }
+    }
+
+    #[test]
+    fn untemper_temper_is_identity() {
+        let mut buf = [0; 4];
+        for _ in 0..10_000 {
+            getrandom::getrandom(&mut buf).unwrap();
+            let x = u32::from_le_bytes(buf);
+            assert_eq!(x, super::temper(super::untemper(x)));
+            let x = u32::from_be_bytes(buf);
+            assert_eq!(x, super::temper(super::untemper(x)));
+        }
+    }
+
+    #[test]
+    fn recovery_via_from() {
+        let mut buf = [0; 4];
+        for _ in 0..100 {
+            getrandom::getrandom(&mut buf).unwrap();
+            let seed = u32::from_le_bytes(buf);
+            for skip in 0..256 {
+                let mut orig_mt = Mt19937GenRand32::new(seed);
+                // skip some samples so the RNG is in an intermediate state
+                for _ in 0..skip {
+                    orig_mt.next_u32();
+                }
+                let mut samples = [0; 624];
+                for sample in &mut samples {
+                    *sample = orig_mt.next_u32();
+                }
+                let mut recovered_mt = Mt19937GenRand32::from(samples);
+                for _ in 0..624 * 2 {
+                    assert_eq!(orig_mt.next_u32(), recovered_mt.next_u32());
+                }
+            }
+        }
+    }
+
+    #[test]
+    fn recovery_via_recover() {
+        let mut buf = [0; 4];
+        for _ in 0..100 {
+            getrandom::getrandom(&mut buf).unwrap();
+            let seed = u32::from_le_bytes(buf);
+            for skip in 0..256 {
+                let mut orig_mt = Mt19937GenRand32::new(seed);
+                // skip some samples so the RNG is in an intermediate state
+                for _ in 0..skip {
+                    orig_mt.next_u32();
+                }
+                let mut samples = [0; 624];
+                for sample in &mut samples {
+                    *sample = orig_mt.next_u32();
+                }
+                let mut recovered_mt = Mt19937GenRand32::recover(samples.iter().copied()).unwrap();
+                for _ in 0..624 * 2 {
+                    assert_eq!(orig_mt.next_u32(), recovered_mt.next_u32());
+                }
+            }
+        }
+    }
+
+    #[test]
+    fn recover_required_exact_sample_length_via_from() {
+        assert_eq!(
+            Mt19937GenRand32::try_from(&[0; 0][..]),
+            Err(RecoverRngError::TooFewSamples(N))
+        );
+        assert_eq!(
+            Mt19937GenRand32::try_from(&[0; 1][..]),
+            Err(RecoverRngError::TooFewSamples(N))
+        );
+        assert_eq!(
+            Mt19937GenRand32::try_from(&[0; 623][..]),
+            Err(RecoverRngError::TooFewSamples(N))
+        );
+        Mt19937GenRand32::try_from(&[0; 624][..]).unwrap();
+        assert_eq!(
+            Mt19937GenRand32::try_from(&[0; 625][..]),
+            Err(RecoverRngError::TooManySamples(N))
+        );
+        assert_eq!(
+            Mt19937GenRand32::try_from(&[0; 1000][..]),
+            Err(RecoverRngError::TooManySamples(N))
+        );
+    }
+
+    #[test]
+    fn recover_required_exact_sample_length_via_recover() {
+        assert_eq!(
+            Mt19937GenRand32::recover([0; 0].iter().copied()),
+            Err(RecoverRngError::TooFewSamples(N))
+        );
+        assert_eq!(
+            Mt19937GenRand32::recover([0; 1].iter().copied()),
+            Err(RecoverRngError::TooFewSamples(N))
+        );
+        assert_eq!(
+            Mt19937GenRand32::recover([0; 623].iter().copied()),
+            Err(RecoverRngError::TooFewSamples(N))
+        );
+        Mt19937GenRand32::recover([0; 624].iter().copied()).unwrap();
+        assert_eq!(
+            Mt19937GenRand32::recover([0; 625].iter().copied()),
+            Err(RecoverRngError::TooManySamples(N))
+        );
+        assert_eq!(
+            Mt19937GenRand32::recover([0; 1000].iter().copied()),
+            Err(RecoverRngError::TooManySamples(N))
+        );
+    }
+
+    #[test]
+    #[cfg(feature = "std")]
+    fn fmt_debug_does_not_leak_seed() {
+        use core::fmt::Write as _;
+        use std::string::String;
+
+        let random = Mt19937GenRand32::new(874);
+
+        let mut buf = String::new();
+        write!(&mut buf, "{:?}", random).unwrap();
+        assert!(!buf.contains("874"));
+        assert_eq!(buf, "Mt19937GenRand32 {}");
+
+        let random = Mt19937GenRand32::new(123_456);
+
+        let mut buf = String::new();
+        write!(&mut buf, "{:?}", random).unwrap();
+        assert!(!buf.contains("123456"));
+        assert_eq!(buf, "Mt19937GenRand32 {}");
+    }
+
+    #[test]
+    fn default_is_new_unseeded() {
+        let mut default = Mt19937GenRand32::default();
+        let mut unseeded = Mt19937GenRand32::new_unseeded();
+
+        assert_eq!(default, unseeded);
+        for _ in 0..1024 {
+            assert_eq!(default.next_u32(), unseeded.next_u32());
+        }
+    }
+}
+
\ No newline at end of file diff --git a/src/rand_mt/mt/rand.rs.html b/src/rand_mt/mt/rand.rs.html new file mode 100644 index 000000000..800bd2cdd --- /dev/null +++ b/src/rand_mt/mt/rand.rs.html @@ -0,0 +1,363 @@ +rand.rs - source

rand_mt/mt/
rand.rs

+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
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
// src/mt/rand.rs
+//
+// Copyright (c) 2015,2017 rust-mersenne-twister developers
+// Copyright (c) 2020 Ryan Lopopolo <rjl@hyperbo.la>
+//
+// Licensed under the Apache License, Version 2.0
+// <LICENSE-APACHE> or <http://www.apache.org/licenses/LICENSE-2.0> or the MIT
+// license <LICENSE-MIT> or <http://opensource.org/licenses/MIT>, at your
+// option. All files in the project carrying such notice may not be copied,
+// modified, or distributed except according to those terms.
+
+use rand_core::{Error, RngCore, SeedableRng};
+
+use super::Mt19937GenRand32;
+
+impl SeedableRng for Mt19937GenRand32 {
+    type Seed = [u8; 4];
+
+    /// Reseed from a little endian encoded `u32`.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use rand_core::{RngCore, SeedableRng};
+    /// use rand_mt::Mt19937GenRand32;
+    ///
+    /// // Default MT seed
+    /// let seed = 5489_u32.to_le_bytes();
+    /// let mut rng = Mt19937GenRand32::from_seed(seed);
+    /// # fn example<T: RngCore>(mut rng: T) {
+    /// assert_ne!(rng.next_u32(), rng.next_u32());
+    /// # }
+    /// # example(rng);
+    /// ```
+    #[inline]
+    fn from_seed(seed: Self::Seed) -> Self {
+        Self::from(seed)
+    }
+}
+
+impl RngCore for Mt19937GenRand32 {
+    /// Generate next `u64` output.
+    ///
+    /// This function is implemented by generating two `u32`s from the RNG and
+    /// performing shifting and masking to turn them into a `u64` output.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use rand_core::RngCore;
+    /// use rand_mt::Mt19937GenRand32;
+    ///
+    /// let mut rng = Mt19937GenRand32::new_unseeded();
+    /// # fn example<T: RngCore>(mut rng: T) {
+    /// assert_ne!(rng.next_u64(), rng.next_u64());
+    /// # }
+    /// # example(rng);
+    /// ```
+    #[inline]
+    fn next_u64(&mut self) -> u64 {
+        Self::next_u64(self)
+    }
+
+    /// Generate next `u32` output.
+    ///
+    /// `u32` is the native output of the generator. This function advances the
+    /// RNG step counter by one.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use rand_core::RngCore;
+    /// use rand_mt::Mt19937GenRand32;
+    ///
+    /// let mut rng = Mt19937GenRand32::new_unseeded();
+    /// # fn example<T: RngCore>(mut rng: T) {
+    /// assert_ne!(rng.next_u32(), rng.next_u32());
+    /// # }
+    /// # example(rng);
+    /// ```
+    #[inline]
+    fn next_u32(&mut self) -> u32 {
+        Self::next_u32(self)
+    }
+
+    /// Fill a buffer with bytes generated from the RNG.
+    ///
+    /// This method generates random `u32`s (the native output unit of the RNG)
+    /// until `dest` is filled.
+    ///
+    /// This method may discard some output bits if `dest.len()` is not a
+    /// multiple of 4.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use rand_core::RngCore;
+    /// use rand_mt::Mt19937GenRand32;
+    ///
+    /// let mut rng = Mt19937GenRand32::new_unseeded();
+    /// # fn example<T: RngCore>(mut rng: T) {
+    /// let mut buf = [0; 32];
+    /// rng.fill_bytes(&mut buf);
+    /// assert_ne!([0; 32], buf);
+    /// let mut buf = [0; 31];
+    /// rng.fill_bytes(&mut buf);
+    /// assert_ne!([0; 31], buf);
+    /// # }
+    /// # example(rng);
+    /// ```
+    #[inline]
+    fn fill_bytes(&mut self, dest: &mut [u8]) {
+        Self::fill_bytes(self, dest);
+    }
+
+    /// Fill a buffer with bytes generated from the RNG.
+    ///
+    /// This method generates random `u32`s (the native output unit of the RNG)
+    /// until `dest` is filled.
+    ///
+    /// This method may discard some output bits if `dest.len()` is not a
+    /// multiple of 4.
+    ///
+    /// `try_fill_bytes` is implemented with [`fill_bytes`](RngCore::fill_bytes)
+    /// and is infallible.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use rand_core::RngCore;
+    /// use rand_mt::Mt19937GenRand32;
+    ///
+    /// let mut rng = Mt19937GenRand32::new_unseeded();
+    /// # fn example<T: RngCore>(mut rng: T) -> Result<(), rand_core::Error> {
+    /// let mut buf = [0; 32];
+    /// rng.try_fill_bytes(&mut buf)?;
+    /// assert_ne!([0; 32], buf);
+    /// let mut buf = [0; 31];
+    /// rng.try_fill_bytes(&mut buf)?;
+    /// assert_ne!([0; 31], buf);
+    /// # Ok(())
+    /// # }
+    /// # example(rng).unwrap()
+    /// ```
+    #[inline]
+    fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
+        Self::fill_bytes(self, dest);
+        Ok(())
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use core::num::Wrapping;
+    use rand_core::{RngCore, SeedableRng};
+
+    use super::Mt19937GenRand32;
+    use crate::vectors::mt::{STATE_SEEDED_BY_U32, TEST_OUTPUT};
+
+    #[test]
+    fn seeded_state_from_u32_seed() {
+        let rng = Mt19937GenRand32::new(0x1234_5678_u32);
+        let rng_from_seed = Mt19937GenRand32::from_seed(0x1234_5678_u32.to_le_bytes());
+        assert_eq!(rng.state, rng_from_seed.state);
+        for (&Wrapping(x), &y) in rng.state.iter().zip(STATE_SEEDED_BY_U32.iter()) {
+            assert_eq!(x, y);
+        }
+        for (&Wrapping(x), &y) in rng_from_seed.state.iter().zip(STATE_SEEDED_BY_U32.iter()) {
+            assert_eq!(x, y);
+        }
+    }
+
+    #[test]
+    fn output_from_u32_slice_key() {
+        let key = [0x123_u32, 0x234_u32, 0x345_u32, 0x456_u32];
+        let mut rng = Mt19937GenRand32::new_with_key(key.iter().copied());
+        for &x in &TEST_OUTPUT {
+            assert_eq!(x, RngCore::next_u32(&mut rng));
+        }
+    }
+}
+
\ No newline at end of file diff --git a/src/rand_mt/mt64.rs.html b/src/rand_mt/mt64.rs.html new file mode 100644 index 000000000..6f5c07065 --- /dev/null +++ b/src/rand_mt/mt64.rs.html @@ -0,0 +1,1357 @@ +mt64.rs - source

rand_mt/
mt64.rs

+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
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
+224
+225
+226
+227
+228
+229
+230
+231
+232
+233
+234
+235
+236
+237
+238
+239
+240
+241
+242
+243
+244
+245
+246
+247
+248
+249
+250
+251
+252
+253
+254
+255
+256
+257
+258
+259
+260
+261
+262
+263
+264
+265
+266
+267
+268
+269
+270
+271
+272
+273
+274
+275
+276
+277
+278
+279
+280
+281
+282
+283
+284
+285
+286
+287
+288
+289
+290
+291
+292
+293
+294
+295
+296
+297
+298
+299
+300
+301
+302
+303
+304
+305
+306
+307
+308
+309
+310
+311
+312
+313
+314
+315
+316
+317
+318
+319
+320
+321
+322
+323
+324
+325
+326
+327
+328
+329
+330
+331
+332
+333
+334
+335
+336
+337
+338
+339
+340
+341
+342
+343
+344
+345
+346
+347
+348
+349
+350
+351
+352
+353
+354
+355
+356
+357
+358
+359
+360
+361
+362
+363
+364
+365
+366
+367
+368
+369
+370
+371
+372
+373
+374
+375
+376
+377
+378
+379
+380
+381
+382
+383
+384
+385
+386
+387
+388
+389
+390
+391
+392
+393
+394
+395
+396
+397
+398
+399
+400
+401
+402
+403
+404
+405
+406
+407
+408
+409
+410
+411
+412
+413
+414
+415
+416
+417
+418
+419
+420
+421
+422
+423
+424
+425
+426
+427
+428
+429
+430
+431
+432
+433
+434
+435
+436
+437
+438
+439
+440
+441
+442
+443
+444
+445
+446
+447
+448
+449
+450
+451
+452
+453
+454
+455
+456
+457
+458
+459
+460
+461
+462
+463
+464
+465
+466
+467
+468
+469
+470
+471
+472
+473
+474
+475
+476
+477
+478
+479
+480
+481
+482
+483
+484
+485
+486
+487
+488
+489
+490
+491
+492
+493
+494
+495
+496
+497
+498
+499
+500
+501
+502
+503
+504
+505
+506
+507
+508
+509
+510
+511
+512
+513
+514
+515
+516
+517
+518
+519
+520
+521
+522
+523
+524
+525
+526
+527
+528
+529
+530
+531
+532
+533
+534
+535
+536
+537
+538
+539
+540
+541
+542
+543
+544
+545
+546
+547
+548
+549
+550
+551
+552
+553
+554
+555
+556
+557
+558
+559
+560
+561
+562
+563
+564
+565
+566
+567
+568
+569
+570
+571
+572
+573
+574
+575
+576
+577
+578
+579
+580
+581
+582
+583
+584
+585
+586
+587
+588
+589
+590
+591
+592
+593
+594
+595
+596
+597
+598
+599
+600
+601
+602
+603
+604
+605
+606
+607
+608
+609
+610
+611
+612
+613
+614
+615
+616
+617
+618
+619
+620
+621
+622
+623
+624
+625
+626
+627
+628
+629
+630
+631
+632
+633
+634
+635
+636
+637
+638
+639
+640
+641
+642
+643
+644
+645
+646
+647
+648
+649
+650
+651
+652
+653
+654
+655
+656
+657
+658
+659
+660
+661
+662
+663
+664
+665
+666
+667
+668
+669
+670
+671
+672
+673
+674
+675
+676
+677
+678
// src/mt64.rs
+//
+// Copyright (c) 2015,2017 rust-mersenne-twister developers
+// Copyright (c) 2020 Ryan Lopopolo <rjl@hyperbo.la>
+//
+// Licensed under the Apache License, Version 2.0
+// <LICENSE-APACHE> or <http://www.apache.org/licenses/LICENSE-2.0> or the MIT
+// license <LICENSE-MIT> or <http://opensource.org/licenses/MIT>, at your
+// option. All files in the project carrying such notice may not be copied,
+// modified, or distributed except according to those terms.
+
+use core::convert::TryFrom;
+use core::fmt;
+use core::mem::size_of;
+use core::num::Wrapping;
+
+use crate::RecoverRngError;
+
+#[cfg(feature = "rand-traits")]
+mod rand;
+
+const NN: usize = 312;
+const MM: usize = 156;
+const ONE: Wrapping<u64> = Wrapping(1);
+const MATRIX_A: Wrapping<u64> = Wrapping(0xb502_6f5a_a966_19e9);
+const UM: Wrapping<u64> = Wrapping(0xffff_ffff_8000_0000); // Most significant 33 bits
+const LM: Wrapping<u64> = Wrapping(0x7fff_ffff); // Least significant 31 bits
+
+/// The 64-bit flavor of the Mersenne Twister pseudorandom number
+/// generator.
+///
+/// # Size
+///
+/// `Mt19937GenRand64` requires approximately 2.5 kilobytes of internal state.
+///
+/// You may wish to store an `Mt19937GenRand64` on the heap in a [`Box`] to make it
+/// easier to embed in another struct.
+///
+/// `Mt19937GenRand64` is also the same size as
+/// [`Mt19937GenRand32`](crate::Mt19937GenRand32).
+///
+/// ```
+/// # use core::mem;
+/// # use rand_mt::{Mt19937GenRand32, Mt19937GenRand64};
+/// assert_eq!(2504, mem::size_of::<Mt19937GenRand64>());
+/// assert_eq!(mem::size_of::<Mt19937GenRand32>(), mem::size_of::<Mt19937GenRand64>());
+/// ```
+#[cfg_attr(feature = "std", doc = "[`Box`]: std::boxed::Box")]
+#[cfg_attr(
+    not(feature = "std"),
+    doc = "[`Box`]: https://doc.rust-lang.org/std/boxed/struct.Box.html"
+)]
+#[derive(Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
+pub struct Mt19937GenRand64 {
+    idx: usize,
+    state: [Wrapping<u64>; NN],
+}
+
+impl fmt::Debug for Mt19937GenRand64 {
+    #[inline]
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        f.write_str("Mt19937GenRand64 {}")
+    }
+}
+
+impl Default for Mt19937GenRand64 {
+    /// Return a new `Mt19937GenRand64` with the default seed.
+    ///
+    /// Equivalent to calling [`Mt19937GenRand64::new_unseeded`].
+    #[inline]
+    fn default() -> Self {
+        Self::new_unseeded()
+    }
+}
+
+impl From<[u8; 8]> for Mt19937GenRand64 {
+    /// Construct a Mersenne Twister RNG from 8 bytes.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use rand_mt::Mt19937GenRand64;
+    /// // Default MT seed
+    /// let seed = 5489_u64.to_le_bytes();
+    /// let mut mt = Mt19937GenRand64::from(seed);
+    /// assert_ne!(mt.next_u64(), mt.next_u64());
+    /// ```
+    #[inline]
+    fn from(seed: [u8; 8]) -> Self {
+        Self::new(u64::from_le_bytes(seed))
+    }
+}
+
+impl From<u64> for Mt19937GenRand64 {
+    /// Construct a Mersenne Twister RNG from a `u64` seed.
+    ///
+    /// This function is equivalent to [`new`].
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use rand_mt::Mt19937GenRand64;
+    /// // Default MT seed
+    /// let seed = 5489_u64;
+    /// let mt1 = Mt19937GenRand64::from(seed);
+    /// let mt2 = Mt19937GenRand64::new(seed);
+    /// assert_eq!(mt1, mt2);
+    ///
+    /// // Non-default MT seed
+    /// let seed = 9927_u64;
+    /// let mt1 = Mt19937GenRand64::from(seed);
+    /// let mt2 = Mt19937GenRand64::new(seed);
+    /// assert_eq!(mt1, mt2);
+    /// ```
+    ///
+    /// [`new`]: Self::new
+    #[inline]
+    fn from(seed: u64) -> Self {
+        Self::new(seed)
+    }
+}
+
+impl From<[u64; NN]> for Mt19937GenRand64 {
+    /// Recover the internal state of a Mersenne Twister using the past 312
+    /// samples.
+    ///
+    /// This conversion takes a history of samples from a RNG and returns a
+    /// RNG that will produce identical output to the RNG that supplied the
+    /// samples.
+    #[inline]
+    fn from(key: [u64; NN]) -> Self {
+        let mut mt = Self {
+            idx: NN,
+            state: [Wrapping(0); NN],
+        };
+        for (sample, out) in key.iter().copied().zip(mt.state.iter_mut()) {
+            *out = Wrapping(untemper(sample));
+        }
+        mt
+    }
+}
+
+impl TryFrom<&[u64]> for Mt19937GenRand64 {
+    type Error = RecoverRngError;
+
+    /// Attempt to recover the internal state of a Mersenne Twister using the
+    /// past 312 samples.
+    ///
+    /// This conversion takes a history of samples from a RNG and returns a
+    /// RNG that will produce identical output to the RNG that supplied the
+    /// samples.
+    ///
+    /// This conversion is implemented with [`Mt19937GenRand64::recover`].
+    ///
+    /// # Errors
+    ///
+    /// If `key` has less than 312 elements, an error is returned because there
+    /// is not enough data to fully initialize the RNG.
+    ///
+    /// If `key` has more than 312 elements, an error is returned because the
+    /// recovered RNG will not produce identical output to the RNG that supplied
+    /// the samples.
+    #[inline]
+    fn try_from(key: &[u64]) -> Result<Self, Self::Error> {
+        Self::recover(key.iter().copied())
+    }
+}
+
+impl Mt19937GenRand64 {
+    /// Default seed used by [`Mt19937GenRand64::new_unseeded`].
+    pub const DEFAULT_SEED: u64 = 5489_u64;
+
+    /// Create a new Mersenne Twister random number generator using the given
+    /// seed.
+    ///
+    /// # Examples
+    ///
+    /// ## Constructing with a `u64` seed
+    ///
+    /// ```
+    /// # use rand_mt::Mt19937GenRand64;
+    /// let seed = 123_456_789_u64;
+    /// let mt1 = Mt19937GenRand64::new(seed);
+    /// let mt2 = Mt19937GenRand64::from(seed.to_le_bytes());
+    /// assert_eq!(mt1, mt2);
+    /// ```
+    ///
+    /// ## Constructing with default seed
+    ///
+    /// ```
+    /// # use rand_mt::Mt19937GenRand64;
+    /// let mt1 = Mt19937GenRand64::new(Mt19937GenRand64::DEFAULT_SEED);
+    /// let mt2 = Mt19937GenRand64::new_unseeded();
+    /// assert_eq!(mt1, mt2);
+    /// ```
+    #[inline]
+    #[must_use]
+    pub fn new(seed: u64) -> Self {
+        let mut mt = Self {
+            idx: 0,
+            state: [Wrapping(0); NN],
+        };
+        mt.reseed(seed);
+        mt
+    }
+
+    /// Create a new Mersenne Twister random number generator using the given
+    /// key.
+    ///
+    /// Key can have any length.
+    #[inline]
+    #[must_use]
+    pub fn new_with_key<I>(key: I) -> Self
+    where
+        I: IntoIterator<Item = u64>,
+        I::IntoIter: Clone,
+    {
+        let mut mt = Self {
+            idx: 0,
+            state: [Wrapping(0); NN],
+        };
+        mt.reseed_with_key(key);
+        mt
+    }
+
+    /// Create a new Mersenne Twister random number generator using the default
+    /// fixed seed.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use rand_mt::Mt19937GenRand64;
+    /// // Default MT seed
+    /// let seed = 5489_u64;
+    /// let mt = Mt19937GenRand64::new(seed);
+    /// let unseeded = Mt19937GenRand64::new_unseeded();
+    /// assert_eq!(mt, unseeded);
+    /// ```
+    #[inline]
+    #[must_use]
+    pub fn new_unseeded() -> Self {
+        Self::new(Self::DEFAULT_SEED)
+    }
+
+    /// Generate next `u64` output.
+    ///
+    /// `u64` is the native output of the generator. This function advances the
+    /// RNG step counter by one.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use rand_mt::Mt19937GenRand64;
+    /// let mut mt = Mt19937GenRand64::new_unseeded();
+    /// assert_ne!(mt.next_u64(), mt.next_u64());
+    /// ```
+    #[inline]
+    pub fn next_u64(&mut self) -> u64 {
+        // Failing this check indicates that, somehow, the structure
+        // was not initialized.
+        debug_assert!(self.idx != 0);
+        if self.idx >= NN {
+            fill_next_state(self);
+        }
+        let Wrapping(x) = self.state[self.idx];
+        self.idx += 1;
+        temper(x)
+    }
+
+    /// Generate next `u32` output.
+    ///
+    /// This function is implemented by generating one `u64` from the RNG and
+    /// performing shifting and masking to turn it into a `u32` output.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use rand_mt::Mt19937GenRand64;
+    /// let mut mt = Mt19937GenRand64::new_unseeded();
+    /// assert_ne!(mt.next_u32(), mt.next_u32());
+    /// ```
+    #[inline]
+    #[allow(clippy::cast_possible_truncation)]
+    pub fn next_u32(&mut self) -> u32 {
+        self.next_u64() as u32
+    }
+
+    /// Fill a buffer with bytes generated from the RNG.
+    ///
+    /// This method generates random `u64`s (the native output unit of the RNG)
+    /// until `dest` is filled.
+    ///
+    /// This method may discard some output bits if `dest.len()` is not a
+    /// multiple of 8.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use rand_mt::Mt19937GenRand64;
+    /// let mut mt = Mt19937GenRand64::new_unseeded();
+    /// let mut buf = [0; 32];
+    /// mt.fill_bytes(&mut buf);
+    /// assert_ne!([0; 32], buf);
+    /// let mut buf = [0; 31];
+    /// mt.fill_bytes(&mut buf);
+    /// assert_ne!([0; 31], buf);
+    /// ```
+    #[inline]
+    pub fn fill_bytes(&mut self, dest: &mut [u8]) {
+        const CHUNK: usize = size_of::<u64>();
+        let mut dest_chunks = dest.chunks_exact_mut(CHUNK);
+
+        for next in &mut dest_chunks {
+            let chunk: [u8; CHUNK] = self.next_u64().to_le_bytes();
+            next.copy_from_slice(&chunk);
+        }
+
+        let remainder = dest_chunks.into_remainder();
+        if remainder.is_empty() {
+            return;
+        }
+        remainder
+            .iter_mut()
+            .zip(self.next_u64().to_le_bytes().iter())
+            .for_each(|(cell, &byte)| {
+                *cell = byte;
+            });
+    }
+
+    /// Attempt to recover the internal state of a Mersenne Twister using the
+    /// past 312 samples.
+    ///
+    /// This conversion takes a history of samples from a RNG and returns a
+    /// RNG that will produce identical output to the RNG that supplied the
+    /// samples.
+    ///
+    /// This constructor is also available as a [`TryFrom`] implementation for
+    /// `&[u32]`.
+    ///
+    /// # Errors
+    ///
+    /// If `key` has less than 312 elements, an error is returned because there
+    /// is not enough data to fully initialize the RNG.
+    ///
+    /// If `key` has more than 312 elements, an error is returned because the
+    /// recovered RNG will not produce identical output to the RNG that supplied
+    /// the samples.
+    #[inline]
+    pub fn recover<I>(key: I) -> Result<Self, RecoverRngError>
+    where
+        I: IntoIterator<Item = u64>,
+    {
+        let mut mt = Self {
+            idx: NN,
+            state: [Wrapping(0); NN],
+        };
+        let mut state = mt.state.iter_mut();
+        for sample in key {
+            let out = state.next().ok_or(RecoverRngError::TooManySamples(NN))?;
+            *out = Wrapping(untemper(sample));
+        }
+        // If the state iterator still has unfilled cells, the given iterator
+        // was too short. If there are no additional cells, return the
+        // initialized RNG.
+        if state.next().is_none() {
+            Ok(mt)
+        } else {
+            Err(RecoverRngError::TooFewSamples(NN))
+        }
+    }
+
+    /// Reseed a Mersenne Twister from a single `u64`.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use rand_mt::Mt19937GenRand64;
+    /// // Default MT seed
+    /// let mut mt = Mt19937GenRand64::new_unseeded();
+    /// let first = mt.next_u64();
+    /// mt.fill_bytes(&mut [0; 512]);
+    /// // Default MT seed
+    /// mt.reseed(5489_u64);
+    /// assert_eq!(first, mt.next_u64());
+    /// ```
+    #[inline]
+    pub fn reseed(&mut self, seed: u64) {
+        self.idx = NN;
+        self.state[0] = Wrapping(seed);
+        for i in 1..NN {
+            self.state[i] = Wrapping(6_364_136_223_846_793_005)
+                * (self.state[i - 1] ^ (self.state[i - 1] >> 62))
+                + Wrapping(i as u64);
+        }
+    }
+
+    /// Reseed a Mersenne Twister from am iterator of `u64`s.
+    ///
+    /// Key can have any length.
+    #[inline]
+    #[allow(clippy::cast_possible_truncation)]
+    pub fn reseed_with_key<I>(&mut self, key: I)
+    where
+        I: IntoIterator<Item = u64>,
+        I::IntoIter: Clone,
+    {
+        self.reseed(19_650_218_u64);
+        let mut i = 1_usize;
+        for (j, piece) in key.into_iter().enumerate().cycle().take(NN) {
+            self.state[i] = (self.state[i]
+                ^ ((self.state[i - 1] ^ (self.state[i - 1] >> 62))
+                    * Wrapping(3_935_559_000_370_003_845)))
+                + Wrapping(piece)
+                + Wrapping(j as u64);
+            i += 1;
+            if i >= NN {
+                self.state[0] = self.state[NN - 1];
+                i = 1;
+            }
+        }
+        for _ in 0..NN - 1 {
+            self.state[i] = (self.state[i]
+                ^ ((self.state[i - 1] ^ (self.state[i - 1] >> 62))
+                    * Wrapping(2_862_933_555_777_941_757)))
+                - Wrapping(i as u64);
+            i += 1;
+            if i >= NN {
+                self.state[0] = self.state[NN - 1];
+                i = 1;
+            }
+        }
+        self.state[0] = Wrapping(1 << 63);
+    }
+}
+
+#[inline]
+fn temper(mut x: u64) -> u64 {
+    x ^= (x >> 29) & 0x5555_5555_5555_5555;
+    x ^= (x << 17) & 0x71d6_7fff_eda6_0000;
+    x ^= (x << 37) & 0xfff7_eee0_0000_0000;
+    x ^= x >> 43;
+    x
+}
+
+#[inline]
+fn untemper(mut x: u64) -> u64 {
+    // reverse `x ^=  x >> 43;`
+    x ^= x >> 43;
+
+    // reverse `x ^= (x << 37) & 0xfff7_eee0_0000_0000;`
+    x ^= (x << 37) & 0xfff7_eee0_0000_0000;
+
+    // reverse `x ^= (x << 17) & 0x71d6_7fff_eda6_0000;`
+    x ^= (x << 17) & 0x0000_0003_eda6_0000;
+    x ^= (x << 17) & 0x0006_7ffc_0000_0000;
+    x ^= (x << 17) & 0x71d0_0000_0000_0000;
+
+    // reverse `x ^= (x >> 29) & 0x5555_5555_5555_5555;`
+    x ^= (x >> 29) & 0x0000_0005_5555_5540;
+    x ^= (x >> 29) & 0x0000_0000_0000_0015;
+
+    x
+}
+
+#[inline]
+fn fill_next_state(rng: &mut Mt19937GenRand64) {
+    for i in 0..NN - MM {
+        let x = (rng.state[i] & UM) | (rng.state[i + 1] & LM);
+        rng.state[i] = rng.state[i + MM] ^ (x >> 1) ^ ((x & ONE) * MATRIX_A);
+    }
+    for i in NN - MM..NN - 1 {
+        let x = (rng.state[i] & UM) | (rng.state[i + 1] & LM);
+        rng.state[i] = rng.state[i + MM - NN] ^ (x >> 1) ^ ((x & ONE) * MATRIX_A);
+    }
+    let x = (rng.state[NN - 1] & UM) | (rng.state[0] & LM);
+    rng.state[NN - 1] = rng.state[MM - 1] ^ (x >> 1) ^ ((x & ONE) * MATRIX_A);
+    rng.idx = 0;
+}
+
+#[cfg(test)]
+mod tests {
+    use core::convert::TryFrom;
+    use core::num::Wrapping;
+
+    use super::{Mt19937GenRand64, NN};
+    use crate::vectors::mt64::{STATE_SEEDED_BY_SLICE, STATE_SEEDED_BY_U64, TEST_OUTPUT};
+    use crate::RecoverRngError;
+
+    #[test]
+    fn seeded_state_from_u64_seed() {
+        let mt = Mt19937GenRand64::new(0x0123_4567_89ab_cdef_u64);
+        let mt_from_seed = Mt19937GenRand64::from(0x0123_4567_89ab_cdef_u64.to_le_bytes());
+        assert_eq!(mt.state, mt_from_seed.state);
+        for (&Wrapping(x), &y) in mt.state.iter().zip(STATE_SEEDED_BY_U64.iter()) {
+            assert_eq!(x, y);
+        }
+        for (&Wrapping(x), &y) in mt_from_seed.state.iter().zip(STATE_SEEDED_BY_U64.iter()) {
+            assert_eq!(x, y);
+        }
+    }
+
+    #[test]
+    fn seeded_state_from_u64_slice_key() {
+        let key = [0x12345_u64, 0x23456_u64, 0x34567_u64, 0x45678_u64];
+        let mt = Mt19937GenRand64::new_with_key(key.iter().copied());
+        for (&Wrapping(x), &y) in mt.state.iter().zip(STATE_SEEDED_BY_SLICE.iter()) {
+            assert_eq!(x, y);
+        }
+    }
+
+    #[test]
+    fn seed_with_empty_iter_returns() {
+        let _rng = Mt19937GenRand64::new_with_key(core::iter::empty());
+    }
+
+    #[test]
+    fn output_from_u64_slice_key() {
+        let key = [0x12345_u64, 0x23456_u64, 0x34567_u64, 0x45678_u64];
+        let mut mt = Mt19937GenRand64::new_with_key(key.iter().copied());
+        for &x in &TEST_OUTPUT {
+            assert_eq!(x, mt.next_u64());
+        }
+    }
+
+    #[test]
+    fn temper_untemper_is_identity() {
+        let mut buf = [0; 8];
+        for _ in 0..10_000 {
+            getrandom::getrandom(&mut buf).unwrap();
+            let x = u64::from_le_bytes(buf);
+            assert_eq!(x, super::untemper(super::temper(x)));
+            let x = u64::from_be_bytes(buf);
+            assert_eq!(x, super::untemper(super::temper(x)));
+        }
+    }
+
+    #[test]
+    fn untemper_temper_is_identity() {
+        let mut buf = [0; 8];
+        for _ in 0..10_000 {
+            getrandom::getrandom(&mut buf).unwrap();
+            let x = u64::from_le_bytes(buf);
+            assert_eq!(x, super::temper(super::untemper(x)));
+            let x = u64::from_be_bytes(buf);
+            assert_eq!(x, super::temper(super::untemper(x)));
+        }
+    }
+
+    #[test]
+    fn recovery_via_from() {
+        let mut buf = [0; 8];
+        for _ in 0..100 {
+            getrandom::getrandom(&mut buf).unwrap();
+            let seed = u64::from_le_bytes(buf);
+            for skip in 0..256 {
+                let mut orig_mt = Mt19937GenRand64::new(seed);
+                // skip some samples so the RNG is in an intermediate state
+                for _ in 0..skip {
+                    orig_mt.next_u64();
+                }
+                let mut samples = [0; 312];
+                for sample in &mut samples {
+                    *sample = orig_mt.next_u64();
+                }
+                let mut recovered_mt = Mt19937GenRand64::from(samples);
+                for _ in 0..312 * 2 {
+                    assert_eq!(orig_mt.next_u64(), recovered_mt.next_u64());
+                }
+            }
+        }
+    }
+
+    #[test]
+    fn recovery_via_recover() {
+        let mut buf = [0; 8];
+        for _ in 0..100 {
+            getrandom::getrandom(&mut buf).unwrap();
+            let seed = u64::from_le_bytes(buf);
+            for skip in 0..256 {
+                let mut orig_mt = Mt19937GenRand64::new(seed);
+                // skip some samples so the RNG is in an intermediate state
+                for _ in 0..skip {
+                    orig_mt.next_u64();
+                }
+                let mut samples = [0; 312];
+                for sample in &mut samples {
+                    *sample = orig_mt.next_u64();
+                }
+                let mut recovered_mt = Mt19937GenRand64::recover(samples.iter().copied()).unwrap();
+                for _ in 0..312 * 2 {
+                    assert_eq!(orig_mt.next_u64(), recovered_mt.next_u64());
+                }
+            }
+        }
+    }
+
+    #[test]
+    fn recover_required_exact_sample_length_via_from() {
+        assert_eq!(
+            Mt19937GenRand64::try_from(&[0; 0][..]),
+            Err(RecoverRngError::TooFewSamples(NN))
+        );
+        assert_eq!(
+            Mt19937GenRand64::try_from(&[0; 1][..]),
+            Err(RecoverRngError::TooFewSamples(NN))
+        );
+        assert_eq!(
+            Mt19937GenRand64::try_from(&[0; 311][..]),
+            Err(RecoverRngError::TooFewSamples(NN))
+        );
+        Mt19937GenRand64::try_from(&[0; 312][..]).unwrap();
+        assert_eq!(
+            Mt19937GenRand64::try_from(&[0; 313][..]),
+            Err(RecoverRngError::TooManySamples(NN))
+        );
+        assert_eq!(
+            Mt19937GenRand64::try_from(&[0; 1000][..]),
+            Err(RecoverRngError::TooManySamples(NN))
+        );
+    }
+
+    #[test]
+    fn recover_required_exact_sample_length_via_recover() {
+        assert_eq!(
+            Mt19937GenRand64::recover([0; 0].iter().copied()),
+            Err(RecoverRngError::TooFewSamples(NN))
+        );
+        assert_eq!(
+            Mt19937GenRand64::recover([0; 1].iter().copied()),
+            Err(RecoverRngError::TooFewSamples(NN))
+        );
+        assert_eq!(
+            Mt19937GenRand64::recover([0; 311].iter().copied()),
+            Err(RecoverRngError::TooFewSamples(NN))
+        );
+        Mt19937GenRand64::recover([0; 312].iter().copied()).unwrap();
+        assert_eq!(
+            Mt19937GenRand64::recover([0; 313].iter().copied()),
+            Err(RecoverRngError::TooManySamples(NN))
+        );
+        assert_eq!(
+            Mt19937GenRand64::recover([0; 1000].iter().copied()),
+            Err(RecoverRngError::TooManySamples(NN))
+        );
+    }
+
+    #[test]
+    #[cfg(feature = "std")]
+    fn fmt_debug_does_not_leak_seed() {
+        use core::fmt::Write as _;
+        use std::string::String;
+
+        let random = Mt19937GenRand64::new(874);
+
+        let mut buf = String::new();
+        write!(&mut buf, "{:?}", random).unwrap();
+        assert!(!buf.contains("874"));
+        assert_eq!(buf, "Mt19937GenRand64 {}");
+
+        let random = Mt19937GenRand64::new(123_456);
+
+        let mut buf = String::new();
+        write!(&mut buf, "{:?}", random).unwrap();
+        assert!(!buf.contains("123456"));
+        assert_eq!(buf, "Mt19937GenRand64 {}");
+    }
+
+    #[test]
+    fn default_is_new_unseeded() {
+        let mut default = Mt19937GenRand64::default();
+        let mut unseeded = Mt19937GenRand64::new_unseeded();
+
+        assert_eq!(default, unseeded);
+        for _ in 0..1024 {
+            assert_eq!(default.next_u64(), unseeded.next_u64());
+        }
+    }
+}
+
\ No newline at end of file diff --git a/src/rand_mt/mt64/rand.rs.html b/src/rand_mt/mt64/rand.rs.html new file mode 100644 index 000000000..c9bfc78dd --- /dev/null +++ b/src/rand_mt/mt64/rand.rs.html @@ -0,0 +1,355 @@ +rand.rs - source

rand_mt/mt64/
rand.rs

+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
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
// src/mt64/rand.rs
+//
+// Copyright (c) 2015,2017 rust-mersenne-twister developers
+// Copyright (c) 2020 Ryan Lopopolo <rjl@hyperbo.la>
+//
+// Licensed under the Apache License, Version 2.0
+// <LICENSE-APACHE> or <http://www.apache.org/licenses/LICENSE-2.0> or the MIT
+// license <LICENSE-MIT> or <http://opensource.org/licenses/MIT>, at your
+// option. All files in the project carrying such notice may not be copied,
+// modified, or distributed except according to those terms.
+
+use rand_core::{Error, RngCore, SeedableRng};
+
+use super::Mt19937GenRand64;
+
+impl SeedableRng for Mt19937GenRand64 {
+    type Seed = [u8; 8];
+
+    /// Reseed from a little endian encoded `u64`.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use rand_core::{RngCore, SeedableRng};
+    /// # use rand_mt::Mt19937GenRand64;
+    /// // Default MT seed
+    /// let seed = 5489_u64.to_le_bytes();
+    /// let mut mt = Mt19937GenRand64::from_seed(seed);
+    /// assert_ne!(mt.next_u64(), mt.next_u64());
+    /// ```
+    #[inline]
+    fn from_seed(seed: Self::Seed) -> Self {
+        Self::from(seed)
+    }
+}
+
+impl RngCore for Mt19937GenRand64 {
+    /// Generate next `u64` output.
+    ///
+    /// `u64` is the native output of the generator. This function advances the
+    /// RNG step counter by one.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use rand_core::RngCore;
+    /// use rand_mt::Mt19937GenRand64;
+    ///
+    /// let mut rng = Mt19937GenRand64::new_unseeded();
+    /// # fn example<T: RngCore>(mut rng: T) {
+    /// assert_ne!(rng.next_u64(), rng.next_u64());
+    /// # }
+    /// # example(rng);
+    /// ```
+    #[inline]
+    fn next_u64(&mut self) -> u64 {
+        Self::next_u64(self)
+    }
+
+    /// Generate next `u32` output.
+    ///
+    /// This function is implemented by generating one `u64` from the RNG and
+    /// performing shifting and masking to turn it into a `u32` output.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use rand_core::RngCore;
+    /// use rand_mt::Mt19937GenRand64;
+    ///
+    /// let mut rng = Mt19937GenRand64::new_unseeded();
+    /// # fn example<T: RngCore>(mut rng: T) {
+    /// assert_ne!(rng.next_u32(), rng.next_u32());
+    /// # }
+    /// # example(rng);
+    /// ```
+    #[inline]
+    fn next_u32(&mut self) -> u32 {
+        Self::next_u32(self)
+    }
+
+    /// Fill a buffer with bytes generated from the RNG.
+    ///
+    /// This method generates random `u64`s (the native output unit of the RNG)
+    /// until `dest` is filled.
+    ///
+    /// This method may discard some output bits if `dest.len()` is not a
+    /// multiple of 8.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use rand_core::RngCore;
+    /// use rand_mt::Mt19937GenRand64;
+    ///
+    /// let mut rng = Mt19937GenRand64::new_unseeded();
+    /// # fn example<T: RngCore>(mut rng: T) {
+    /// let mut buf = [0; 32];
+    /// rng.fill_bytes(&mut buf);
+    /// assert_ne!([0; 32], buf);
+    /// let mut buf = [0; 31];
+    /// rng.fill_bytes(&mut buf);
+    /// assert_ne!([0; 31], buf);
+    /// # }
+    /// # example(rng);
+    /// ```
+    #[inline]
+    fn fill_bytes(&mut self, dest: &mut [u8]) {
+        Self::fill_bytes(self, dest);
+    }
+
+    /// Fill a buffer with bytes generated from the RNG.
+    ///
+    /// This method generates random `u64`s (the native output unit of the RNG)
+    /// until `dest` is filled.
+    ///
+    /// This method may discard some output bits if `dest.len()` is not a
+    /// multiple of 8.
+    ///
+    /// `try_fill_bytes` is implemented with [`fill_bytes`](RngCore::fill_bytes)
+    /// and is infallible.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use rand_core::RngCore;
+    /// use rand_mt::Mt19937GenRand64;
+    ///
+    /// let mut rng = Mt19937GenRand64::new_unseeded();
+    /// # fn example<T: RngCore>(mut rng: T) -> Result<(), rand_core::Error> {
+    /// let mut buf = [0; 32];
+    /// rng.try_fill_bytes(&mut buf)?;
+    /// assert_ne!([0; 32], buf);
+    /// let mut buf = [0; 31];
+    /// rng.try_fill_bytes(&mut buf)?;
+    /// assert_ne!([0; 31], buf);
+    /// # Ok(())
+    /// # }
+    /// # example(rng).unwrap()
+    /// ```
+    #[inline]
+    fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
+        Self::fill_bytes(self, dest);
+        Ok(())
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use core::num::Wrapping;
+    use rand_core::{RngCore, SeedableRng};
+
+    use super::Mt19937GenRand64;
+    use crate::vectors::mt64::{STATE_SEEDED_BY_U64, TEST_OUTPUT};
+
+    #[test]
+    fn seeded_state_from_u64_seed() {
+        let mt = Mt19937GenRand64::new(0x0123_4567_89ab_cdef_u64);
+        let mt_from_seed = Mt19937GenRand64::from_seed(0x0123_4567_89ab_cdef_u64.to_le_bytes());
+        assert_eq!(mt.state, mt_from_seed.state);
+        for (&Wrapping(x), &y) in mt.state.iter().zip(STATE_SEEDED_BY_U64.iter()) {
+            assert_eq!(x, y);
+        }
+        for (&Wrapping(x), &y) in mt_from_seed.state.iter().zip(STATE_SEEDED_BY_U64.iter()) {
+            assert_eq!(x, y);
+        }
+    }
+
+    #[test]
+    fn output_from_u64_slice_key() {
+        let key = [0x12345_u64, 0x23456_u64, 0x34567_u64, 0x45678_u64];
+        let mut mt = Mt19937GenRand64::new_with_key(key.iter().copied());
+        for &x in &TEST_OUTPUT {
+            assert_eq!(x, RngCore::next_u64(&mut mt));
+        }
+    }
+}
+
\ No newline at end of file diff --git a/static.files/COPYRIGHT-eb44e4cf.txt b/static.files/COPYRIGHT-eb44e4cf.txt new file mode 100644 index 000000000..1447df792 --- /dev/null +++ b/static.files/COPYRIGHT-eb44e4cf.txt @@ -0,0 +1,50 @@ +# REUSE-IgnoreStart + +These documentation pages include resources by third parties. This copyright +file applies only to those resources. The following third party resources are +included, and carry their own copyright notices and license terms: + +* Fira Sans (FiraSans-Regular.woff2, FiraSans-Medium.woff2): + + Copyright (c) 2014, Mozilla Foundation https://mozilla.org/ + with Reserved Font Name Fira Sans. + + Copyright (c) 2014, Telefonica S.A. + + Licensed under the SIL Open Font License, Version 1.1. + See FiraSans-LICENSE.txt. + +* rustdoc.css, main.js, and playpen.js: + + Copyright 2015 The Rust Developers. + Licensed under the Apache License, Version 2.0 (see LICENSE-APACHE.txt) or + the MIT license (LICENSE-MIT.txt) at your option. + +* normalize.css: + + Copyright (c) Nicolas Gallagher and Jonathan Neal. + Licensed under the MIT license (see LICENSE-MIT.txt). + +* Source Code Pro (SourceCodePro-Regular.ttf.woff2, + SourceCodePro-Semibold.ttf.woff2, SourceCodePro-It.ttf.woff2): + + Copyright 2010, 2012 Adobe Systems Incorporated (http://www.adobe.com/), + with Reserved Font Name 'Source'. All Rights Reserved. Source is a trademark + of Adobe Systems Incorporated in the United States and/or other countries. + + Licensed under the SIL Open Font License, Version 1.1. + See SourceCodePro-LICENSE.txt. + +* Source Serif 4 (SourceSerif4-Regular.ttf.woff2, SourceSerif4-Bold.ttf.woff2, + SourceSerif4-It.ttf.woff2): + + Copyright 2014-2021 Adobe (http://www.adobe.com/), with Reserved Font Name + 'Source'. All Rights Reserved. Source is a trademark of Adobe in the United + States and/or other countries. + + Licensed under the SIL Open Font License, Version 1.1. + See SourceSerif4-LICENSE.md. + +This copyright file is intended to be distributed with rustdoc output. + +# REUSE-IgnoreEnd diff --git a/static.files/FiraSans-LICENSE-05ab6dbd.txt b/static.files/FiraSans-LICENSE-05ab6dbd.txt new file mode 100644 index 000000000..d7e9c149b --- /dev/null +++ b/static.files/FiraSans-LICENSE-05ab6dbd.txt @@ -0,0 +1,98 @@ +// REUSE-IgnoreStart + +Digitized data copyright (c) 2012-2015, The Mozilla Foundation and Telefonica S.A. +with Reserved Font Name < Fira >, + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. + +// REUSE-IgnoreEnd diff --git a/static.files/FiraSans-Medium-e1aa3f0a.woff2 b/static.files/FiraSans-Medium-e1aa3f0a.woff2 new file mode 100644 index 000000000..7a1e5fc54 Binary files /dev/null and b/static.files/FiraSans-Medium-e1aa3f0a.woff2 differ diff --git a/static.files/FiraSans-Regular-0fe48ade.woff2 b/static.files/FiraSans-Regular-0fe48ade.woff2 new file mode 100644 index 000000000..e766e06cc Binary files /dev/null and b/static.files/FiraSans-Regular-0fe48ade.woff2 differ diff --git a/static.files/LICENSE-APACHE-a60eea81.txt b/static.files/LICENSE-APACHE-a60eea81.txt new file mode 100644 index 000000000..16fe87b06 --- /dev/null +++ b/static.files/LICENSE-APACHE-a60eea81.txt @@ -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/static.files/LICENSE-MIT-23f18e03.txt b/static.files/LICENSE-MIT-23f18e03.txt new file mode 100644 index 000000000..31aa79387 --- /dev/null +++ b/static.files/LICENSE-MIT-23f18e03.txt @@ -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/static.files/NanumBarunGothic-13b3dcba.ttf.woff2 b/static.files/NanumBarunGothic-13b3dcba.ttf.woff2 new file mode 100644 index 000000000..1866ad4bc Binary files /dev/null and b/static.files/NanumBarunGothic-13b3dcba.ttf.woff2 differ diff --git a/static.files/NanumBarunGothic-LICENSE-a37d393b.txt b/static.files/NanumBarunGothic-LICENSE-a37d393b.txt new file mode 100644 index 000000000..4b3edc29e --- /dev/null +++ b/static.files/NanumBarunGothic-LICENSE-a37d393b.txt @@ -0,0 +1,103 @@ +// REUSE-IgnoreStart + +Copyright (c) 2010, NAVER Corporation (https://www.navercorp.com/), + +with Reserved Font Name Nanum, Naver Nanum, NanumGothic, Naver NanumGothic, +NanumMyeongjo, Naver NanumMyeongjo, NanumBrush, Naver NanumBrush, NanumPen, +Naver NanumPen, Naver NanumGothicEco, NanumGothicEco, Naver NanumMyeongjoEco, +NanumMyeongjoEco, Naver NanumGothicLight, NanumGothicLight, NanumBarunGothic, +Naver NanumBarunGothic, NanumSquareRound, NanumBarunPen, MaruBuri + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. + +// REUSE-IgnoreEnd diff --git a/static.files/SourceCodePro-It-fc8b9304.ttf.woff2 b/static.files/SourceCodePro-It-fc8b9304.ttf.woff2 new file mode 100644 index 000000000..462c34efc Binary files /dev/null and b/static.files/SourceCodePro-It-fc8b9304.ttf.woff2 differ diff --git a/static.files/SourceCodePro-LICENSE-67f54ca7.txt b/static.files/SourceCodePro-LICENSE-67f54ca7.txt new file mode 100644 index 000000000..0d2941e14 --- /dev/null +++ b/static.files/SourceCodePro-LICENSE-67f54ca7.txt @@ -0,0 +1,97 @@ +// REUSE-IgnoreStart + +Copyright 2010, 2012 Adobe Systems Incorporated (http://www.adobe.com/), with Reserved Font Name 'Source'. All Rights Reserved. Source is a trademark of Adobe Systems Incorporated in the United States and/or other countries. + +This Font Software is licensed under the SIL Open Font License, Version 1.1. + +This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. + +// REUSE-IgnoreEnd diff --git a/static.files/SourceCodePro-Regular-8badfe75.ttf.woff2 b/static.files/SourceCodePro-Regular-8badfe75.ttf.woff2 new file mode 100644 index 000000000..10b558e0b Binary files /dev/null and b/static.files/SourceCodePro-Regular-8badfe75.ttf.woff2 differ diff --git a/static.files/SourceCodePro-Semibold-aa29a496.ttf.woff2 b/static.files/SourceCodePro-Semibold-aa29a496.ttf.woff2 new file mode 100644 index 000000000..5ec64eef0 Binary files /dev/null and b/static.files/SourceCodePro-Semibold-aa29a496.ttf.woff2 differ diff --git a/static.files/SourceSerif4-Bold-6d4fd4c0.ttf.woff2 b/static.files/SourceSerif4-Bold-6d4fd4c0.ttf.woff2 new file mode 100644 index 000000000..181a07f63 Binary files /dev/null and b/static.files/SourceSerif4-Bold-6d4fd4c0.ttf.woff2 differ diff --git a/static.files/SourceSerif4-It-ca3b17ed.ttf.woff2 b/static.files/SourceSerif4-It-ca3b17ed.ttf.woff2 new file mode 100644 index 000000000..2ae08a7be Binary files /dev/null and b/static.files/SourceSerif4-It-ca3b17ed.ttf.woff2 differ diff --git a/static.files/SourceSerif4-LICENSE-a2cfd9d5.md b/static.files/SourceSerif4-LICENSE-a2cfd9d5.md new file mode 100644 index 000000000..175fa4f47 --- /dev/null +++ b/static.files/SourceSerif4-LICENSE-a2cfd9d5.md @@ -0,0 +1,98 @@ + + +Copyright 2014-2021 Adobe (http://www.adobe.com/), with Reserved Font Name 'Source'. All Rights Reserved. Source is a trademark of Adobe in the United States and/or other countries. +Copyright 2014 - 2023 Adobe (http://www.adobe.com/), with Reserved Font Name ‘Source’. All Rights Reserved. Source is a trademark of Adobe in the United States and/or other countries. + +This Font Software is licensed under the SIL Open Font License, Version 1.1. + +This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. + + diff --git a/static.files/SourceSerif4-Regular-6b053e98.ttf.woff2 b/static.files/SourceSerif4-Regular-6b053e98.ttf.woff2 new file mode 100644 index 000000000..0263fc304 Binary files /dev/null and b/static.files/SourceSerif4-Regular-6b053e98.ttf.woff2 differ diff --git a/static.files/favicon-044be391.svg b/static.files/favicon-044be391.svg new file mode 100644 index 000000000..8b34b5119 --- /dev/null +++ b/static.files/favicon-044be391.svg @@ -0,0 +1,24 @@ + + + + + diff --git a/static.files/favicon-32x32-6580c154.png b/static.files/favicon-32x32-6580c154.png new file mode 100644 index 000000000..69b8613ce Binary files /dev/null and b/static.files/favicon-32x32-6580c154.png differ diff --git a/static.files/main-5f194d8c.js b/static.files/main-5f194d8c.js new file mode 100644 index 000000000..3d672cb6e --- /dev/null +++ b/static.files/main-5f194d8c.js @@ -0,0 +1,11 @@ +"use strict";window.RUSTDOC_TOOLTIP_HOVER_MS=300;window.RUSTDOC_TOOLTIP_HOVER_EXIT_MS=450;function resourcePath(basename,extension){return getVar("root-path")+basename+getVar("resource-suffix")+extension}function hideMain(){addClass(document.getElementById(MAIN_ID),"hidden");const toggle=document.getElementById("toggle-all-docs");if(toggle){toggle.setAttribute("disabled","disabled")}}function showMain(){const main=document.getElementById(MAIN_ID);removeClass(main,"hidden");const mainHeading=main.querySelector(".main-heading");if(mainHeading&&searchState.rustdocToolbar){if(searchState.rustdocToolbar.parentElement){searchState.rustdocToolbar.parentElement.removeChild(searchState.rustdocToolbar)}mainHeading.appendChild(searchState.rustdocToolbar)}const toggle=document.getElementById("toggle-all-docs");if(toggle){toggle.removeAttribute("disabled")}}window.rootPath=getVar("root-path");window.currentCrate=getVar("current-crate");function setMobileTopbar(){const mobileTopbar=document.querySelector(".mobile-topbar");const locationTitle=document.querySelector(".sidebar h2.location");if(mobileTopbar){const mobileTitle=document.createElement("h2");mobileTitle.className="location";if(hasClass(document.querySelector(".rustdoc"),"crate")){mobileTitle.innerHTML=`Crate ${window.currentCrate}`}else if(locationTitle){mobileTitle.innerHTML=locationTitle.innerHTML}mobileTopbar.appendChild(mobileTitle)}}function getVirtualKey(ev){if("key"in ev&&typeof ev.key!=="undefined"){return ev.key}const c=ev.charCode||ev.keyCode;if(c===27){return"Escape"}return String.fromCharCode(c)}const MAIN_ID="main-content";const SETTINGS_BUTTON_ID="settings-menu";const ALTERNATIVE_DISPLAY_ID="alternative-display";const NOT_DISPLAYED_ID="not-displayed";const HELP_BUTTON_ID="help-button";function getSettingsButton(){return document.getElementById(SETTINGS_BUTTON_ID)}function getHelpButton(){return document.getElementById(HELP_BUTTON_ID)}function getNakedUrl(){return window.location.href.split("?")[0].split("#")[0]}function insertAfter(newNode,referenceNode){referenceNode.parentNode.insertBefore(newNode,referenceNode.nextSibling)}function getOrCreateSection(id,classes){let el=document.getElementById(id);if(!el){el=document.createElement("section");el.id=id;el.className=classes;insertAfter(el,document.getElementById(MAIN_ID))}return el}function getAlternativeDisplayElem(){return getOrCreateSection(ALTERNATIVE_DISPLAY_ID,"content hidden")}function getNotDisplayedElem(){return getOrCreateSection(NOT_DISPLAYED_ID,"hidden")}function switchDisplayedElement(elemToDisplay){const el=getAlternativeDisplayElem();if(el.children.length>0){getNotDisplayedElem().appendChild(el.firstElementChild)}if(elemToDisplay===null){addClass(el,"hidden");showMain();return}el.appendChild(elemToDisplay);hideMain();removeClass(el,"hidden");const mainHeading=elemToDisplay.querySelector(".main-heading");if(mainHeading&&searchState.rustdocToolbar){if(searchState.rustdocToolbar.parentElement){searchState.rustdocToolbar.parentElement.removeChild(searchState.rustdocToolbar)}mainHeading.appendChild(searchState.rustdocToolbar)}}function browserSupportsHistoryApi(){return window.history&&typeof window.history.pushState==="function"}function preLoadCss(cssUrl){const link=document.createElement("link");link.href=cssUrl;link.rel="preload";link.as="style";document.getElementsByTagName("head")[0].appendChild(link)}(function(){const isHelpPage=window.location.pathname.endsWith("/help.html");function loadScript(url,errorCallback){const script=document.createElement("script");script.src=url;if(errorCallback!==undefined){script.onerror=errorCallback}document.head.append(script)}if(getSettingsButton()){getSettingsButton().onclick=event=>{if(event.ctrlKey||event.altKey||event.metaKey){return}window.hideAllModals(false);addClass(getSettingsButton(),"rotate");event.preventDefault();loadScript(getVar("static-root-path")+getVar("settings-js"));setTimeout(()=>{const themes=getVar("themes").split(",");for(const theme of themes){if(theme!==""){preLoadCss(getVar("root-path")+theme+".css")}}},0)}}window.searchState={rustdocToolbar:document.querySelector("rustdoc-toolbar"),loadingText:"Loading search results...",input:document.getElementsByClassName("search-input")[0],outputElement:()=>{let el=document.getElementById("search");if(!el){el=document.createElement("section");el.id="search";getNotDisplayedElem().appendChild(el)}return el},title:document.title,titleBeforeSearch:document.title,timeout:null,currentTab:0,focusedByTab:[null,null,null],clearInputTimeout:()=>{if(searchState.timeout!==null){clearTimeout(searchState.timeout);searchState.timeout=null}},isDisplayed:()=>searchState.outputElement().parentElement.id===ALTERNATIVE_DISPLAY_ID,focus:()=>{searchState.input.focus()},defocus:()=>{searchState.input.blur()},showResults:search=>{if(search===null||typeof search==="undefined"){search=searchState.outputElement()}switchDisplayedElement(search);searchState.mouseMovedAfterSearch=false;document.title=searchState.title},removeQueryParameters:()=>{document.title=searchState.titleBeforeSearch;if(browserSupportsHistoryApi()){history.replaceState(null,"",getNakedUrl()+window.location.hash)}},hideResults:()=>{switchDisplayedElement(null);searchState.removeQueryParameters()},getQueryStringParams:()=>{const params={};window.location.search.substring(1).split("&").map(s=>{const pair=s.split("=").map(x=>x.replace(/\+/g," "));params[decodeURIComponent(pair[0])]=typeof pair[1]==="undefined"?null:decodeURIComponent(pair[1])});return params},setup:()=>{const search_input=searchState.input;if(!searchState.input){return}let searchLoaded=false;function sendSearchForm(){document.getElementsByClassName("search-form")[0].submit()}function loadSearch(){if(!searchLoaded){searchLoaded=true;loadScript(getVar("static-root-path")+getVar("search-js"),sendSearchForm);loadScript(resourcePath("search-index",".js"),sendSearchForm)}}search_input.addEventListener("focus",()=>{search_input.origPlaceholder=search_input.placeholder;search_input.placeholder="Type your search here.";loadSearch()});if(search_input.value!==""){loadSearch()}const params=searchState.getQueryStringParams();if(params.search!==undefined){searchState.setLoadingSearch();loadSearch()}},setLoadingSearch:()=>{const search=searchState.outputElement();search.innerHTML="

"+searchState.loadingText+"

";searchState.showResults(search)},descShards:new Map(),loadDesc:async function({descShard,descIndex}){if(descShard.promise===null){descShard.promise=new Promise((resolve,reject)=>{descShard.resolve=resolve;const ds=descShard;const fname=`${ds.crate}-desc-${ds.shard}-`;const url=resourcePath(`search.desc/${descShard.crate}/${fname}`,".js",);loadScript(url,reject)})}const list=await descShard.promise;return list[descIndex]},loadedDescShard:function(crate,shard,data){this.descShards.get(crate)[shard].resolve(data.split("\n"))},};const toggleAllDocsId="toggle-all-docs";let savedHash="";function handleHashes(ev){if(ev!==null&&searchState.isDisplayed()&&ev.newURL){switchDisplayedElement(null);const hash=ev.newURL.slice(ev.newURL.indexOf("#")+1);if(browserSupportsHistoryApi()){history.replaceState(null,"",getNakedUrl()+window.location.search+"#"+hash)}const elem=document.getElementById(hash);if(elem){elem.scrollIntoView()}}const pageId=window.location.hash.replace(/^#/,"");if(savedHash!==pageId){savedHash=pageId;if(pageId!==""){expandSection(pageId)}}if(savedHash.startsWith("impl-")){const splitAt=savedHash.indexOf("/");if(splitAt!==-1){const implId=savedHash.slice(0,splitAt);const assocId=savedHash.slice(splitAt+1);const implElems=document.querySelectorAll(`details > summary > section[id^="${implId}"]`,);onEachLazy(implElems,implElem=>{const numbered=/^(.+?)-([0-9]+)$/.exec(implElem.id);if(implElem.id!==implId&&(!numbered||numbered[1]!==implId)){return false}return onEachLazy(implElem.parentElement.parentElement.querySelectorAll(`[id^="${assocId}"]`),item=>{const numbered=/^(.+?)-([0-9]+)$/.exec(item.id);if(item.id===assocId||(numbered&&numbered[1]===assocId)){openParentDetails(item);item.scrollIntoView();setTimeout(()=>{window.location.replace("#"+item.id)},0);return true}},)})}}}function onHashChange(ev){hideSidebar();handleHashes(ev)}function openParentDetails(elem){while(elem){if(elem.tagName==="DETAILS"){elem.open=true}elem=elem.parentNode}}function expandSection(id){openParentDetails(document.getElementById(id))}function handleEscape(ev){searchState.clearInputTimeout();searchState.hideResults();ev.preventDefault();searchState.defocus();window.hideAllModals(true)}function handleShortcut(ev){const disableShortcuts=getSettingValue("disable-shortcuts")==="true";if(ev.ctrlKey||ev.altKey||ev.metaKey||disableShortcuts){return}if(document.activeElement.tagName==="INPUT"&&document.activeElement.type!=="checkbox"&&document.activeElement.type!=="radio"){switch(getVirtualKey(ev)){case"Escape":handleEscape(ev);break}}else{switch(getVirtualKey(ev)){case"Escape":handleEscape(ev);break;case"s":case"S":case"/":ev.preventDefault();searchState.focus();break;case"+":ev.preventDefault();expandAllDocs();break;case"-":ev.preventDefault();collapseAllDocs();break;case"?":showHelp();break;default:break}}}document.addEventListener("keypress",handleShortcut);document.addEventListener("keydown",handleShortcut);function addSidebarItems(){if(!window.SIDEBAR_ITEMS){return}const sidebar=document.getElementById("rustdoc-modnav");function block(shortty,id,longty){const filtered=window.SIDEBAR_ITEMS[shortty];if(!filtered){return}const modpath=hasClass(document.querySelector(".rustdoc"),"mod")?"../":"";const h3=document.createElement("h3");h3.innerHTML=`${longty}`;const ul=document.createElement("ul");ul.className="block "+shortty;for(const name of filtered){let path;if(shortty==="mod"){path=`${modpath}${name}/index.html`}else{path=`${modpath}${shortty}.${name}.html`}let current_page=document.location.href.toString();if(current_page.endsWith("/")){current_page+="index.html"}const link=document.createElement("a");link.href=path;link.textContent=name;const li=document.createElement("li");if(link.href===current_page){li.classList.add("current")}li.appendChild(link);ul.appendChild(li)}sidebar.appendChild(h3);sidebar.appendChild(ul)}if(sidebar){block("primitive","primitives","Primitive Types");block("mod","modules","Modules");block("macro","macros","Macros");block("struct","structs","Structs");block("enum","enums","Enums");block("constant","constants","Constants");block("static","static","Statics");block("trait","traits","Traits");block("fn","functions","Functions");block("type","types","Type Aliases");block("union","unions","Unions");block("foreigntype","foreign-types","Foreign Types");block("keyword","keywords","Keywords");block("attr","attributes","Attribute Macros");block("derive","derives","Derive Macros");block("traitalias","trait-aliases","Trait Aliases")}}window.register_implementors=imp=>{const implementors=document.getElementById("implementors-list");const synthetic_implementors=document.getElementById("synthetic-implementors-list");const inlined_types=new Set();const TEXT_IDX=0;const SYNTHETIC_IDX=1;const TYPES_IDX=2;if(synthetic_implementors){onEachLazy(synthetic_implementors.getElementsByClassName("impl"),el=>{const aliases=el.getAttribute("data-aliases");if(!aliases){return}aliases.split(",").forEach(alias=>{inlined_types.add(alias)})})}let currentNbImpls=implementors.getElementsByClassName("impl").length;const traitName=document.querySelector(".main-heading h1 > .trait").textContent;const baseIdName="impl-"+traitName+"-";const libs=Object.getOwnPropertyNames(imp);const script=document.querySelector("script[data-ignore-extern-crates]");const ignoreExternCrates=new Set((script?script.getAttribute("data-ignore-extern-crates"):"").split(","),);for(const lib of libs){if(lib===window.currentCrate||ignoreExternCrates.has(lib)){continue}const structs=imp[lib];struct_loop:for(const struct of structs){const list=struct[SYNTHETIC_IDX]?synthetic_implementors:implementors;if(struct[SYNTHETIC_IDX]){for(const struct_type of struct[TYPES_IDX]){if(inlined_types.has(struct_type)){continue struct_loop}inlined_types.add(struct_type)}}const code=document.createElement("h3");code.innerHTML=struct[TEXT_IDX];addClass(code,"code-header");onEachLazy(code.getElementsByTagName("a"),elem=>{const href=elem.getAttribute("href");if(href&&!href.startsWith("#")&&!/^(?:[a-z+]+:)?\/\//.test(href)){elem.setAttribute("href",window.rootPath+href)}});const currentId=baseIdName+currentNbImpls;const anchor=document.createElement("a");anchor.href="#"+currentId;addClass(anchor,"anchor");const display=document.createElement("div");display.id=currentId;addClass(display,"impl");display.appendChild(anchor);display.appendChild(code);list.appendChild(display);currentNbImpls+=1}}};if(window.pending_implementors){window.register_implementors(window.pending_implementors)}window.register_type_impls=imp=>{if(!imp||!imp[window.currentCrate]){return}window.pending_type_impls=null;const idMap=new Map();let implementations=document.getElementById("implementations-list");let trait_implementations=document.getElementById("trait-implementations-list");let trait_implementations_header=document.getElementById("trait-implementations");const script=document.querySelector("script[data-self-path]");const selfPath=script?script.getAttribute("data-self-path"):null;const mainContent=document.querySelector("#main-content");const sidebarSection=document.querySelector(".sidebar section");let methods=document.querySelector(".sidebar .block.method");let associatedTypes=document.querySelector(".sidebar .block.associatedtype");let associatedConstants=document.querySelector(".sidebar .block.associatedconstant");let sidebarTraitList=document.querySelector(".sidebar .block.trait-implementation");for(const impList of imp[window.currentCrate]){const types=impList.slice(2);const text=impList[0];const isTrait=impList[1]!==0;const traitName=impList[1];if(types.indexOf(selfPath)===-1){continue}let outputList=isTrait?trait_implementations:implementations;if(outputList===null){const outputListName=isTrait?"Trait Implementations":"Implementations";const outputListId=isTrait?"trait-implementations-list":"implementations-list";const outputListHeaderId=isTrait?"trait-implementations":"implementations";const outputListHeader=document.createElement("h2");outputListHeader.id=outputListHeaderId;outputListHeader.innerText=outputListName;outputList=document.createElement("div");outputList.id=outputListId;if(isTrait){const link=document.createElement("a");link.href=`#${outputListHeaderId}`;link.innerText="Trait Implementations";const h=document.createElement("h3");h.appendChild(link);trait_implementations=outputList;trait_implementations_header=outputListHeader;sidebarSection.appendChild(h);sidebarTraitList=document.createElement("ul");sidebarTraitList.className="block trait-implementation";sidebarSection.appendChild(sidebarTraitList);mainContent.appendChild(outputListHeader);mainContent.appendChild(outputList)}else{implementations=outputList;if(trait_implementations){mainContent.insertBefore(outputListHeader,trait_implementations_header);mainContent.insertBefore(outputList,trait_implementations_header)}else{const mainContent=document.querySelector("#main-content");mainContent.appendChild(outputListHeader);mainContent.appendChild(outputList)}}}const template=document.createElement("template");template.innerHTML=text;onEachLazy(template.content.querySelectorAll("a"),elem=>{const href=elem.getAttribute("href");if(href&&!href.startsWith("#")&&!/^(?:[a-z+]+:)?\/\//.test(href)){elem.setAttribute("href",window.rootPath+href)}});onEachLazy(template.content.querySelectorAll("[id]"),el=>{let i=0;if(idMap.has(el.id)){i=idMap.get(el.id)}else if(document.getElementById(el.id)){i=1;while(document.getElementById(`${el.id}-${2 * i}`)){i=2*i}while(document.getElementById(`${el.id}-${i}`)){i+=1}}if(i!==0){const oldHref=`#${el.id}`;const newHref=`#${el.id}-${i}`;el.id=`${el.id}-${i}`;onEachLazy(template.content.querySelectorAll("a[href]"),link=>{if(link.getAttribute("href")===oldHref){link.href=newHref}})}idMap.set(el.id,i+1)});const templateAssocItems=template.content.querySelectorAll("section.tymethod, "+"section.method, section.associatedtype, section.associatedconstant");if(isTrait){const li=document.createElement("li");const a=document.createElement("a");a.href=`#${template.content.querySelector(".impl").id}`;a.textContent=traitName;li.appendChild(a);sidebarTraitList.append(li)}else{onEachLazy(templateAssocItems,item=>{let block=hasClass(item,"associatedtype")?associatedTypes:(hasClass(item,"associatedconstant")?associatedConstants:(methods));if(!block){const blockTitle=hasClass(item,"associatedtype")?"Associated Types":(hasClass(item,"associatedconstant")?"Associated Constants":("Methods"));const blockClass=hasClass(item,"associatedtype")?"associatedtype":(hasClass(item,"associatedconstant")?"associatedconstant":("method"));const blockHeader=document.createElement("h3");const blockLink=document.createElement("a");blockLink.href="#implementations";blockLink.innerText=blockTitle;blockHeader.appendChild(blockLink);block=document.createElement("ul");block.className=`block ${blockClass}`;const insertionReference=methods||sidebarTraitList;if(insertionReference){const insertionReferenceH=insertionReference.previousElementSibling;sidebarSection.insertBefore(blockHeader,insertionReferenceH);sidebarSection.insertBefore(block,insertionReferenceH)}else{sidebarSection.appendChild(blockHeader);sidebarSection.appendChild(block)}if(hasClass(item,"associatedtype")){associatedTypes=block}else if(hasClass(item,"associatedconstant")){associatedConstants=block}else{methods=block}}const li=document.createElement("li");const a=document.createElement("a");a.innerText=item.id.split("-")[0].split(".")[1];a.href=`#${item.id}`;li.appendChild(a);block.appendChild(li)})}outputList.appendChild(template.content)}for(const list of[methods,associatedTypes,associatedConstants,sidebarTraitList]){if(!list){continue}const newChildren=Array.prototype.slice.call(list.children);newChildren.sort((a,b)=>{const aI=a.innerText;const bI=b.innerText;return aIbI?1:0});list.replaceChildren(...newChildren)}};if(window.pending_type_impls){window.register_type_impls(window.pending_type_impls)}function addSidebarCrates(){if(!window.ALL_CRATES){return}const sidebarElems=document.getElementById("rustdoc-modnav");if(!sidebarElems){return}const h3=document.createElement("h3");h3.innerHTML="Crates";const ul=document.createElement("ul");ul.className="block crate";for(const crate of window.ALL_CRATES){const link=document.createElement("a");link.href=window.rootPath+crate+"/index.html";link.textContent=crate;const li=document.createElement("li");if(window.rootPath!=="./"&&crate===window.currentCrate){li.className="current"}li.appendChild(link);ul.appendChild(li)}sidebarElems.appendChild(h3);sidebarElems.appendChild(ul)}function expandAllDocs(){const innerToggle=document.getElementById(toggleAllDocsId);removeClass(innerToggle,"will-expand");onEachLazy(document.getElementsByClassName("toggle"),e=>{if(!hasClass(e,"type-contents-toggle")&&!hasClass(e,"more-examples-toggle")){e.open=true}});innerToggle.children[0].innerText="Summary"}function collapseAllDocs(){const innerToggle=document.getElementById(toggleAllDocsId);addClass(innerToggle,"will-expand");onEachLazy(document.getElementsByClassName("toggle"),e=>{if(e.parentNode.id!=="implementations-list"||(!hasClass(e,"implementors-toggle")&&!hasClass(e,"type-contents-toggle"))){e.open=false}});innerToggle.children[0].innerText="Show all"}function toggleAllDocs(){const innerToggle=document.getElementById(toggleAllDocsId);if(!innerToggle){return}if(hasClass(innerToggle,"will-expand")){expandAllDocs()}else{collapseAllDocs()}}(function(){const toggles=document.getElementById(toggleAllDocsId);if(toggles){toggles.onclick=toggleAllDocs}const hideMethodDocs=getSettingValue("auto-hide-method-docs")==="true";const hideImplementations=getSettingValue("auto-hide-trait-implementations")==="true";const hideLargeItemContents=getSettingValue("auto-hide-large-items")!=="false";function setImplementorsTogglesOpen(id,open){const list=document.getElementById(id);if(list!==null){onEachLazy(list.getElementsByClassName("implementors-toggle"),e=>{e.open=open})}}if(hideImplementations){setImplementorsTogglesOpen("trait-implementations-list",false);setImplementorsTogglesOpen("blanket-implementations-list",false)}onEachLazy(document.getElementsByClassName("toggle"),e=>{if(!hideLargeItemContents&&hasClass(e,"type-contents-toggle")){e.open=true}if(hideMethodDocs&&hasClass(e,"method-toggle")){e.open=false}})}());window.rustdoc_add_line_numbers_to_examples=()=>{if(document.querySelector(".rustdoc.src")){return}onEachLazy(document.querySelectorAll(":not(.scraped-example) > .example-wrap > pre:not(.example-line-numbers)",),x=>{const parent=x.parentNode;const line_numbers=parent.querySelectorAll(".example-line-numbers");if(line_numbers.length>0){return}const count=x.textContent.split("\n").length;const elems=[];for(let i=0;i{onEachLazy(document.querySelectorAll(".example-wrap > .example-line-numbers"),x=>{x.parentNode.removeChild(x)})};if(getSettingValue("line-numbers")==="true"){window.rustdoc_add_line_numbers_to_examples()}function showSidebar(){window.hideAllModals(false);const sidebar=document.getElementsByClassName("sidebar")[0];addClass(sidebar,"shown")}function hideSidebar(){const sidebar=document.getElementsByClassName("sidebar")[0];removeClass(sidebar,"shown")}window.addEventListener("resize",()=>{if(window.CURRENT_TOOLTIP_ELEMENT){const base=window.CURRENT_TOOLTIP_ELEMENT.TOOLTIP_BASE;const force_visible=base.TOOLTIP_FORCE_VISIBLE;hideTooltip(false);if(force_visible){showTooltip(base);base.TOOLTIP_FORCE_VISIBLE=true}}});const mainElem=document.getElementById(MAIN_ID);if(mainElem){mainElem.addEventListener("click",hideSidebar)}onEachLazy(document.querySelectorAll("a[href^='#']"),el=>{el.addEventListener("click",()=>{expandSection(el.hash.slice(1));hideSidebar()})});onEachLazy(document.querySelectorAll(".toggle > summary:not(.hideme)"),el=>{el.addEventListener("click",e=>{if(e.target.tagName!=="SUMMARY"&&e.target.tagName!=="A"){e.preventDefault()}})});function showTooltip(e){const notable_ty=e.getAttribute("data-notable-ty");if(!window.NOTABLE_TRAITS&¬able_ty){const data=document.getElementById("notable-traits-data");if(data){window.NOTABLE_TRAITS=JSON.parse(data.innerText)}else{throw new Error("showTooltip() called with notable without any notable traits!")}}if(window.CURRENT_TOOLTIP_ELEMENT&&window.CURRENT_TOOLTIP_ELEMENT.TOOLTIP_BASE===e){clearTooltipHoverTimeout(window.CURRENT_TOOLTIP_ELEMENT);return}window.hideAllModals(false);const wrapper=document.createElement("div");if(notable_ty){wrapper.innerHTML="
"+window.NOTABLE_TRAITS[notable_ty]+"
"}else{if(e.getAttribute("title")!==null){e.setAttribute("data-title",e.getAttribute("title"));e.removeAttribute("title")}if(e.getAttribute("data-title")!==null){const titleContent=document.createElement("div");titleContent.className="content";titleContent.appendChild(document.createTextNode(e.getAttribute("data-title")));wrapper.appendChild(titleContent)}}wrapper.className="tooltip popover";const focusCatcher=document.createElement("div");focusCatcher.setAttribute("tabindex","0");focusCatcher.onfocus=hideTooltip;wrapper.appendChild(focusCatcher);const pos=e.getBoundingClientRect();wrapper.style.top=(pos.top+window.scrollY+pos.height)+"px";wrapper.style.left=0;wrapper.style.right="auto";wrapper.style.visibility="hidden";document.body.appendChild(wrapper);const wrapperPos=wrapper.getBoundingClientRect();const finalPos=pos.left+window.scrollX-wrapperPos.width+24;if(finalPos>0){wrapper.style.left=finalPos+"px"}else{wrapper.style.setProperty("--popover-arrow-offset",(wrapperPos.right-pos.right+4)+"px",)}wrapper.style.visibility="";window.CURRENT_TOOLTIP_ELEMENT=wrapper;window.CURRENT_TOOLTIP_ELEMENT.TOOLTIP_BASE=e;clearTooltipHoverTimeout(window.CURRENT_TOOLTIP_ELEMENT);wrapper.onpointerenter=ev=>{if(ev.pointerType!=="mouse"){return}clearTooltipHoverTimeout(e)};wrapper.onpointerleave=ev=>{if(ev.pointerType!=="mouse"){return}if(!e.TOOLTIP_FORCE_VISIBLE&&!e.contains(ev.relatedTarget)){setTooltipHoverTimeout(e,false);addClass(wrapper,"fade-out")}}}function setTooltipHoverTimeout(element,show){clearTooltipHoverTimeout(element);if(!show&&!window.CURRENT_TOOLTIP_ELEMENT){return}if(show&&window.CURRENT_TOOLTIP_ELEMENT){return}if(window.CURRENT_TOOLTIP_ELEMENT&&window.CURRENT_TOOLTIP_ELEMENT.TOOLTIP_BASE!==element){return}element.TOOLTIP_HOVER_TIMEOUT=setTimeout(()=>{if(show){showTooltip(element)}else if(!element.TOOLTIP_FORCE_VISIBLE){hideTooltip(false)}},show?window.RUSTDOC_TOOLTIP_HOVER_MS:window.RUSTDOC_TOOLTIP_HOVER_EXIT_MS)}function clearTooltipHoverTimeout(element){if(element.TOOLTIP_HOVER_TIMEOUT!==undefined){removeClass(window.CURRENT_TOOLTIP_ELEMENT,"fade-out");clearTimeout(element.TOOLTIP_HOVER_TIMEOUT);delete element.TOOLTIP_HOVER_TIMEOUT}}function tooltipBlurHandler(event){if(window.CURRENT_TOOLTIP_ELEMENT&&!window.CURRENT_TOOLTIP_ELEMENT.contains(document.activeElement)&&!window.CURRENT_TOOLTIP_ELEMENT.contains(event.relatedTarget)&&!window.CURRENT_TOOLTIP_ELEMENT.TOOLTIP_BASE.contains(document.activeElement)&&!window.CURRENT_TOOLTIP_ELEMENT.TOOLTIP_BASE.contains(event.relatedTarget)){setTimeout(()=>hideTooltip(false),0)}}function hideTooltip(focus){if(window.CURRENT_TOOLTIP_ELEMENT){if(window.CURRENT_TOOLTIP_ELEMENT.TOOLTIP_BASE.TOOLTIP_FORCE_VISIBLE){if(focus){window.CURRENT_TOOLTIP_ELEMENT.TOOLTIP_BASE.focus()}window.CURRENT_TOOLTIP_ELEMENT.TOOLTIP_BASE.TOOLTIP_FORCE_VISIBLE=false}document.body.removeChild(window.CURRENT_TOOLTIP_ELEMENT);clearTooltipHoverTimeout(window.CURRENT_TOOLTIP_ELEMENT);window.CURRENT_TOOLTIP_ELEMENT=null}}onEachLazy(document.getElementsByClassName("tooltip"),e=>{e.onclick=()=>{e.TOOLTIP_FORCE_VISIBLE=e.TOOLTIP_FORCE_VISIBLE?false:true;if(window.CURRENT_TOOLTIP_ELEMENT&&!e.TOOLTIP_FORCE_VISIBLE){hideTooltip(true)}else{showTooltip(e);window.CURRENT_TOOLTIP_ELEMENT.setAttribute("tabindex","0");window.CURRENT_TOOLTIP_ELEMENT.focus();window.CURRENT_TOOLTIP_ELEMENT.onblur=tooltipBlurHandler}return false};e.onpointerenter=ev=>{if(ev.pointerType!=="mouse"){return}setTooltipHoverTimeout(e,true)};e.onpointermove=ev=>{if(ev.pointerType!=="mouse"){return}setTooltipHoverTimeout(e,true)};e.onpointerleave=ev=>{if(ev.pointerType!=="mouse"){return}if(!e.TOOLTIP_FORCE_VISIBLE&&window.CURRENT_TOOLTIP_ELEMENT&&!window.CURRENT_TOOLTIP_ELEMENT.contains(ev.relatedTarget)){setTooltipHoverTimeout(e,false);addClass(window.CURRENT_TOOLTIP_ELEMENT,"fade-out")}}});const sidebar_menu_toggle=document.getElementsByClassName("sidebar-menu-toggle")[0];if(sidebar_menu_toggle){sidebar_menu_toggle.addEventListener("click",()=>{const sidebar=document.getElementsByClassName("sidebar")[0];if(!hasClass(sidebar,"shown")){showSidebar()}else{hideSidebar()}})}function helpBlurHandler(event){if(!getHelpButton().contains(document.activeElement)&&!getHelpButton().contains(event.relatedTarget)&&!getSettingsButton().contains(document.activeElement)&&!getSettingsButton().contains(event.relatedTarget)){window.hidePopoverMenus()}}function buildHelpMenu(){const book_info=document.createElement("span");const channel=getVar("channel");book_info.className="top";book_info.innerHTML=`You can find more information in \ +the rustdoc book.`;const shortcuts=[["?","Show this help dialog"],["S / /","Focus the search field"],["↑","Move up in search results"],["↓","Move down in search results"],["← / →","Switch result tab (when results focused)"],["⏎","Go to active search result"],["+","Expand all sections"],["-","Collapse all sections"],].map(x=>"
"+x[0].split(" ").map((y,index)=>((index&1)===0?""+y+"":" "+y+" ")).join("")+"
"+x[1]+"
").join("");const div_shortcuts=document.createElement("div");addClass(div_shortcuts,"shortcuts");div_shortcuts.innerHTML="

Keyboard Shortcuts

"+shortcuts+"
";const infos=[`For a full list of all search features, take a look here.`,"Prefix searches with a type followed by a colon (e.g., fn:) to \ + restrict the search to a given item kind.","Accepted kinds are: fn, mod, struct, \ + enum, trait, type, macro, \ + and const.","Search functions by type signature (e.g., vec -> usize or \ + -> vec or String, enum:Cow -> bool)","You can look for items with an exact name by putting double quotes around \ + your request: \"string\"","Look for functions that accept or return \ + slices and \ + arrays by writing \ + square brackets (e.g., -> [u8] or [] -> Option)","Look for items inside another one by searching for a path: vec::Vec",].map(x=>"

"+x+"

").join("");const div_infos=document.createElement("div");addClass(div_infos,"infos");div_infos.innerHTML="

Search Tricks

"+infos;const rustdoc_version=document.createElement("span");rustdoc_version.className="bottom";const rustdoc_version_code=document.createElement("code");rustdoc_version_code.innerText="rustdoc "+getVar("rustdoc-version");rustdoc_version.appendChild(rustdoc_version_code);const container=document.createElement("div");if(!isHelpPage){container.className="popover"}container.id="help";container.style.display="none";const side_by_side=document.createElement("div");side_by_side.className="side-by-side";side_by_side.appendChild(div_shortcuts);side_by_side.appendChild(div_infos);container.appendChild(book_info);container.appendChild(side_by_side);container.appendChild(rustdoc_version);if(isHelpPage){const help_section=document.createElement("section");help_section.appendChild(container);document.getElementById("main-content").appendChild(help_section);container.style.display="block"}else{const help_button=getHelpButton();help_button.appendChild(container);container.onblur=helpBlurHandler;help_button.onblur=helpBlurHandler;help_button.children[0].onblur=helpBlurHandler}return container}window.hideAllModals=switchFocus=>{hideSidebar();window.hidePopoverMenus();hideTooltip(switchFocus)};window.hidePopoverMenus=()=>{onEachLazy(document.querySelectorAll("rustdoc-toolbar .popover"),elem=>{elem.style.display="none"});const button=getHelpButton();if(button){removeClass(button,"help-open")}};function getHelpMenu(buildNeeded){let menu=getHelpButton().querySelector(".popover");if(!menu&&buildNeeded){menu=buildHelpMenu()}return menu}function showHelp(){const button=getHelpButton();addClass(button,"help-open");button.querySelector("a").focus();const menu=getHelpMenu(true);if(menu.style.display==="none"){window.hideAllModals();menu.style.display=""}}const helpLink=document.querySelector(`#${HELP_BUTTON_ID} > a`);if(isHelpPage){buildHelpMenu()}else if(helpLink){helpLink.addEventListener("click",event=>{if(!helpLink.contains(helpLink)||event.ctrlKey||event.altKey||event.metaKey){return}event.preventDefault();const menu=getHelpMenu(true);const shouldShowHelp=menu.style.display==="none";if(shouldShowHelp){showHelp()}else{window.hidePopoverMenus()}})}setMobileTopbar();addSidebarItems();addSidebarCrates();onHashChange(null);window.addEventListener("hashchange",onHashChange);searchState.setup()}());(function(){const SIDEBAR_MIN=100;const SIDEBAR_MAX=500;const RUSTDOC_MOBILE_BREAKPOINT=700;const BODY_MIN=400;const SIDEBAR_VANISH_THRESHOLD=SIDEBAR_MIN/2;const sidebarButton=document.getElementById("sidebar-button");if(sidebarButton){sidebarButton.addEventListener("click",e=>{removeClass(document.documentElement,"hide-sidebar");updateLocalStorage("hide-sidebar","false");if(document.querySelector(".rustdoc.src")){window.rustdocToggleSrcSidebar()}e.preventDefault()})}let currentPointerId=null;let desiredSidebarSize=null;let pendingSidebarResizingFrame=false;const resizer=document.querySelector(".sidebar-resizer");const sidebar=document.querySelector(".sidebar");if(!resizer||!sidebar){return}const isSrcPage=hasClass(document.body,"src");function hideSidebar(){if(isSrcPage){window.rustdocCloseSourceSidebar();updateLocalStorage("src-sidebar-width",null);document.documentElement.style.removeProperty("--src-sidebar-width");sidebar.style.removeProperty("--src-sidebar-width");resizer.style.removeProperty("--src-sidebar-width")}else{addClass(document.documentElement,"hide-sidebar");updateLocalStorage("hide-sidebar","true");updateLocalStorage("desktop-sidebar-width",null);document.documentElement.style.removeProperty("--desktop-sidebar-width");sidebar.style.removeProperty("--desktop-sidebar-width");resizer.style.removeProperty("--desktop-sidebar-width")}}function showSidebar(){if(isSrcPage){window.rustdocShowSourceSidebar()}else{removeClass(document.documentElement,"hide-sidebar");updateLocalStorage("hide-sidebar","false")}}function changeSidebarSize(size){if(isSrcPage){updateLocalStorage("src-sidebar-width",size);sidebar.style.setProperty("--src-sidebar-width",size+"px");resizer.style.setProperty("--src-sidebar-width",size+"px")}else{updateLocalStorage("desktop-sidebar-width",size);sidebar.style.setProperty("--desktop-sidebar-width",size+"px");resizer.style.setProperty("--desktop-sidebar-width",size+"px")}}function isSidebarHidden(){return isSrcPage?!hasClass(document.documentElement,"src-sidebar-expanded"):hasClass(document.documentElement,"hide-sidebar")}function resize(e){if(currentPointerId===null||currentPointerId!==e.pointerId){return}e.preventDefault();const pos=e.clientX-3;if(pos=SIDEBAR_MIN){if(isSidebarHidden()){showSidebar()}const constrainedPos=Math.min(pos,window.innerWidth-BODY_MIN,SIDEBAR_MAX);changeSidebarSize(constrainedPos);desiredSidebarSize=constrainedPos;if(pendingSidebarResizingFrame!==false){clearTimeout(pendingSidebarResizingFrame)}pendingSidebarResizingFrame=setTimeout(()=>{if(currentPointerId===null||pendingSidebarResizingFrame===false){return}pendingSidebarResizingFrame=false;document.documentElement.style.setProperty("--resizing-sidebar-width",desiredSidebarSize+"px",)},100)}}window.addEventListener("resize",()=>{if(window.innerWidth=(window.innerWidth-BODY_MIN)){changeSidebarSize(window.innerWidth-BODY_MIN)}else if(desiredSidebarSize!==null&&desiredSidebarSize>SIDEBAR_MIN){changeSidebarSize(desiredSidebarSize)}});function stopResize(e){if(currentPointerId===null){return}if(e){e.preventDefault()}desiredSidebarSize=sidebar.getBoundingClientRect().width;removeClass(resizer,"active");window.removeEventListener("pointermove",resize,false);window.removeEventListener("pointerup",stopResize,false);removeClass(document.documentElement,"sidebar-resizing");document.documentElement.style.removeProperty("--resizing-sidebar-width");if(resizer.releasePointerCapture){resizer.releasePointerCapture(currentPointerId);currentPointerId=null}}function initResize(e){if(currentPointerId!==null||e.altKey||e.ctrlKey||e.metaKey||e.button!==0){return}if(resizer.setPointerCapture){resizer.setPointerCapture(e.pointerId);if(!resizer.hasPointerCapture(e.pointerId)){resizer.releasePointerCapture(e.pointerId);return}currentPointerId=e.pointerId}window.hideAllModals(false);e.preventDefault();window.addEventListener("pointermove",resize,false);window.addEventListener("pointercancel",stopResize,false);window.addEventListener("pointerup",stopResize,false);addClass(resizer,"active");addClass(document.documentElement,"sidebar-resizing");const pos=e.clientX-sidebar.offsetLeft-3;document.documentElement.style.setProperty("--resizing-sidebar-width",pos+"px");desiredSidebarSize=null}resizer.addEventListener("pointerdown",initResize,false)}());(function(){function copyContentToClipboard(content){const el=document.createElement("textarea");el.value=content;el.setAttribute("readonly","");el.style.position="absolute";el.style.left="-9999px";document.body.appendChild(el);el.select();document.execCommand("copy");document.body.removeChild(el)}function copyButtonAnimation(button){button.classList.add("clicked");if(button.reset_button_timeout!==undefined){window.clearTimeout(button.reset_button_timeout)}button.reset_button_timeout=window.setTimeout(()=>{button.reset_button_timeout=undefined;button.classList.remove("clicked")},1000)}const but=document.getElementById("copy-path");if(!but){return}but.onclick=()=>{const title=document.querySelector("title").textContent.replace(" - Rust","");const[item,module]=title.split(" in ");const path=[item];if(module!==undefined){path.unshift(module)}copyContentToClipboard(path.join("::"));copyButtonAnimation(but)};function copyCode(codeElem){if(!codeElem){return}copyContentToClipboard(codeElem.textContent)}function getExampleWrap(event){let elem=event.target;while(!hasClass(elem,"example-wrap")){if(elem===document.body||elem.tagName==="A"||elem.tagName==="BUTTON"||hasClass(elem,"docblock")){return null}elem=elem.parentElement}return elem}function addCopyButton(event){const elem=getExampleWrap(event);if(elem===null){return}elem.removeEventListener("mouseover",addCopyButton);const parent=document.createElement("div");parent.className="button-holder";const runButton=elem.querySelector(".test-arrow");if(runButton!==null){parent.appendChild(runButton)}elem.appendChild(parent);const copyButton=document.createElement("button");copyButton.className="copy-button";copyButton.title="Copy code to clipboard";copyButton.addEventListener("click",()=>{copyCode(elem.querySelector("pre > code"));copyButtonAnimation(copyButton)});parent.appendChild(copyButton);if(!elem.parentElement.classList.contains("scraped-example")){return}const scrapedWrapped=elem.parentElement;window.updateScrapedExample(scrapedWrapped,parent)}function showHideCodeExampleButtons(event){const elem=getExampleWrap(event);if(elem===null){return}let buttons=elem.querySelector(".button-holder");if(buttons===null){addCopyButton(event);buttons=elem.querySelector(".button-holder");if(buttons===null){return}}buttons.classList.toggle("keep-visible")}onEachLazy(document.querySelectorAll(".docblock .example-wrap"),elem=>{elem.addEventListener("mouseover",addCopyButton);elem.addEventListener("click",showHideCodeExampleButtons)})}()) \ No newline at end of file diff --git a/static.files/normalize-9960930a.css b/static.files/normalize-9960930a.css new file mode 100644 index 000000000..469959f13 --- /dev/null +++ b/static.files/normalize-9960930a.css @@ -0,0 +1,2 @@ + /*! normalize.css v8.0.1 | MIT License | github.com/necolas/normalize.css */ +html{line-height:1.15;-webkit-text-size-adjust:100%}body{margin:0}main{display:block}h1{font-size:2em;margin:0.67em 0}hr{box-sizing:content-box;height:0;overflow:visible}pre{font-family:monospace,monospace;font-size:1em}a{background-color:transparent}abbr[title]{border-bottom:none;text-decoration:underline;text-decoration:underline dotted}b,strong{font-weight:bolder}code,kbd,samp{font-family:monospace,monospace;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-0.25em}sup{top:-0.5em}img{border-style:none}button,input,optgroup,select,textarea{font-family:inherit;font-size:100%;line-height:1.15;margin:0}button,input{overflow:visible}button,select{text-transform:none}[type="button"],[type="reset"],[type="submit"],button{-webkit-appearance:button}[type="button"]::-moz-focus-inner,[type="reset"]::-moz-focus-inner,[type="submit"]::-moz-focus-inner,button::-moz-focus-inner{border-style:none;padding:0}[type="button"]:-moz-focusring,[type="reset"]:-moz-focusring,[type="submit"]:-moz-focusring,button:-moz-focusring{outline:1px dotted ButtonText}fieldset{padding:0.35em 0.75em 0.625em}legend{box-sizing:border-box;color:inherit;display:table;max-width:100%;padding:0;white-space:normal}progress{vertical-align:baseline}textarea{overflow:auto}[type="checkbox"],[type="radio"]{box-sizing:border-box;padding:0}[type="number"]::-webkit-inner-spin-button,[type="number"]::-webkit-outer-spin-button{height:auto}[type="search"]{-webkit-appearance:textfield;outline-offset:-2px}[type="search"]::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}details{display:block}summary{display:list-item}template{display:none}[hidden]{display:none} \ No newline at end of file diff --git a/static.files/noscript-893ab5e7.css b/static.files/noscript-893ab5e7.css new file mode 100644 index 000000000..a6c18ecaf --- /dev/null +++ b/static.files/noscript-893ab5e7.css @@ -0,0 +1 @@ + #main-content .attributes{margin-left:0 !important;}#copy-path,#sidebar-button,.sidebar-resizer{display:none !important;}nav.sub{display:none;}.src .sidebar{display:none;}.notable-traits{display:none;}:root,:root:not([data-theme]){--main-background-color:white;--main-color:black;--settings-input-color:#2196f3;--settings-input-border-color:#717171;--settings-button-color:#000;--settings-button-border-focus:#717171;--sidebar-background-color:#f5f5f5;--sidebar-background-color-hover:#e0e0e0;--code-block-background-color:#f5f5f5;--scrollbar-track-background-color:#dcdcdc;--scrollbar-thumb-background-color:rgba(36,37,39,0.6);--scrollbar-color:rgba(36,37,39,0.6) #d9d9d9;--headings-border-bottom-color:#ddd;--border-color:#e0e0e0;--button-background-color:#fff;--right-side-color:grey;--code-attribute-color:#999;--toggles-color:#999;--toggle-filter:none;--mobile-sidebar-menu-filter:none;--search-input-focused-border-color:#66afe9;--copy-path-button-color:#999;--copy-path-img-filter:invert(50%);--copy-path-img-hover-filter:invert(35%);--code-example-button-color:#7f7f7f;--code-example-button-hover-color:#595959;--settings-menu-filter:invert(50%);--settings-menu-hover-filter:invert(35%);--codeblock-error-hover-color:rgb(255,0,0);--codeblock-error-color:rgba(255,0,0,.5);--codeblock-ignore-hover-color:rgb(255,142,0);--codeblock-ignore-color:rgba(255,142,0,.6);--warning-border-color:#ff8e00;--type-link-color:#ad378a;--trait-link-color:#6e4fc9;--assoc-item-link-color:#3873ad;--function-link-color:#ad7c37;--macro-link-color:#068000;--keyword-link-color:#3873ad;--mod-link-color:#3873ad;--link-color:#3873ad;--sidebar-link-color:#356da4;--sidebar-current-link-background-color:#fff;--search-result-link-focus-background-color:#ccc;--search-result-border-color:#aaa3;--search-color:#000;--search-error-code-background-color:#d0cccc;--search-results-alias-color:#000;--search-results-grey-color:#999;--search-tab-title-count-color:#888;--search-tab-button-not-selected-border-top-color:#e6e6e6;--search-tab-button-not-selected-background:#e6e6e6;--search-tab-button-selected-border-top-color:#0089ff;--search-tab-button-selected-background:#fff;--stab-background-color:#fff5d6;--stab-code-color:#000;--code-highlight-kw-color:#8959a8;--code-highlight-kw-2-color:#4271ae;--code-highlight-lifetime-color:#b76514;--code-highlight-prelude-color:#4271ae;--code-highlight-prelude-val-color:#c82829;--code-highlight-number-color:#718c00;--code-highlight-string-color:#718c00;--code-highlight-literal-color:#c82829;--code-highlight-attribute-color:#c82829;--code-highlight-self-color:#c82829;--code-highlight-macro-color:#3e999f;--code-highlight-question-mark-color:#ff9011;--code-highlight-comment-color:#8e908c;--code-highlight-doc-comment-color:#4d4d4c;--src-line-numbers-span-color:#c67e2d;--src-line-number-highlighted-background-color:#fdffd3;--target-background-color:#fdffd3;--target-border-color:#ad7c37;--kbd-color:#000;--kbd-background:#fafbfc;--kbd-box-shadow-color:#c6cbd1;--rust-logo-filter:initial;--crate-search-div-filter:invert(100%) sepia(0%) saturate(4223%) hue-rotate(289deg) brightness(114%) contrast(76%);--crate-search-div-hover-filter:invert(44%) sepia(18%) saturate(23%) hue-rotate(317deg) brightness(96%) contrast(93%);--crate-search-hover-border:#717171;--src-sidebar-background-selected:#fff;--src-sidebar-background-hover:#e0e0e0;--table-alt-row-background-color:#f5f5f5;--codeblock-link-background:#eee;--scrape-example-toggle-line-background:#ccc;--scrape-example-toggle-line-hover-background:#999;--scrape-example-code-line-highlight:#fcffd6;--scrape-example-code-line-highlight-focus:#f6fdb0;--scrape-example-help-border-color:#555;--scrape-example-help-color:#333;--scrape-example-help-hover-border-color:#000;--scrape-example-help-hover-color:#000;--scrape-example-code-wrapper-background-start:rgba(255,255,255,1);--scrape-example-code-wrapper-background-end:rgba(255,255,255,0);--sidebar-resizer-hover:hsl(207,90%,66%);--sidebar-resizer-active:hsl(207,90%,54%);}@media (prefers-color-scheme:dark){:root,:root:not([data-theme]){--main-background-color:#353535;--main-color:#ddd;--settings-input-color:#2196f3;--settings-input-border-color:#999;--settings-button-color:#000;--settings-button-border-focus:#ffb900;--sidebar-background-color:#505050;--sidebar-background-color-hover:#676767;--code-block-background-color:#2A2A2A;--scrollbar-track-background-color:#717171;--scrollbar-thumb-background-color:rgba(32,34,37,.6);--scrollbar-color:rgba(32,34,37,.6) #5a5a5a;--headings-border-bottom-color:#d2d2d2;--border-color:#e0e0e0;--button-background-color:#f0f0f0;--right-side-color:grey;--code-attribute-color:#999;--toggles-color:#999;--toggle-filter:invert(100%);--mobile-sidebar-menu-filter:invert(100%);--search-input-focused-border-color:#008dfd;--copy-path-button-color:#999;--copy-path-img-filter:invert(50%);--copy-path-img-hover-filter:invert(65%);--code-example-button-color:#7f7f7f;--code-example-button-hover-color:#a5a5a5;--codeblock-error-hover-color:rgb(255,0,0);--codeblock-error-color:rgba(255,0,0,.5);--codeblock-ignore-hover-color:rgb(255,142,0);--codeblock-ignore-color:rgba(255,142,0,.6);--warning-border-color:#ff8e00;--type-link-color:#2dbfb8;--trait-link-color:#b78cf2;--assoc-item-link-color:#d2991d;--function-link-color:#2bab63;--macro-link-color:#09bd00;--keyword-link-color:#d2991d;--mod-link-color:#d2991d;--link-color:#d2991d;--sidebar-link-color:#fdbf35;--sidebar-current-link-background-color:#444;--search-result-link-focus-background-color:#616161;--search-result-border-color:#aaa3;--search-color:#111;--search-error-code-background-color:#484848;--search-results-alias-color:#fff;--search-results-grey-color:#ccc;--search-tab-title-count-color:#888;--search-tab-button-not-selected-border-top-color:#252525;--search-tab-button-not-selected-background:#252525;--search-tab-button-selected-border-top-color:#0089ff;--search-tab-button-selected-background:#353535;--settings-menu-filter:invert(50%);--settings-menu-hover-filter:invert(65%);--stab-background-color:#314559;--stab-code-color:#e6e1cf;--code-highlight-kw-color:#ab8ac1;--code-highlight-kw-2-color:#769acb;--code-highlight-lifetime-color:#d97f26;--code-highlight-prelude-color:#769acb;--code-highlight-prelude-val-color:#ee6868;--code-highlight-number-color:#83a300;--code-highlight-string-color:#83a300;--code-highlight-literal-color:#ee6868;--code-highlight-attribute-color:#ee6868;--code-highlight-self-color:#ee6868;--code-highlight-macro-color:#3e999f;--code-highlight-question-mark-color:#ff9011;--code-highlight-comment-color:#8d8d8b;--code-highlight-doc-comment-color:#8ca375;--src-line-numbers-span-color:#3b91e2;--src-line-number-highlighted-background-color:#0a042f;--target-background-color:#494a3d;--target-border-color:#bb7410;--kbd-color:#000;--kbd-background:#fafbfc;--kbd-box-shadow-color:#c6cbd1;--rust-logo-filter:drop-shadow(1px 0 0px #fff) drop-shadow(0 1px 0 #fff) drop-shadow(-1px 0 0 #fff) drop-shadow(0 -1px 0 #fff);--crate-search-div-filter:invert(94%) sepia(0%) saturate(721%) hue-rotate(255deg) brightness(90%) contrast(90%);--crate-search-div-hover-filter:invert(69%) sepia(60%) saturate(6613%) hue-rotate(184deg) brightness(100%) contrast(91%);--crate-search-hover-border:#2196f3;--src-sidebar-background-selected:#333;--src-sidebar-background-hover:#444;--table-alt-row-background-color:#2a2a2a;--codeblock-link-background:#333;--scrape-example-toggle-line-background:#999;--scrape-example-toggle-line-hover-background:#c5c5c5;--scrape-example-code-line-highlight:#5b3b01;--scrape-example-code-line-highlight-focus:#7c4b0f;--scrape-example-help-border-color:#aaa;--scrape-example-help-color:#eee;--scrape-example-help-hover-border-color:#fff;--scrape-example-help-hover-color:#fff;--scrape-example-code-wrapper-background-start:rgba(53,53,53,1);--scrape-example-code-wrapper-background-end:rgba(53,53,53,0);--sidebar-resizer-hover:hsl(207,30%,54%);--sidebar-resizer-active:hsl(207,90%,54%);}} \ No newline at end of file diff --git a/static.files/rust-logo-9a9549ea.svg b/static.files/rust-logo-9a9549ea.svg new file mode 100644 index 000000000..62424d8ff --- /dev/null +++ b/static.files/rust-logo-9a9549ea.svg @@ -0,0 +1,61 @@ + + + diff --git a/static.files/rustdoc-a5dc3bae.css b/static.files/rustdoc-a5dc3bae.css new file mode 100644 index 000000000..218d08688 --- /dev/null +++ b/static.files/rustdoc-a5dc3bae.css @@ -0,0 +1,53 @@ + :root{--nav-sub-mobile-padding:8px;--search-typename-width:6.75rem;--desktop-sidebar-width:200px;--src-sidebar-width:300px;--desktop-sidebar-z-index:100;--sidebar-elems-left-padding:24px;--clipboard-image:url('data:image/svg+xml,\ +\ +\ +');--copy-path-height:34px;--copy-path-width:33px;--checkmark-image:url('data:image/svg+xml,\ +\ +');--button-left-margin:4px;--button-border-radius:2px;--toolbar-button-border-radius:6px;--code-block-border-radius:6px;}@font-face {font-family:'Fira Sans';font-style:normal;font-weight:400;src:local('Fira Sans'),url("FiraSans-Regular-0fe48ade.woff2") format("woff2");font-display:swap;}@font-face {font-family:'Fira Sans';font-style:normal;font-weight:500;src:local('Fira Sans Medium'),url("FiraSans-Medium-e1aa3f0a.woff2") format("woff2");font-display:swap;}@font-face {font-family:'Source Serif 4';font-style:normal;font-weight:400;src:local('Source Serif 4'),url("SourceSerif4-Regular-6b053e98.ttf.woff2") format("woff2");font-display:swap;}@font-face {font-family:'Source Serif 4';font-style:italic;font-weight:400;src:local('Source Serif 4 Italic'),url("SourceSerif4-It-ca3b17ed.ttf.woff2") format("woff2");font-display:swap;}@font-face {font-family:'Source Serif 4';font-style:normal;font-weight:700;src:local('Source Serif 4 Bold'),url("SourceSerif4-Bold-6d4fd4c0.ttf.woff2") format("woff2");font-display:swap;}@font-face {font-family:'Source Code Pro';font-style:normal;font-weight:400;src:url("SourceCodePro-Regular-8badfe75.ttf.woff2") format("woff2");font-display:swap;}@font-face {font-family:'Source Code Pro';font-style:italic;font-weight:400;src:url("SourceCodePro-It-fc8b9304.ttf.woff2") format("woff2");font-display:swap;}@font-face {font-family:'Source Code Pro';font-style:normal;font-weight:600;src:url("SourceCodePro-Semibold-aa29a496.ttf.woff2") format("woff2");font-display:swap;}@font-face {font-family:'NanumBarunGothic';src:url("NanumBarunGothic-13b3dcba.ttf.woff2") format("woff2");font-display:swap;unicode-range:U+AC00-D7AF,U+1100-11FF,U+3130-318F,U+A960-A97F,U+D7B0-D7FF;}*{box-sizing:border-box;}body{font:1rem/1.5 "Source Serif 4",NanumBarunGothic,serif;margin:0;position:relative;overflow-wrap:break-word;overflow-wrap:anywhere;font-feature-settings:"kern","liga";background-color:var(--main-background-color);color:var(--main-color);}h1{font-size:1.5rem;}h2{font-size:1.375rem;}h3{font-size:1.25rem;}h1,h2,h3,h4,h5,h6{font-weight:500;}h1,h2,h3,h4{margin:25px 0 15px 0;padding-bottom:6px;}.docblock h3,.docblock h4,h5,h6{margin:15px 0 5px 0;}.docblock>h2:first-child,.docblock>h3:first-child,.docblock>h4:first-child,.docblock>h5:first-child,.docblock>h6:first-child{margin-top:0;}.main-heading h1{margin:0;padding:0;grid-area:main-heading-h1;overflow-wrap:break-word;overflow-wrap:anywhere;}.main-heading{position:relative;display:grid;grid-template-areas:"main-heading-breadcrumbs main-heading-breadcrumbs" "main-heading-h1 main-heading-toolbar" "main-heading-sub-heading main-heading-toolbar";grid-template-columns:minmax(105px,1fr) minmax(0,max-content);grid-template-rows:minmax(25px,min-content) min-content min-content;padding-bottom:6px;margin-bottom:11px;}.rustdoc-breadcrumbs{grid-area:main-heading-breadcrumbs;line-height:1.25;display:flex;flex-wrap:wrap;align-items:end;padding-top:5px;}.rustdoc-breadcrumbs a{padding:4px 0;margin:-4px 0;z-index:1;}.content h2,.top-doc .docblock>h3,.top-doc .docblock>h4{border-bottom:1px solid var(--headings-border-bottom-color);}h1,h2{line-height:1.25;padding-top:3px;padding-bottom:9px;}h3.code-header{font-size:1.125rem;}h4.code-header{font-size:1rem;}.code-header{font-weight:600;margin:0;padding:0;white-space:pre-wrap;}.structfield{margin:0.6em 0;}#crate-search,h1,h2,h3,h4,h5,h6,.sidebar,.mobile-topbar,.search-input,.search-results .result-name,.item-name>a,.out-of-band,.sub-heading,span.since,a.src,rustdoc-toolbar,summary.hideme,.scraped-example-list,.rustdoc-breadcrumbs,ul.all-items{font-family:"Fira Sans",Arial,NanumBarunGothic,sans-serif;}#toggle-all-docs,a.anchor,.section-header a,#src-sidebar a,.rust a,.sidebar h2 a,.sidebar h3 a,.mobile-topbar h2 a,h1 a,.search-results a,.stab,.result-name i{color:var(--main-color);}span.enum,a.enum,span.struct,a.struct,span.union,a.union,span.primitive,a.primitive,span.type,a.type,span.foreigntype,a.foreigntype{color:var(--type-link-color);}span.trait,a.trait,span.traitalias,a.traitalias{color:var(--trait-link-color);}span.associatedtype,a.associatedtype,span.constant,a.constant,span.static,a.static{color:var(--assoc-item-link-color);}span.fn,a.fn,span.method,a.method,span.tymethod,a.tymethod{color:var(--function-link-color);}span.attr,a.attr,span.derive,a.derive,span.macro,a.macro{color:var(--macro-link-color);}span.mod,a.mod{color:var(--mod-link-color);}span.keyword,a.keyword{color:var(--keyword-link-color);}a{color:var(--link-color);text-decoration:none;}ol,ul{padding-left:24px;}ul ul,ol ul,ul ol,ol ol{margin-bottom:.625em;}p,.docblock>.warning{margin:0 0 .75em 0;}p:last-child,.docblock>.warning:last-child{margin:0;}button{padding:1px 6px;cursor:pointer;}button#toggle-all-docs{padding:0;background:none;border:none;-webkit-appearance:none;opacity:1;}.rustdoc{display:flex;flex-direction:row;flex-wrap:nowrap;}main{position:relative;flex-grow:1;padding:10px 15px 40px 45px;min-width:0;}.src main{padding:15px;}.width-limiter{max-width:960px;margin-right:auto;}details:not(.toggle) summary{margin-bottom:.6em;}code,pre,.code-header{font-family:"Source Code Pro",monospace;}.docblock code,.docblock-short code{border-radius:3px;padding:0 0.125em;}.docblock pre code,.docblock-short pre code{padding:0;}pre{padding:14px;line-height:1.5;}pre.item-decl{overflow-x:auto;}.item-decl .type-contents-toggle{contain:initial;}.src .content pre{padding:20px;}.rustdoc.src .example-wrap .src-line-numbers{padding:20px 0 20px 4px;}img{max-width:100%;}.logo-container{line-height:0;display:block;}.rust-logo{filter:var(--rust-logo-filter);}.sidebar{font-size:0.875rem;flex:0 0 var(--desktop-sidebar-width);width:var(--desktop-sidebar-width);overflow-y:scroll;overscroll-behavior:contain;position:sticky;height:100vh;top:0;left:0;z-index:var(--desktop-sidebar-z-index);}.rustdoc.src .sidebar{flex-basis:50px;width:50px;border-right:1px solid;overflow-x:hidden;overflow-y:hidden;}.hide-sidebar .sidebar,.hide-sidebar .sidebar-resizer{display:none;}.sidebar-resizer{touch-action:none;width:9px;cursor:col-resize;z-index:calc(var(--desktop-sidebar-z-index) + 1);position:fixed;height:100%;left:calc(var(--desktop-sidebar-width) + 1px);}.rustdoc.src .sidebar-resizer{left:49px;}.src-sidebar-expanded .src .sidebar-resizer{left:var(--src-sidebar-width);}.sidebar-resizing{-moz-user-select:none;-webkit-user-select:none;-ms-user-select:none;user-select:none;}.sidebar-resizing*{cursor:col-resize !important;}.sidebar-resizing .sidebar{position:fixed;}.sidebar-resizing>body{padding-left:var(--resizing-sidebar-width);}.sidebar-resizer:hover,.sidebar-resizer:active,.sidebar-resizer:focus,.sidebar-resizer.active{width:10px;margin:0;left:var(--desktop-sidebar-width);border-left:solid 1px var(--sidebar-resizer-hover);}.src-sidebar-expanded .rustdoc.src .sidebar-resizer:hover,.src-sidebar-expanded .rustdoc.src .sidebar-resizer:active,.src-sidebar-expanded .rustdoc.src .sidebar-resizer:focus,.src-sidebar-expanded .rustdoc.src .sidebar-resizer.active{left:calc(var(--src-sidebar-width) - 1px);}@media (pointer:coarse){.sidebar-resizer{display:none !important;}}.sidebar-resizer.active{padding:0 140px;width:2px;margin-left:-140px;border-left:none;}.sidebar-resizer.active:before{border-left:solid 2px var(--sidebar-resizer-active);display:block;height:100%;content:"";}.sidebar,.mobile-topbar,.sidebar-menu-toggle,#src-sidebar{background-color:var(--sidebar-background-color);}.src .sidebar>*{visibility:hidden;}.src-sidebar-expanded .src .sidebar{overflow-y:auto;flex-basis:var(--src-sidebar-width);width:var(--src-sidebar-width);}.src-sidebar-expanded .src .sidebar>*{visibility:visible;}#all-types{margin-top:1em;}*{scrollbar-width:initial;scrollbar-color:var(--scrollbar-color);}.sidebar{scrollbar-width:thin;scrollbar-color:var(--scrollbar-color);}::-webkit-scrollbar{width:12px;}.sidebar::-webkit-scrollbar{width:8px;}::-webkit-scrollbar-track{-webkit-box-shadow:inset 0;background-color:var(--scrollbar-track-background-color);}.sidebar::-webkit-scrollbar-track{background-color:var(--scrollbar-track-background-color);}::-webkit-scrollbar-thumb,.sidebar::-webkit-scrollbar-thumb{background-color:var(--scrollbar-thumb-background-color);}.hidden{display:none !important;}.logo-container>img{height:48px;width:48px;}ul.block,.block li,.block ul{padding:0;margin:0;list-style:none;}.block ul a{padding-left:1rem;}.sidebar-elems a,.sidebar>h2 a{display:block;padding:0.25rem;margin-right:0.25rem;border-left:solid var(--sidebar-elems-left-padding) transparent;margin-left:calc(-0.25rem - var(--sidebar-elems-left-padding));background-clip:border-box;}.hide-toc #rustdoc-toc,.hide-toc .in-crate{display:none;}.hide-modnav #rustdoc-modnav{display:none;}.sidebar h2{text-wrap:balance;overflow-wrap:anywhere;padding:0;margin:0.7rem 0;}.sidebar h3{text-wrap:balance;overflow-wrap:anywhere;font-size:1.125rem;padding:0;margin:0;}.sidebar-elems,.sidebar>.version,.sidebar>h2{padding-left:var(--sidebar-elems-left-padding);}.sidebar a{color:var(--sidebar-link-color);}.sidebar .current,.sidebar .current a,.sidebar-crate a.logo-container:hover+h2 a,.sidebar a:hover:not(.logo-container){background-color:var(--sidebar-current-link-background-color);}.sidebar-elems .block{margin-bottom:2em;}.sidebar-elems .block li a{white-space:nowrap;text-overflow:ellipsis;overflow:hidden;}.sidebar-crate{display:flex;align-items:center;justify-content:center;margin:14px 32px 1rem;row-gap:10px;column-gap:32px;flex-wrap:wrap;}.sidebar-crate h2{flex-grow:1;margin:0 -8px;align-self:start;}.sidebar-crate .logo-container{margin:0 calc(-16px - var(--sidebar-elems-left-padding));padding:0 var(--sidebar-elems-left-padding);text-align:center;}.sidebar-crate .logo-container img{margin-top:-16px;border-top:solid 16px transparent;box-sizing:content-box;position:relative;background-clip:border-box;z-index:1;}.sidebar-crate h2 a{display:block;border-left:solid var(--sidebar-elems-left-padding) transparent;background-clip:border-box;margin:0 calc(-24px + 0.25rem) 0 calc(-0.2rem - var(--sidebar-elems-left-padding));padding:calc((16px - 0.57rem ) / 2 ) 0.25rem;padding-left:0.2rem;}.sidebar-crate h2 .version{display:block;font-weight:normal;font-size:1rem;overflow-wrap:break-word;}.sidebar-crate+.version{margin-top:-1rem;margin-bottom:1rem;}.mobile-topbar{display:none;}.rustdoc .example-wrap{display:flex;position:relative;margin-bottom:10px;}.rustdoc .example-wrap>pre,.rustdoc .scraped-example .src-line-numbers,.rustdoc .scraped-example .src-line-numbers>pre{border-radius:6px;}.rustdoc .example-wrap>.example-line-numbers,.rustdoc .scraped-example .src-line-numbers,.rustdoc .scraped-example .src-line-numbers>pre{border-top-right-radius:0;border-bottom-right-radius:0;}.rustdoc .example-wrap>.example-line-numbers+pre,.rustdoc .scraped-example .rust{border-top-left-radius:0;border-bottom-left-radius:0;}.rustdoc .scraped-example{position:relative;}.rustdoc .example-wrap:last-child{margin-bottom:0px;}.rustdoc .example-wrap pre{margin:0;flex-grow:1;}.scraped-example:not(.expanded) .example-wrap{max-height:calc(1.5em * 5 + 10px);}.more-scraped-examples .scraped-example:not(.expanded) .example-wrap{max-height:calc(1.5em * 10 + 10px);}.rustdoc:not(.src) .scraped-example:not(.expanded) .src-line-numbers,.rustdoc:not(.src) .scraped-example:not(.expanded) .src-line-numbers>pre,.rustdoc:not(.src) .scraped-example:not(.expanded) pre.rust{padding-bottom:0;overflow:auto hidden;}.rustdoc:not(.src) .scraped-example .src-line-numbers{padding-top:0;}.rustdoc:not(.src) .scraped-example.expanded .src-line-numbers{padding-bottom:0;}.rustdoc:not(.src) .example-wrap pre{overflow:auto;}.rustdoc .example-wrap pre.example-line-numbers,.rustdoc .example-wrap .src-line-numbers{min-width:fit-content;flex-grow:0;text-align:right;-webkit-user-select:none;user-select:none;padding:14px 8px;padding-right:2px;color:var(--src-line-numbers-span-color);}.rustdoc .scraped-example .example-wrap .src-line-numbers{padding:0;}.rustdoc .src-line-numbers pre{padding:14px 0;}.src-line-numbers a,.src-line-numbers span{color:var(--src-line-numbers-span-color);padding:0 8px;}.src-line-numbers :target{background-color:transparent;border-right:none;padding:0 8px;}.src-line-numbers .line-highlighted{background-color:var(--src-line-number-highlighted-background-color);}.search-loading{text-align:center;}.docblock-short{overflow-wrap:break-word;overflow-wrap:anywhere;}.docblock :not(pre)>code,.docblock-short code{white-space:pre-wrap;}.top-doc .docblock h2{font-size:1.375rem;}.top-doc .docblock h3{font-size:1.25rem;}.top-doc .docblock h4,.top-doc .docblock h5{font-size:1.125rem;}.top-doc .docblock h6{font-size:1rem;}.docblock h5{font-size:1rem;}.docblock h6{font-size:0.875rem;}.docblock{margin-left:24px;position:relative;}.docblock>:not(.more-examples-toggle):not(.example-wrap){max-width:100%;overflow-x:auto;}.sub-heading{font-size:1rem;flex-grow:0;grid-area:main-heading-sub-heading;line-height:1.25;padding-bottom:4px;}.main-heading rustdoc-toolbar,.main-heading .out-of-band{grid-area:main-heading-toolbar;}rustdoc-toolbar{display:flex;flex-direction:row;flex-wrap:nowrap;min-height:60px;}.docblock code,.docblock-short code,pre,.rustdoc.src .example-wrap,.example-wrap .src-line-numbers{background-color:var(--code-block-background-color);border-radius:var(--code-block-border-radius);}#main-content{position:relative;}.docblock table{margin:.5em 0;border-collapse:collapse;}.docblock table td,.docblock table th{padding:.5em;border:1px solid var(--border-color);}.docblock table tbody tr:nth-child(2n){background:var(--table-alt-row-background-color);}.docblock .stab,.docblock-short .stab{display:inline-block;}.docblock li{margin-bottom:.4em;}.docblock li p:not(:last-child){margin-bottom:.3em;}div.where{white-space:pre-wrap;font-size:0.875rem;}.item-info{display:block;margin-left:24px;}.item-info code{font-size:0.875rem;}#main-content>.item-info{margin-left:0;}nav.sub{flex-grow:1;flex-flow:row nowrap;margin:4px 0 0 0;display:flex;align-items:center;}.search-form{position:relative;display:flex;height:34px;flex-grow:1;}.src nav.sub{margin:0 0 -10px 0;}.section-header{display:block;position:relative;}.section-header:hover>.anchor,.impl:hover>.anchor,.trait-impl:hover>.anchor,.variant:hover>.anchor{display:initial;}.anchor{display:none;position:absolute;left:-0.5em;background:none !important;}.anchor.field{left:-5px;}.section-header>.anchor{left:-15px;padding-right:8px;}h2.section-header>.anchor{padding-right:6px;}a.doc-anchor{color:var(--main-color);display:none;position:absolute;left:-17px;padding-right:10px;padding-left:3px;}*:hover>.doc-anchor{display:block;}.top-doc>.docblock>*:first-child>.doc-anchor{display:none !important;}.main-heading a:hover,.example-wrap .rust a:hover,.all-items a:hover,.docblock a:not(.scrape-help):not(.tooltip):hover:not(.doc-anchor),.docblock-short a:not(.scrape-help):not(.tooltip):hover,.item-info a{text-decoration:underline;}.crate.block li.current a{font-weight:500;}table,.item-table{overflow-wrap:break-word;}.item-table{display:table;padding:0;margin:0;width:100%;}.item-table>li{display:table-row;}.item-table>li>div{display:table-cell;}.item-table>li>.item-name{padding-right:1.25rem;}.search-results-title{margin-top:0;white-space:nowrap;display:flex;align-items:baseline;}.search-results-title+.sub-heading{color:var(--main-color);display:flex;align-items:baseline;white-space:nowrap;}#crate-search-div{position:relative;min-width:0;}#crate-search{padding:0 23px 0 4px;max-width:100%;text-overflow:ellipsis;border:1px solid var(--border-color);border-radius:4px;outline:none;cursor:pointer;-moz-appearance:none;-webkit-appearance:none;text-indent:0.01px;background-color:var(--main-background-color);color:inherit;line-height:1.5;font-weight:500;}#crate-search:hover,#crate-search:focus{border-color:var(--crate-search-hover-border);}#crate-search-div::after{pointer-events:none;width:100%;height:100%;position:absolute;top:0;left:0;content:"";background-repeat:no-repeat;background-size:20px;background-position:calc(100% - 2px) 56%;background-image:url('data:image/svg+xml, \ + ');filter:var(--crate-search-div-filter);}#crate-search-div:hover::after,#crate-search-div:focus-within::after{filter:var(--crate-search-div-hover-filter);}#crate-search>option{font-size:1rem;}.search-input{-webkit-appearance:none;outline:none;border:1px solid var(--border-color);border-radius:2px;padding:8px;font-size:1rem;flex-grow:1;background-color:var(--button-background-color);color:var(--search-color);}.search-input:focus{border-color:var(--search-input-focused-border-color);}.search-results{display:none;}.search-results.active{display:block;}.search-results>a{display:flex;margin-left:2px;margin-right:2px;border-bottom:1px solid var(--search-result-border-color);gap:1em;}.search-results>a>div.desc{white-space:nowrap;text-overflow:ellipsis;overflow:hidden;flex:2;}.search-results a:hover,.search-results a:focus{background-color:var(--search-result-link-focus-background-color);}.search-results .result-name{display:flex;align-items:center;justify-content:start;flex:3;}.search-results .result-name .alias{color:var(--search-results-alias-color);}.search-results .result-name .grey{color:var(--search-results-grey-color);}.search-results .result-name .typename{color:var(--search-results-grey-color);font-size:0.875rem;width:var(--search-typename-width);}.search-results .result-name .path{word-break:break-all;max-width:calc(100% - var(--search-typename-width));display:inline-block;}.search-results .result-name .path>*{display:inline;}.popover{position:absolute;top:100%;right:0;z-index:calc(var(--desktop-sidebar-z-index) + 1);margin-top:7px;border-radius:3px;border:1px solid var(--border-color);background-color:var(--main-background-color);color:var(--main-color);--popover-arrow-offset:11px;}.popover::before{content:'';position:absolute;right:var(--popover-arrow-offset);border:solid var(--border-color);border-width:1px 1px 0 0;background-color:var(--main-background-color);padding:4px;transform:rotate(-45deg);top:-5px;}.setting-line{margin:1.2em 0.6em;}.setting-radio input,.setting-check input{margin-right:0.3em;height:1.2rem;width:1.2rem;border:2px solid var(--settings-input-border-color);outline:none;-webkit-appearance:none;cursor:pointer;}.setting-radio input{border-radius:50%;}.setting-radio span,.setting-check span{padding-bottom:1px;}.setting-radio{margin-top:0.1em;margin-bottom:0.1em;min-width:3.8em;padding:0.3em;display:inline-flex;align-items:center;cursor:pointer;}.setting-radio+.setting-radio{margin-left:0.5em;}.setting-check{margin-right:20px;display:flex;align-items:center;cursor:pointer;}.setting-radio input:checked{box-shadow:inset 0 0 0 3px var(--main-background-color);background-color:var(--settings-input-color);}.setting-check input:checked{background-color:var(--settings-input-color);border-width:1px;content:url('data:image/svg+xml,\ + \ + ');}.setting-radio input:focus,.setting-check input:focus{box-shadow:0 0 1px 1px var(--settings-input-color);}.setting-radio input:checked:focus{box-shadow:inset 0 0 0 3px var(--main-background-color),0 0 2px 2px var(--settings-input-color);}.setting-radio input:hover,.setting-check input:hover{border-color:var(--settings-input-color) !important;}#settings.popover{--popover-arrow-offset:202px;top:calc(100% - 16px);}#help.popover{max-width:600px;--popover-arrow-offset:118px;top:calc(100% - 16px);}#help dt{float:left;clear:left;margin-right:0.5rem;}#help dd{margin-bottom:0.5rem;}#help span.top,#help span.bottom{text-align:center;display:block;font-size:1.125rem;padding:0 0.5rem;text-wrap-style:balance;}#help span.top{margin:10px 0;border-bottom:1px solid var(--border-color);padding-bottom:4px;margin-bottom:6px;}#help span.bottom{clear:both;border-top:1px solid var(--border-color);}.side-by-side{display:flex;margin-bottom:20px;}.side-by-side>div{width:50%;padding:0 20px 0 17px;}.item-info .stab{display:block;padding:3px;margin-bottom:5px;}.item-name .stab{margin-left:0.3125em;}.stab{padding:0 2px;font-size:0.875rem;font-weight:normal;color:var(--main-color);background-color:var(--stab-background-color);width:fit-content;white-space:pre-wrap;border-radius:3px;display:inline;vertical-align:baseline;}.stab.portability>code{background:none;color:var(--stab-code-color);}.stab .emoji,.item-info .stab::before{font-size:1.25rem;}.stab .emoji{margin-right:0.3rem;}.item-info .stab::before{content:"\0";width:0;display:inline-block;color:transparent;}.emoji{text-shadow:1px 0 0 black,-1px 0 0 black,0 1px 0 black,0 -1px 0 black;}.since{font-weight:normal;font-size:initial;}.rightside{padding-left:12px;float:right;}.rightside:not(a),.out-of-band,.sub-heading,rustdoc-toolbar{color:var(--right-side-color);}pre.rust{tab-size:4;-moz-tab-size:4;}pre.rust .kw{color:var(--code-highlight-kw-color);}pre.rust .kw-2{color:var(--code-highlight-kw-2-color);}pre.rust .lifetime{color:var(--code-highlight-lifetime-color);}pre.rust .prelude-ty{color:var(--code-highlight-prelude-color);}pre.rust .prelude-val{color:var(--code-highlight-prelude-val-color);}pre.rust .string{color:var(--code-highlight-string-color);}pre.rust .number{color:var(--code-highlight-number-color);}pre.rust .bool-val{color:var(--code-highlight-literal-color);}pre.rust .self{color:var(--code-highlight-self-color);}pre.rust .attr{color:var(--code-highlight-attribute-color);}pre.rust .macro,pre.rust .macro-nonterminal{color:var(--code-highlight-macro-color);}pre.rust .question-mark{font-weight:bold;color:var(--code-highlight-question-mark-color);}pre.rust .comment{color:var(--code-highlight-comment-color);}pre.rust .doccomment{color:var(--code-highlight-doc-comment-color);}.rustdoc.src .example-wrap pre.rust a{background:var(--codeblock-link-background);}.example-wrap.compile_fail,.example-wrap.should_panic{border-left:2px solid var(--codeblock-error-color);}.ignore.example-wrap{border-left:2px solid var(--codeblock-ignore-color);}.example-wrap.compile_fail:hover,.example-wrap.should_panic:hover{border-left:2px solid var(--codeblock-error-hover-color);}.example-wrap.ignore:hover{border-left:2px solid var(--codeblock-ignore-hover-color);}.example-wrap.compile_fail .tooltip,.example-wrap.should_panic .tooltip{color:var(--codeblock-error-color);}.example-wrap.ignore .tooltip{color:var(--codeblock-ignore-color);}.example-wrap.compile_fail:hover .tooltip,.example-wrap.should_panic:hover .tooltip{color:var(--codeblock-error-hover-color);}.example-wrap.ignore:hover .tooltip{color:var(--codeblock-ignore-hover-color);}.example-wrap .tooltip{position:absolute;display:block;left:-25px;top:5px;margin:0;line-height:1;}.example-wrap.compile_fail .tooltip,.example-wrap.should_panic .tooltip,.example-wrap.ignore .tooltip{font-weight:bold;font-size:1.25rem;}.content .docblock .warning{border-left:2px solid var(--warning-border-color);padding:14px;position:relative;overflow-x:visible !important;}.content .docblock .warning::before{color:var(--warning-border-color);content:"ⓘ";position:absolute;left:-25px;top:5px;font-weight:bold;font-size:1.25rem;}.top-doc>.docblock>.warning:first-child::before{top:20px;}.example-wrap>a.test-arrow,.example-wrap .button-holder{visibility:hidden;position:absolute;top:4px;right:4px;z-index:1;}a.test-arrow{height:var(--copy-path-height);padding:6px 4px 0 11px;}a.test-arrow::before{content:url('data:image/svg+xml,');}.example-wrap .button-holder{display:flex;}@media not (pointer:coarse){.example-wrap:hover>a.test-arrow,.example-wrap:hover>.button-holder{visibility:visible;}}.example-wrap .button-holder.keep-visible{visibility:visible;}.example-wrap .button-holder>*{background:var(--main-background-color);cursor:pointer;border-radius:var(--button-border-radius);height:var(--copy-path-height);width:var(--copy-path-width);border:0;color:var(--code-example-button-color);}.example-wrap .button-holder>*:hover{color:var(--code-example-button-hover-color);}.example-wrap .button-holder>*:not(:first-child){margin-left:var(--button-left-margin);}.example-wrap .button-holder .copy-button{padding:2px 0 0 4px;}.example-wrap .button-holder .copy-button::before,.example-wrap .test-arrow::before{filter:var(--copy-path-img-filter);}.example-wrap .button-holder .copy-button::before{content:var(--clipboard-image);}.example-wrap .button-holder .copy-button:hover::before,.example-wrap .test-arrow:hover::before{filter:var(--copy-path-img-hover-filter);}.example-wrap .button-holder .copy-button.clicked::before{content:var(--checkmark-image);padding-right:5px;}.code-attribute{font-weight:300;color:var(--code-attribute-color);}.item-spacer{width:100%;height:12px;display:block;}.main-heading span.since::before{content:"Since ";}.sub-variant h4{font-size:1rem;font-weight:400;margin-top:0;margin-bottom:0;}.sub-variant{margin-left:24px;margin-bottom:40px;}.sub-variant>.sub-variant-field{margin-left:24px;}@keyframes targetfadein{from{background-color:var(--main-background-color);}10%{background-color:var(--target-border-color);}to{background-color:var(--target-background-color);}}:target{padding-right:3px;background-color:var(--target-background-color);border-right:3px solid var(--target-border-color);}.code-header a.tooltip{color:inherit;margin-right:15px;position:relative;}.code-header a.tooltip:hover{color:var(--link-color);}a.tooltip:hover::after{position:absolute;top:calc(100% - 10px);left:-15px;right:-15px;height:20px;content:"\00a0";}@media not (prefers-reduced-motion){:target{animation:0.65s cubic-bezier(0,0,0.1,1.0) 0.1s targetfadein;}.fade-out{opacity:0;transition:opacity 0.45s cubic-bezier(0,0,0.1,1.0);}}.popover.tooltip .content{margin:0.25em 0.5em;}.popover.tooltip .content pre,.popover.tooltip .content code{background:transparent;margin:0;padding:0;font-size:1.25rem;white-space:pre-wrap;}.popover.tooltip .content>h3:first-child{margin:0 0 5px 0;}.search-failed{text-align:center;margin-top:20px;display:none;}.search-failed.active{display:block;}.search-failed>ul{text-align:left;max-width:570px;margin-left:auto;margin-right:auto;}#search-tabs{margin-top:0.25rem;display:flex;flex-direction:row;gap:1px;margin-bottom:4px;}#search-tabs button{text-align:center;font-size:1.125rem;border:0;border-top:2px solid;flex:1;line-height:1.5;color:inherit;}#search-tabs button:not(.selected){background-color:var(--search-tab-button-not-selected-background);border-top-color:var(--search-tab-button-not-selected-border-top-color);}#search-tabs button:hover,#search-tabs button.selected{background-color:var(--search-tab-button-selected-background);border-top-color:var(--search-tab-button-selected-border-top-color);}#search-tabs .count{font-size:1rem;font-variant-numeric:tabular-nums;color:var(--search-tab-title-count-color);}#search .error code{border-radius:3px;background-color:var(--search-error-code-background-color);}.search-corrections{font-weight:normal;}#src-sidebar{width:100%;overflow:auto;}#src-sidebar div.files>a:hover,details.dir-entry summary:hover,#src-sidebar div.files>a:focus,details.dir-entry summary:focus{background-color:var(--src-sidebar-background-hover);}#src-sidebar div.files>a.selected{background-color:var(--src-sidebar-background-selected);}.src-sidebar-title{position:sticky;top:0;display:flex;padding:8px 8px 0 48px;margin-bottom:7px;background:var(--sidebar-background-color);border-bottom:1px solid var(--border-color);}#settings-menu,#help-button,button#toggle-all-docs{margin-left:var(--button-left-margin);display:flex;line-height:1.25;min-width:14px;}#sidebar-button{display:none;line-height:0;}.hide-sidebar #sidebar-button,.src #sidebar-button{display:flex;margin-right:4px;position:fixed;left:6px;height:34px;width:34px;background-color:var(--main-background-color);z-index:1;}.src #sidebar-button{left:8px;z-index:calc(var(--desktop-sidebar-z-index) + 1);}.hide-sidebar .src #sidebar-button{position:static;}#settings-menu>a,#help-button>a,#sidebar-button>a,button#toggle-all-docs{display:flex;align-items:center;justify-content:center;flex-direction:column;border:1px solid transparent;border-radius:var(--button-border-radius);color:var(--main-color);}#settings-menu>a,#help-button>a,button#toggle-all-docs{width:80px;border-radius:var(--toolbar-button-border-radius);}#settings-menu>a,#help-button>a{min-width:0;}#sidebar-button>a{background-color:var(--button-background-color);border-color:var(--border-color);width:33px;}#settings-menu>a:hover,#settings-menu>a:focus-visible,#help-button>a:hover,#help-button>a:focus-visible,#sidebar-button>a:hover,#sidebar-button>a:focus-visible,button#toggle-all-docs:hover,button#toggle-all-docs:focus-visible{border-color:var(--settings-button-border-focus);text-decoration:none;}#settings-menu>a:before{content:url('data:image/svg+xml,\ + ');width:18px;height:18px;filter:var(--settings-menu-filter);}button#toggle-all-docs:before{content:url('data:image/svg+xml,\ + ');width:18px;height:18px;filter:var(--settings-menu-filter);}#help-button>a:before{content:url('data:image/svg+xml,\ + \ + ?');width:18px;height:18px;filter:var(--settings-menu-filter);}button#toggle-all-docs:before,#help-button>a:before,#settings-menu>a:before{filter:var(--settings-menu-filter);margin:8px;}@media not (pointer:coarse){button#toggle-all-docs:hover:before,#help-button>a:hover:before,#settings-menu>a:hover:before{filter:var(--settings-menu-hover-filter);}}button[disabled]#toggle-all-docs{opacity:0.25;border:solid 1px var(--main-background-color);background-size:cover;}button[disabled]#toggle-all-docs:hover{border:solid 1px var(--main-background-color);cursor:not-allowed;}rustdoc-toolbar span.label{font-size:1rem;flex-grow:1;padding-bottom:4px;}#sidebar-button>a:before{content:url('data:image/svg+xml,\ + \ + \ + ');width:22px;height:22px;}#copy-path{color:var(--copy-path-button-color);background:var(--main-background-color);height:var(--copy-path-height);width:var(--copy-path-width);margin-left:10px;padding:0;padding-left:2px;border:0;font-size:0;}#copy-path::before{filter:var(--copy-path-img-filter);content:var(--clipboard-image);}#copy-path:hover::before{filter:var(--copy-path-img-hover-filter);}#copy-path.clicked::before{content:var(--checkmark-image);}@keyframes rotating{from{transform:rotate(0deg);}to{transform:rotate(360deg);}}#settings-menu.rotate>a img{animation:rotating 2s linear infinite;}kbd{display:inline-block;padding:3px 5px;font:15px monospace;line-height:10px;vertical-align:middle;border:solid 1px var(--border-color);border-radius:3px;color:var(--kbd-color);background-color:var(--kbd-background);box-shadow:inset 0 -1px 0 var(--kbd-box-shadow-color);}ul.all-items>li{list-style:none;}details.dir-entry{padding-left:4px;}details.dir-entry>summary{margin:0 0 0 -4px;padding:0 0 0 4px;cursor:pointer;}details.dir-entry div.folders,details.dir-entry div.files{padding-left:23px;}details.dir-entry a{display:block;}details.toggle{contain:layout;position:relative;}details.big-toggle{contain:inline-size;}details.toggle>summary.hideme{cursor:pointer;font-size:1rem;}details.toggle>summary{list-style:none;outline:none;}details.toggle>summary::-webkit-details-marker,details.toggle>summary::marker{display:none;}details.toggle>summary.hideme>span{margin-left:9px;}details.toggle>summary::before{background:url('data:image/svg+xml,\ + ');content:"";cursor:pointer;width:16px;height:16px;display:inline-block;vertical-align:middle;opacity:.5;filter:var(--toggle-filter);}details.toggle>summary.hideme>span,.more-examples-toggle summary,.more-examples-toggle .hide-more{color:var(--toggles-color);}details.toggle>summary::after{content:"Expand";overflow:hidden;width:0;height:0;position:absolute;}details.toggle>summary.hideme::after{content:"";}details.toggle>summary:focus::before,details.toggle>summary:hover::before{opacity:1;}details.toggle>summary:focus-visible::before{outline:1px dotted #000;outline-offset:1px;}details.non-exhaustive{margin-bottom:8px;}details.toggle>summary.hideme::before{position:relative;}details.toggle>summary:not(.hideme)::before{position:absolute;left:-24px;top:4px;}.impl-items>details.toggle>summary:not(.hideme)::before{position:absolute;left:-24px;}details.big-toggle>summary:not(.hideme)::before{left:-34px;top:9px;}details.toggle[open] >summary.hideme{position:absolute;}details.toggle[open] >summary.hideme>span{display:none;}details.toggle[open] >summary::before{background:url('data:image/svg+xml,\ + ');}details.toggle[open] >summary::after{content:"Collapse";}.docblock summary>*{display:inline-block;}.docblock>.example-wrap:first-child .tooltip{margin-top:16px;}.src #sidebar-button>a:before,.sidebar-menu-toggle:before{content:url('data:image/svg+xml,\ + ');opacity:0.75;}.sidebar-menu-toggle:hover:before,.sidebar-menu-toggle:active:before,.sidebar-menu-toggle:focus:before{opacity:1;}.src #sidebar-button>a:before{content:url('data:image/svg+xml,\ + \ + \ + ');opacity:0.75;}@media (max-width:850px){#search-tabs .count{display:block;}.side-by-side{flex-direction:column-reverse;}.side-by-side>div{width:auto;}}@media (max-width:700px){*[id]{scroll-margin-top:45px;}#copy-path{display:none;}rustdoc-toolbar span.label{display:none;}#settings-menu>a,#help-button>a,button#toggle-all-docs{width:33px;}#settings.popover{--popover-arrow-offset:86px;}#help.popover{--popover-arrow-offset:48px;}.rustdoc{display:block;}main{padding-left:15px;padding-top:0px;}.sidebar .logo-container,.sidebar .location,.sidebar-resizer{display:none;}.sidebar{position:fixed;top:45px;left:-1000px;z-index:11;height:calc(100vh - 45px);width:200px;}.src main,.rustdoc.src .sidebar{top:0;padding:0;height:100vh;border:0;}.src .search-form{margin-left:40px;}.src .main-heading{margin-left:8px;}.hide-sidebar .search-form{margin-left:32px;}.hide-sidebar .src .search-form{margin-left:0;}.sidebar.shown,.src-sidebar-expanded .src .sidebar,.rustdoc:not(.src) .sidebar:focus-within{left:0;}.mobile-topbar h2{padding-bottom:0;margin:auto 0.5em auto auto;overflow:hidden;font-size:24px;white-space:nowrap;text-overflow:ellipsis;}.mobile-topbar .logo-container>img{max-width:35px;max-height:35px;margin:5px 0 5px 20px;}.mobile-topbar{display:flex;flex-direction:row;position:sticky;z-index:10;font-size:2rem;height:45px;width:100%;left:0;top:0;}.hide-sidebar .mobile-topbar{display:none;}.sidebar-menu-toggle{width:45px;border:none;line-height:0;}.hide-sidebar .sidebar-menu-toggle{display:none;}.sidebar-elems{margin-top:1em;}.anchor{display:none !important;}#main-content>details.toggle>summary::before,#main-content>div>details.toggle>summary::before{left:-11px;}#sidebar-button>a:before{content:url('data:image/svg+xml,\ + \ + \ + ');width:22px;height:22px;}.sidebar-menu-toggle:before{filter:var(--mobile-sidebar-menu-filter);}.sidebar-menu-toggle:hover{background:var(--main-background-color);}.item-table,.item-row,.item-table>li,.item-table>li>div,.search-results>a,.search-results>a>div{display:block;}.search-results>a{padding:5px 0px;}.search-results>a>div.desc,.item-table>li>div.desc{padding-left:2em;}.search-results .result-name{display:block;}.search-results .result-name .typename{width:initial;margin-right:0;}.search-results .result-name .typename,.search-results .result-name .path{display:inline;}.src-sidebar-expanded .src .sidebar{position:fixed;max-width:100vw;width:100vw;}.src .src-sidebar-title{padding-top:0;}details.toggle:not(.top-doc)>summary,.impl-items>section{margin-left:10px;}.impl-items>details.toggle>summary:not(.hideme)::before,#main-content>details.toggle:not(.top-doc)>summary::before,#main-content>div>details.toggle>summary::before{left:-11px;}.impl-items>.item-info{margin-left:34px;}.src nav.sub{margin:0 0 -25px 0;padding:var(--nav-sub-mobile-padding);}}@media (min-width:701px){.scraped-example-title{position:absolute;z-index:10;background:var(--main-background-color);bottom:8px;right:5px;padding:2px 4px;box-shadow:0 0 4px var(--main-background-color);}.item-table>li>.item-name{width:33%;}.item-table>li>div{overflow-wrap:anywhere;}}@media print{nav.sidebar,nav.sub,.out-of-band,a.src,#copy-path,details.toggle[open] >summary::before,details.toggle>summary::before,details.toggle.top-doc>summary{display:none;}.docblock{margin-left:0;}main{padding:10px;}}@media (max-width:464px){.docblock{margin-left:12px;}.docblock code{overflow-wrap:break-word;overflow-wrap:anywhere;}nav.sub{flex-direction:column;}.search-form{align-self:stretch;}}.variant,.implementors-toggle>summary,.impl,#implementors-list>.docblock,.impl-items>section,.impl-items>.toggle>summary,.methods>section,.methods>.toggle>summary{margin-bottom:0.75em;}.variants>.docblock,.implementors-toggle>.docblock,.impl-items>.toggle[open]:not(:last-child),.methods>.toggle[open]:not(:last-child),.implementors-toggle[open]:not(:last-child){margin-bottom:2em;}#trait-implementations-list .impl-items>.toggle:not(:last-child),#synthetic-implementations-list .impl-items>.toggle:not(:last-child),#blanket-implementations-list .impl-items>.toggle:not(:last-child){margin-bottom:1em;}.scraped-example-list .scrape-help{margin-left:10px;padding:0 4px;font-weight:normal;font-size:12px;position:relative;bottom:1px;border:1px solid var(--scrape-example-help-border-color);border-radius:50px;color:var(--scrape-example-help-color);}.scraped-example-list .scrape-help:hover{border-color:var(--scrape-example-help-hover-border-color);color:var(--scrape-example-help-hover-color);}.scraped-example:not(.expanded) .example-wrap::before,.scraped-example:not(.expanded) .example-wrap::after{content:" ";width:100%;height:5px;position:absolute;z-index:1;}.scraped-example:not(.expanded) .example-wrap::before{top:0;background:linear-gradient(to bottom,var(--scrape-example-code-wrapper-background-start),var(--scrape-example-code-wrapper-background-end));}.scraped-example:not(.expanded) .example-wrap::after{bottom:0;background:linear-gradient(to top,var(--scrape-example-code-wrapper-background-start),var(--scrape-example-code-wrapper-background-end));}.scraped-example:not(.expanded){width:100%;overflow-y:hidden;margin-bottom:0;}.scraped-example:not(.expanded){overflow-x:hidden;}.scraped-example .rust span.highlight{background:var(--scrape-example-code-line-highlight);}.scraped-example .rust span.highlight.focus{background:var(--scrape-example-code-line-highlight-focus);}.more-examples-toggle{max-width:calc(100% + 25px);margin-top:10px;margin-left:-25px;}.more-examples-toggle .hide-more{margin-left:25px;cursor:pointer;}.more-scraped-examples{margin-left:25px;position:relative;}.toggle-line{position:absolute;top:5px;bottom:0;right:calc(100% + 10px);padding:0 4px;cursor:pointer;}.toggle-line-inner{min-width:2px;height:100%;background:var(--scrape-example-toggle-line-background);}.toggle-line:hover .toggle-line-inner{background:var(--scrape-example-toggle-line-hover-background);}.more-scraped-examples .scraped-example,.example-links{margin-top:20px;}.more-scraped-examples .scraped-example:first-child{margin-top:5px;}.example-links ul{margin-bottom:0;}:root[data-theme="light"],:root:not([data-theme]){--main-background-color:white;--main-color:black;--settings-input-color:#2196f3;--settings-input-border-color:#717171;--settings-button-color:#000;--settings-button-border-focus:#717171;--sidebar-background-color:#f5f5f5;--sidebar-background-color-hover:#e0e0e0;--code-block-background-color:#f5f5f5;--scrollbar-track-background-color:#dcdcdc;--scrollbar-thumb-background-color:rgba(36,37,39,0.6);--scrollbar-color:rgba(36,37,39,0.6) #d9d9d9;--headings-border-bottom-color:#ddd;--border-color:#e0e0e0;--button-background-color:#fff;--right-side-color:grey;--code-attribute-color:#999;--toggles-color:#999;--toggle-filter:none;--mobile-sidebar-menu-filter:none;--search-input-focused-border-color:#66afe9;--copy-path-button-color:#999;--copy-path-img-filter:invert(50%);--copy-path-img-hover-filter:invert(35%);--code-example-button-color:#7f7f7f;--code-example-button-hover-color:#595959;--settings-menu-filter:invert(50%);--settings-menu-hover-filter:invert(35%);--codeblock-error-hover-color:rgb(255,0,0);--codeblock-error-color:rgba(255,0,0,.5);--codeblock-ignore-hover-color:rgb(255,142,0);--codeblock-ignore-color:rgba(255,142,0,.6);--warning-border-color:#ff8e00;--type-link-color:#ad378a;--trait-link-color:#6e4fc9;--assoc-item-link-color:#3873ad;--function-link-color:#ad7c37;--macro-link-color:#068000;--keyword-link-color:#3873ad;--mod-link-color:#3873ad;--link-color:#3873ad;--sidebar-link-color:#356da4;--sidebar-current-link-background-color:#fff;--search-result-link-focus-background-color:#ccc;--search-result-border-color:#aaa3;--search-color:#000;--search-error-code-background-color:#d0cccc;--search-results-alias-color:#000;--search-results-grey-color:#999;--search-tab-title-count-color:#888;--search-tab-button-not-selected-border-top-color:#e6e6e6;--search-tab-button-not-selected-background:#e6e6e6;--search-tab-button-selected-border-top-color:#0089ff;--search-tab-button-selected-background:#fff;--stab-background-color:#fff5d6;--stab-code-color:#000;--code-highlight-kw-color:#8959a8;--code-highlight-kw-2-color:#4271ae;--code-highlight-lifetime-color:#b76514;--code-highlight-prelude-color:#4271ae;--code-highlight-prelude-val-color:#c82829;--code-highlight-number-color:#718c00;--code-highlight-string-color:#718c00;--code-highlight-literal-color:#c82829;--code-highlight-attribute-color:#c82829;--code-highlight-self-color:#c82829;--code-highlight-macro-color:#3e999f;--code-highlight-question-mark-color:#ff9011;--code-highlight-comment-color:#8e908c;--code-highlight-doc-comment-color:#4d4d4c;--src-line-numbers-span-color:#c67e2d;--src-line-number-highlighted-background-color:#fdffd3;--target-background-color:#fdffd3;--target-border-color:#ad7c37;--kbd-color:#000;--kbd-background:#fafbfc;--kbd-box-shadow-color:#c6cbd1;--rust-logo-filter:initial;--crate-search-div-filter:invert(100%) sepia(0%) saturate(4223%) hue-rotate(289deg) brightness(114%) contrast(76%);--crate-search-div-hover-filter:invert(44%) sepia(18%) saturate(23%) hue-rotate(317deg) brightness(96%) contrast(93%);--crate-search-hover-border:#717171;--src-sidebar-background-selected:#fff;--src-sidebar-background-hover:#e0e0e0;--table-alt-row-background-color:#f5f5f5;--codeblock-link-background:#eee;--scrape-example-toggle-line-background:#ccc;--scrape-example-toggle-line-hover-background:#999;--scrape-example-code-line-highlight:#fcffd6;--scrape-example-code-line-highlight-focus:#f6fdb0;--scrape-example-help-border-color:#555;--scrape-example-help-color:#333;--scrape-example-help-hover-border-color:#000;--scrape-example-help-hover-color:#000;--scrape-example-code-wrapper-background-start:rgba(255,255,255,1);--scrape-example-code-wrapper-background-end:rgba(255,255,255,0);--sidebar-resizer-hover:hsl(207,90%,66%);--sidebar-resizer-active:hsl(207,90%,54%);}:root[data-theme="dark"]{--main-background-color:#353535;--main-color:#ddd;--settings-input-color:#2196f3;--settings-input-border-color:#999;--settings-button-color:#000;--settings-button-border-focus:#ffb900;--sidebar-background-color:#505050;--sidebar-background-color-hover:#676767;--code-block-background-color:#2A2A2A;--scrollbar-track-background-color:#717171;--scrollbar-thumb-background-color:rgba(32,34,37,.6);--scrollbar-color:rgba(32,34,37,.6) #5a5a5a;--headings-border-bottom-color:#d2d2d2;--border-color:#e0e0e0;--button-background-color:#f0f0f0;--right-side-color:grey;--code-attribute-color:#999;--toggles-color:#999;--toggle-filter:invert(100%);--mobile-sidebar-menu-filter:invert(100%);--search-input-focused-border-color:#008dfd;--copy-path-button-color:#999;--copy-path-img-filter:invert(50%);--copy-path-img-hover-filter:invert(65%);--code-example-button-color:#7f7f7f;--code-example-button-hover-color:#a5a5a5;--codeblock-error-hover-color:rgb(255,0,0);--codeblock-error-color:rgba(255,0,0,.5);--codeblock-ignore-hover-color:rgb(255,142,0);--codeblock-ignore-color:rgba(255,142,0,.6);--warning-border-color:#ff8e00;--type-link-color:#2dbfb8;--trait-link-color:#b78cf2;--assoc-item-link-color:#d2991d;--function-link-color:#2bab63;--macro-link-color:#09bd00;--keyword-link-color:#d2991d;--mod-link-color:#d2991d;--link-color:#d2991d;--sidebar-link-color:#fdbf35;--sidebar-current-link-background-color:#444;--search-result-link-focus-background-color:#616161;--search-result-border-color:#aaa3;--search-color:#111;--search-error-code-background-color:#484848;--search-results-alias-color:#fff;--search-results-grey-color:#ccc;--search-tab-title-count-color:#888;--search-tab-button-not-selected-border-top-color:#252525;--search-tab-button-not-selected-background:#252525;--search-tab-button-selected-border-top-color:#0089ff;--search-tab-button-selected-background:#353535;--settings-menu-filter:invert(50%);--settings-menu-hover-filter:invert(65%);--stab-background-color:#314559;--stab-code-color:#e6e1cf;--code-highlight-kw-color:#ab8ac1;--code-highlight-kw-2-color:#769acb;--code-highlight-lifetime-color:#d97f26;--code-highlight-prelude-color:#769acb;--code-highlight-prelude-val-color:#ee6868;--code-highlight-number-color:#83a300;--code-highlight-string-color:#83a300;--code-highlight-literal-color:#ee6868;--code-highlight-attribute-color:#ee6868;--code-highlight-self-color:#ee6868;--code-highlight-macro-color:#3e999f;--code-highlight-question-mark-color:#ff9011;--code-highlight-comment-color:#8d8d8b;--code-highlight-doc-comment-color:#8ca375;--src-line-numbers-span-color:#3b91e2;--src-line-number-highlighted-background-color:#0a042f;--target-background-color:#494a3d;--target-border-color:#bb7410;--kbd-color:#000;--kbd-background:#fafbfc;--kbd-box-shadow-color:#c6cbd1;--rust-logo-filter:drop-shadow(1px 0 0px #fff) drop-shadow(0 1px 0 #fff) drop-shadow(-1px 0 0 #fff) drop-shadow(0 -1px 0 #fff);--crate-search-div-filter:invert(94%) sepia(0%) saturate(721%) hue-rotate(255deg) brightness(90%) contrast(90%);--crate-search-div-hover-filter:invert(69%) sepia(60%) saturate(6613%) hue-rotate(184deg) brightness(100%) contrast(91%);--crate-search-hover-border:#2196f3;--src-sidebar-background-selected:#333;--src-sidebar-background-hover:#444;--table-alt-row-background-color:#2a2a2a;--codeblock-link-background:#333;--scrape-example-toggle-line-background:#999;--scrape-example-toggle-line-hover-background:#c5c5c5;--scrape-example-code-line-highlight:#5b3b01;--scrape-example-code-line-highlight-focus:#7c4b0f;--scrape-example-help-border-color:#aaa;--scrape-example-help-color:#eee;--scrape-example-help-hover-border-color:#fff;--scrape-example-help-hover-color:#fff;--scrape-example-code-wrapper-background-start:rgba(53,53,53,1);--scrape-example-code-wrapper-background-end:rgba(53,53,53,0);--sidebar-resizer-hover:hsl(207,30%,54%);--sidebar-resizer-active:hsl(207,90%,54%);}:root[data-theme="ayu"]{--main-background-color:#0f1419;--main-color:#c5c5c5;--settings-input-color:#ffb454;--settings-input-border-color:#999;--settings-button-color:#fff;--settings-button-border-focus:#e0e0e0;--sidebar-background-color:#14191f;--sidebar-background-color-hover:rgba(70,70,70,0.33);--code-block-background-color:#191f26;--scrollbar-track-background-color:transparent;--scrollbar-thumb-background-color:#5c6773;--scrollbar-color:#5c6773 #24292f;--headings-border-bottom-color:#5c6773;--border-color:#5c6773;--button-background-color:#141920;--right-side-color:grey;--code-attribute-color:#999;--toggles-color:#999;--toggle-filter:invert(100%);--mobile-sidebar-menu-filter:invert(100%);--search-input-focused-border-color:#5c6773;--copy-path-button-color:#fff;--copy-path-img-filter:invert(70%);--copy-path-img-hover-filter:invert(100%);--code-example-button-color:#b2b2b2;--code-example-button-hover-color:#fff;--codeblock-error-hover-color:rgb(255,0,0);--codeblock-error-color:rgba(255,0,0,.5);--codeblock-ignore-hover-color:rgb(255,142,0);--codeblock-ignore-color:rgba(255,142,0,.6);--warning-border-color:#ff8e00;--type-link-color:#ffa0a5;--trait-link-color:#39afd7;--assoc-item-link-color:#39afd7;--function-link-color:#fdd687;--macro-link-color:#a37acc;--keyword-link-color:#39afd7;--mod-link-color:#39afd7;--link-color:#39afd7;--sidebar-link-color:#53b1db;--sidebar-current-link-background-color:transparent;--search-result-link-focus-background-color:#3c3c3c;--search-result-border-color:#aaa3;--search-color:#fff;--search-error-code-background-color:#4f4c4c;--search-results-alias-color:#c5c5c5;--search-results-grey-color:#999;--search-tab-title-count-color:#888;--search-tab-button-not-selected-border-top-color:none;--search-tab-button-not-selected-background:transparent !important;--search-tab-button-selected-border-top-color:none;--search-tab-button-selected-background:#141920 !important;--settings-menu-filter:invert(70%);--settings-menu-hover-filter:invert(100%);--stab-background-color:#314559;--stab-code-color:#e6e1cf;--code-highlight-kw-color:#ff7733;--code-highlight-kw-2-color:#ff7733;--code-highlight-lifetime-color:#ff7733;--code-highlight-prelude-color:#69f2df;--code-highlight-prelude-val-color:#ff7733;--code-highlight-number-color:#b8cc52;--code-highlight-string-color:#b8cc52;--code-highlight-literal-color:#ff7733;--code-highlight-attribute-color:#e6e1cf;--code-highlight-self-color:#36a3d9;--code-highlight-macro-color:#a37acc;--code-highlight-question-mark-color:#ff9011;--code-highlight-comment-color:#788797;--code-highlight-doc-comment-color:#a1ac88;--src-line-numbers-span-color:#5c6773;--src-line-number-highlighted-background-color:rgba(255,236,164,0.06);--target-background-color:rgba(255,236,164,0.06);--target-border-color:rgba(255,180,76,0.85);--kbd-color:#c5c5c5;--kbd-background:#314559;--kbd-box-shadow-color:#5c6773;--rust-logo-filter:drop-shadow(1px 0 0px #fff) drop-shadow(0 1px 0 #fff) drop-shadow(-1px 0 0 #fff) drop-shadow(0 -1px 0 #fff);--crate-search-div-filter:invert(41%) sepia(12%) saturate(487%) hue-rotate(171deg) brightness(94%) contrast(94%);--crate-search-div-hover-filter:invert(98%) sepia(12%) saturate(81%) hue-rotate(343deg) brightness(113%) contrast(76%);--crate-search-hover-border:#e0e0e0;--src-sidebar-background-selected:#14191f;--src-sidebar-background-hover:#14191f;--table-alt-row-background-color:#191f26;--codeblock-link-background:#333;--scrape-example-toggle-line-background:#999;--scrape-example-toggle-line-hover-background:#c5c5c5;--scrape-example-code-line-highlight:#5b3b01;--scrape-example-code-line-highlight-focus:#7c4b0f;--scrape-example-help-border-color:#aaa;--scrape-example-help-color:#eee;--scrape-example-help-hover-border-color:#fff;--scrape-example-help-hover-color:#fff;--scrape-example-code-wrapper-background-start:rgba(15,20,25,1);--scrape-example-code-wrapper-background-end:rgba(15,20,25,0);--sidebar-resizer-hover:hsl(34,50%,33%);--sidebar-resizer-active:hsl(34,100%,66%);}:root[data-theme="ayu"] h1,:root[data-theme="ayu"] h2,:root[data-theme="ayu"] h3,:root[data-theme="ayu"] h4,:where(:root[data-theme="ayu"]) h1 a,:root[data-theme="ayu"] .sidebar h2 a,:root[data-theme="ayu"] .sidebar h3 a{color:#fff;}:root[data-theme="ayu"] .docblock code{color:#ffb454;}:root[data-theme="ayu"] .docblock a>code{color:#39AFD7 !important;}:root[data-theme="ayu"] .code-header,:root[data-theme="ayu"] .docblock pre>code,:root[data-theme="ayu"] pre,:root[data-theme="ayu"] pre>code,:root[data-theme="ayu"] .item-info code,:root[data-theme="ayu"] .rustdoc.source .example-wrap{color:#e6e1cf;}:root[data-theme="ayu"] .sidebar .current,:root[data-theme="ayu"] .sidebar .current a,:root[data-theme="ayu"] .sidebar a:hover,:root[data-theme="ayu"] #src-sidebar div.files>a:hover,:root[data-theme="ayu"] details.dir-entry summary:hover,:root[data-theme="ayu"] #src-sidebar div.files>a:focus,:root[data-theme="ayu"] details.dir-entry summary:focus,:root[data-theme="ayu"] #src-sidebar div.files>a.selected{color:#ffb44c;}:root[data-theme="ayu"] .sidebar-elems .location{color:#ff7733;}:root[data-theme="ayu"] .src-line-numbers .line-highlighted{color:#708090;padding-right:7px;border-right:1px solid #ffb44c;}:root[data-theme="ayu"] .search-results a:hover,:root[data-theme="ayu"] .search-results a:focus{color:#fff !important;background-color:#3c3c3c;}:root[data-theme="ayu"] .search-results a{color:#0096cf;}:root[data-theme="ayu"] .search-results a div.desc{color:#c5c5c5;}:root[data-theme="ayu"] .result-name .primitive>i,:root[data-theme="ayu"] .result-name .keyword>i{color:#788797;}:root[data-theme="ayu"] #search-tabs>button.selected{border-bottom:1px solid #ffb44c !important;border-top:none;}:root[data-theme="ayu"] #search-tabs>button:not(.selected){border:none;background-color:transparent !important;}:root[data-theme="ayu"] #search-tabs>button:hover{border-bottom:1px solid rgba(242,151,24,0.3);}:root[data-theme="ayu"] #settings-menu>a img,:root[data-theme="ayu"] #sidebar-button>a:before{filter:invert(100);} \ No newline at end of file diff --git a/static.files/scrape-examples-d508a8a9.js b/static.files/scrape-examples-d508a8a9.js new file mode 100644 index 000000000..87b6065d8 --- /dev/null +++ b/static.files/scrape-examples-d508a8a9.js @@ -0,0 +1 @@ +"use strict";(function(){const DEFAULT_MAX_LINES=5;const HIDDEN_MAX_LINES=10;function scrollToLoc(elt,loc,isHidden){const lines=elt.querySelector(".src-line-numbers > pre");let scrollOffset;const maxLines=isHidden?HIDDEN_MAX_LINES:DEFAULT_MAX_LINES;if(loc[1]-loc[0]>maxLines){const line=Math.max(0,loc[0]-1);scrollOffset=lines.children[line].offsetTop}else{const halfHeight=elt.offsetHeight/2;const offsetTop=lines.children[loc[0]].offsetTop;const lastLine=lines.children[loc[1]];const offsetBot=lastLine.offsetTop+lastLine.offsetHeight;const offsetMid=(offsetTop+offsetBot)/2;scrollOffset=offsetMid-halfHeight}lines.parentElement.scrollTo(0,scrollOffset);elt.querySelector(".rust").scrollTo(0,scrollOffset)}function createScrapeButton(parent,className,content){const button=document.createElement("button");button.className=className;button.innerText=content;parent.insertBefore(button,parent.firstChild);return button}window.updateScrapedExample=(example,buttonHolder)=>{let locIndex=0;const highlights=Array.prototype.slice.call(example.querySelectorAll(".highlight"));const link=example.querySelector(".scraped-example-title a");let expandButton=null;if(!example.classList.contains("expanded")){expandButton=createScrapeButton(buttonHolder,"expand","↕")}const isHidden=example.parentElement.classList.contains("more-scraped-examples");const locs=example.locs;if(locs.length>1){const next=createScrapeButton(buttonHolder,"next","≻");const prev=createScrapeButton(buttonHolder,"prev","≺");const onChangeLoc=changeIndex=>{removeClass(highlights[locIndex],"focus");changeIndex();scrollToLoc(example,locs[locIndex][0],isHidden);addClass(highlights[locIndex],"focus");const url=locs[locIndex][1];const title=locs[locIndex][2];link.href=url;link.innerHTML=title};prev.addEventListener("click",()=>{onChangeLoc(()=>{locIndex=(locIndex-1+locs.length)%locs.length})});next.addEventListener("click",()=>{onChangeLoc(()=>{locIndex=(locIndex+1)%locs.length})})}if(expandButton){expandButton.addEventListener("click",()=>{if(hasClass(example,"expanded")){removeClass(example,"expanded");scrollToLoc(example,locs[0][0],isHidden)}else{addClass(example,"expanded")}})}};function setupLoc(example,isHidden){example.locs=JSON.parse(example.attributes.getNamedItem("data-locs").textContent);scrollToLoc(example,example.locs[0][0],isHidden)}const firstExamples=document.querySelectorAll(".scraped-example-list > .scraped-example");onEachLazy(firstExamples,el=>setupLoc(el,false));onEachLazy(document.querySelectorAll(".more-examples-toggle"),toggle=>{onEachLazy(toggle.querySelectorAll(".toggle-line, .hide-more"),button=>{button.addEventListener("click",()=>{toggle.open=false})});const moreExamples=toggle.querySelectorAll(".scraped-example");toggle.querySelector("summary").addEventListener("click",()=>{setTimeout(()=>{onEachLazy(moreExamples,el=>setupLoc(el,true))})},{once:true})})})() \ No newline at end of file diff --git a/static.files/search-c5a66128.js b/static.files/search-c5a66128.js new file mode 100644 index 000000000..3e2c702e3 --- /dev/null +++ b/static.files/search-c5a66128.js @@ -0,0 +1,6 @@ +"use strict";if(!Array.prototype.toSpliced){Array.prototype.toSpliced=function(){const me=this.slice();Array.prototype.splice.apply(me,arguments);return me}}(function(){const itemTypes=["keyword","primitive","mod","externcrate","import","struct","enum","fn","type","static","trait","impl","tymethod","method","structfield","variant","macro","associatedtype","constant","associatedconstant","union","foreigntype","existential","attr","derive","traitalias","generic",];const TY_GENERIC=itemTypes.indexOf("generic");const TY_IMPORT=itemTypes.indexOf("import");const ROOT_PATH=typeof window!=="undefined"?window.rootPath:"../";const UNBOXING_LIMIT=5;const REGEX_IDENT=/\p{ID_Start}\p{ID_Continue}*|_\p{ID_Continue}+/uy;const REGEX_INVALID_TYPE_FILTER=/[^a-z]/ui;const MAX_RESULTS=200;const NO_TYPE_FILTER=-1;const editDistanceState={current:[],prev:[],prevPrev:[],calculate:function calculate(a,b,limit){if(a.lengthlimit){return limit+1}while(b.length>0&&b[0]===a[0]){a=a.substring(1);b=b.substring(1)}while(b.length>0&&b[b.length-1]===a[a.length-1]){a=a.substring(0,a.length-1);b=b.substring(0,b.length-1)}if(b.length===0){return minDist}const aLength=a.length;const bLength=b.length;for(let i=0;i<=bLength;++i){this.current[i]=0;this.prev[i]=i;this.prevPrev[i]=Number.MAX_VALUE}for(let i=1;i<=aLength;++i){this.current[0]=i;const aIdx=i-1;for(let j=1;j<=bLength;++j){const bIdx=j-1;const substitutionCost=a[aIdx]===b[bIdx]?0:1;this.current[j]=Math.min(this.prev[j]+1,this.current[j-1]+1,this.prev[j-1]+substitutionCost,);if((i>1)&&(j>1)&&(a[aIdx]===b[bIdx-1])&&(a[aIdx-1]===b[bIdx])){this.current[j]=Math.min(this.current[j],this.prevPrev[j-2]+1,)}}const prevPrevTmp=this.prevPrev;this.prevPrev=this.prev;this.prev=this.current;this.current=prevPrevTmp}const distance=this.prev[bLength];return distance<=limit?distance:(limit+1)},};function editDistance(a,b,limit){return editDistanceState.calculate(a,b,limit)}function isEndCharacter(c){return"=,>-])".indexOf(c)!==-1}function isSeparatorCharacter(c){return c===","||c==="="}function isReturnArrow(parserState){return parserState.userQuery.slice(parserState.pos,parserState.pos+2)==="->"}function skipWhitespace(parserState){while(parserState.pos0){const c=parserState.userQuery[pos-1];if(c===lookingFor){return true}else if(c!==" "){break}pos-=1}return false}function isLastElemGeneric(elems,parserState){return(elems.length>0&&elems[elems.length-1].generics.length>0)||prevIs(parserState,">")}function getFilteredNextElem(query,parserState,elems,isInGenerics){const start=parserState.pos;if(parserState.userQuery[parserState.pos]===":"&&!isPathStart(parserState)){throw["Expected type filter before ",":"]}getNextElem(query,parserState,elems,isInGenerics);if(parserState.userQuery[parserState.pos]===":"&&!isPathStart(parserState)){if(parserState.typeFilter!==null){throw["Unexpected ",":"," (expected path after type filter ",parserState.typeFilter+":",")",]}if(elems.length===0){throw["Expected type filter before ",":"]}else if(query.literalSearch){throw["Cannot use quotes on type filter"]}const typeFilterElem=elems.pop();checkExtraTypeFilterCharacters(start,parserState);parserState.typeFilter=typeFilterElem.name;parserState.pos+=1;parserState.totalElems-=1;query.literalSearch=false;getNextElem(query,parserState,elems,isInGenerics)}}function getItemsBefore(query,parserState,elems,endChar){let foundStopChar=true;let foundSeparator=false;const oldTypeFilter=parserState.typeFilter;parserState.typeFilter=null;const oldIsInBinding=parserState.isInBinding;parserState.isInBinding=null;let hofParameters=null;let extra="";if(endChar===">"){extra="<"}else if(endChar==="]"){extra="["}else if(endChar===")"){extra="("}else if(endChar===""){extra="->"}else{extra=endChar}while(parserState.pos"," after ","="]}hofParameters=[...elems];elems.length=0;parserState.pos+=2;foundStopChar=true;foundSeparator=false;continue}else if(c===" "){parserState.pos+=1;continue}else if(isSeparatorCharacter(c)){parserState.pos+=1;foundStopChar=true;foundSeparator=true;continue}else if(c===":"&&isPathStart(parserState)){throw["Unexpected ","::",": paths cannot start with ","::"]}else if(isEndCharacter(c)){throw["Unexpected ",c," after ",extra]}if(!foundStopChar){let extra=[];if(isLastElemGeneric(query.elems,parserState)){extra=[" after ",">"]}else if(prevIs(parserState,"\"")){throw["Cannot have more than one element if you use quotes"]}if(endChar!==""){throw["Expected ",",",", ","=",", or ",endChar,...extra,", found ",c,]}throw["Expected ",","," or ","=",...extra,", found ",c,]}const posBefore=parserState.pos;getFilteredNextElem(query,parserState,elems,endChar!=="");if(endChar!==""&&parserState.pos>=parserState.length){throw["Unclosed ",extra]}if(posBefore===parserState.pos){parserState.pos+=1}foundStopChar=false}if(parserState.pos>=parserState.length&&endChar!==""){throw["Unclosed ",extra]}parserState.pos+=1;if(hofParameters){foundSeparator=false;if([...elems,...hofParameters].some(x=>x.bindingName)||parserState.isInBinding){throw["Unexpected ","="," within ","->"]}const hofElem=makePrimitiveElement("->",{generics:hofParameters,bindings:new Map([["output",[...elems]]]),typeFilter:null,});elems.length=0;elems[0]=hofElem}parserState.typeFilter=oldTypeFilter;parserState.isInBinding=oldIsInBinding;return{foundSeparator}}function getNextElem(query,parserState,elems,isInGenerics){const generics=[];skipWhitespace(parserState);let start=parserState.pos;let end;if("[(".indexOf(parserState.userQuery[parserState.pos])!==-1){let endChar=")";let name="()";let friendlyName="tuple";if(parserState.userQuery[parserState.pos]==="["){endChar="]";name="[]";friendlyName="slice"}parserState.pos+=1;const{foundSeparator}=getItemsBefore(query,parserState,generics,endChar);const typeFilter=parserState.typeFilter;const bindingName=parserState.isInBinding;parserState.typeFilter=null;parserState.isInBinding=null;for(const gen of generics){if(gen.bindingName!==null){throw["Type parameter ","=",` cannot be within ${friendlyName} `,name]}}if(name==="()"&&!foundSeparator&&generics.length===1&&typeFilter===null){elems.push(generics[0])}else if(name==="()"&&generics.length===1&&generics[0].name==="->"){generics[0].typeFilter=typeFilter;elems.push(generics[0])}else{if(typeFilter!==null&&typeFilter!=="primitive"){throw["Invalid search type: primitive ",name," and ",typeFilter," both specified",]}parserState.totalElems+=1;if(isInGenerics){parserState.genericsElems+=1}elems.push(makePrimitiveElement(name,{bindingName,generics}))}}else if(parserState.userQuery[parserState.pos]==="&"){if(parserState.typeFilter!==null&&parserState.typeFilter!=="primitive"){throw["Invalid search type: primitive ","&"," and ",parserState.typeFilter," both specified",]}parserState.typeFilter=null;parserState.pos+=1;let c=parserState.userQuery[parserState.pos];while(c===" "&&parserState.pos=end){throw["Found generics without a path"]}parserState.pos+=1;getItemsBefore(query,parserState,generics,">")}else if(parserState.pos=end){throw["Found generics without a path"]}if(parserState.isInBinding){throw["Unexpected ","("," after ","="]}parserState.pos+=1;const typeFilter=parserState.typeFilter;parserState.typeFilter=null;getItemsBefore(query,parserState,generics,")");skipWhitespace(parserState);if(isReturnArrow(parserState)){parserState.pos+=2;skipWhitespace(parserState);getFilteredNextElem(query,parserState,generics,isInGenerics);generics[generics.length-1].bindingName=makePrimitiveElement("output")}else{generics.push(makePrimitiveElement(null,{bindingName:makePrimitiveElement("output"),typeFilter:null,}))}parserState.typeFilter=typeFilter}if(isStringElem){skipWhitespace(parserState)}if(start>=end&&generics.length===0){return}if(parserState.userQuery[parserState.pos]==="="){if(parserState.isInBinding){throw["Cannot write ","="," twice in a binding"]}if(!isInGenerics){throw["Type parameter ","="," must be within generics list"]}const name=parserState.userQuery.slice(start,end).trim();if(name==="!"){throw["Type parameter ","="," key cannot be ","!"," never type"]}if(name.includes("!")){throw["Type parameter ","="," key cannot be ","!"," macro"]}if(name.includes("::")){throw["Type parameter ","="," key cannot contain ","::"," path"]}if(name.includes(":")){throw["Type parameter ","="," key cannot contain ",":"," type"]}parserState.isInBinding={name,generics}}else{elems.push(createQueryElement(query,parserState,parserState.userQuery.slice(start,end),generics,isInGenerics,),)}}}function checkExtraTypeFilterCharacters(start,parserState){const query=parserState.userQuery.slice(start,parserState.pos).trim();const match=query.match(REGEX_INVALID_TYPE_FILTER);if(match){throw["Unexpected ",match[0]," in type filter (before ",":",")",]}}function createQueryElement(query,parserState,name,generics,isInGenerics){const path=name.trim();if(path.length===0&&generics.length===0){throw["Unexpected ",parserState.userQuery[parserState.pos]]}if(query.literalSearch&&parserState.totalElems-parserState.genericsElems>0){throw["Cannot have more than one element if you use quotes"]}const typeFilter=parserState.typeFilter;parserState.typeFilter=null;if(name.trim()==="!"){if(typeFilter!==null&&typeFilter!=="primitive"){throw["Invalid search type: primitive never type ","!"," and ",typeFilter," both specified",]}if(generics.length!==0){throw["Never type ","!"," does not accept generic parameters",]}const bindingName=parserState.isInBinding;parserState.isInBinding=null;return makePrimitiveElement("never",{bindingName})}const quadcolon=/::\s*::/.exec(path);if(path.startsWith("::")){throw["Paths cannot start with ","::"]}else if(path.endsWith("::")){throw["Paths cannot end with ","::"]}else if(quadcolon!==null){throw["Unexpected ",quadcolon[0]]}const pathSegments=path.split(/(?:::\s*)|(?:\s+(?:::\s*)?)/);if(pathSegments.length===0||(pathSegments.length===1&&pathSegments[0]==="")){if(generics.length>0||prevIs(parserState,">")){throw["Found generics without a path"]}else{throw["Unexpected ",parserState.userQuery[parserState.pos]]}}for(const[i,pathSegment]of pathSegments.entries()){if(pathSegment==="!"){if(i!==0){throw["Never type ","!"," is not associated item"]}pathSegments[i]="never"}}parserState.totalElems+=1;if(isInGenerics){parserState.genericsElems+=1}const bindingName=parserState.isInBinding;parserState.isInBinding=null;const bindings=new Map();const pathLast=pathSegments[pathSegments.length-1];return{name:name.trim(),id:null,fullPath:pathSegments,pathWithoutLast:pathSegments.slice(0,pathSegments.length-1),pathLast,normalizedPathLast:pathLast.replace(/_/g,""),generics:generics.filter(gen=>{if(gen.bindingName!==null){if(gen.name!==null){gen.bindingName.generics.unshift(gen)}bindings.set(gen.bindingName.name,gen.bindingName.generics);return false}return true}),bindings,typeFilter,bindingName,}}function makePrimitiveElement(name,extra){return Object.assign({name,id:null,fullPath:[name],pathWithoutLast:[],pathLast:name,normalizedPathLast:name,generics:[],bindings:new Map(),typeFilter:"primitive",bindingName:null,},extra)}function getStringElem(query,parserState,isInGenerics){if(isInGenerics){throw["Unexpected ","\""," in generics"]}else if(query.literalSearch){throw["Cannot have more than one literal search element"]}else if(parserState.totalElems-parserState.genericsElems>0){throw["Cannot use literal search when there is more than one element"]}parserState.pos+=1;const start=parserState.pos;const end=getIdentEndPosition(parserState);if(parserState.pos>=parserState.length){throw["Unclosed ","\""]}else if(parserState.userQuery[end]!=="\""){throw["Unexpected ",parserState.userQuery[end]," in a string element"]}else if(start===end){throw["Cannot have empty string element"]}parserState.pos+=1;query.literalSearch=true}function getIdentEndPosition(parserState){let afterIdent=consumeIdent(parserState);let end=parserState.pos;let macroExclamation=-1;while(parserState.pos0){throw["Unexpected ",c," after ",parserState.userQuery[parserState.pos-1]," (not a valid identifier)"]}else{throw["Unexpected ",c," (not a valid identifier)"]}parserState.pos+=1;afterIdent=consumeIdent(parserState);end=parserState.pos}if(macroExclamation!==-1){if(parserState.typeFilter===null){parserState.typeFilter="macro"}else if(parserState.typeFilter!=="macro"){throw["Invalid search type: macro ","!"," and ",parserState.typeFilter," both specified",]}end=macroExclamation}return end}function isSpecialStartCharacter(c){return"<\"".indexOf(c)!==-1}function isPathStart(parserState){return parserState.userQuery.slice(parserState.pos,parserState.pos+2)==="::"}function consumeIdent(parserState){REGEX_IDENT.lastIndex=parserState.pos;const match=parserState.userQuery.match(REGEX_IDENT);if(match){parserState.pos+=match[0].length;return true}return false}function isPathSeparator(c){return c===":"||c===" "}class VlqHexDecoder{constructor(string,cons){this.string=string;this.cons=cons;this.offset=0;this.backrefQueue=[]}decodeList(){let c=this.string.charCodeAt(this.offset);const ret=[];while(c!==125){ret.push(this.decode());c=this.string.charCodeAt(this.offset)}this.offset+=1;return ret}decode(){let n=0;let c=this.string.charCodeAt(this.offset);if(c===123){this.offset+=1;return this.decodeList()}while(c<96){n=(n<<4)|(c&0xF);this.offset+=1;c=this.string.charCodeAt(this.offset)}n=(n<<4)|(c&0xF);const[sign,value]=[n&1,n>>1];this.offset+=1;return sign?-value:value}next(){const c=this.string.charCodeAt(this.offset);if(c>=48&&c<64){this.offset+=1;return this.backrefQueue[c-48]}if(c===96){this.offset+=1;return this.cons(0)}const result=this.cons(this.decode());this.backrefQueue.unshift(result);if(this.backrefQueue.length>16){this.backrefQueue.pop()}return result}}class RoaringBitmap{constructor(str){const strdecoded=atob(str);const u8array=new Uint8Array(strdecoded.length);for(let j=0;j=4){offsets=[];for(let j=0;j>3]&(1<<(j&0x7))){const runcount=(u8array[i]|(u8array[i+1]<<8));i+=2;this.containers.push(new RoaringBitmapRun(runcount,u8array.slice(i,i+(runcount*4)),));i+=runcount*4}else if(this.cardinalities[j]>=4096){this.containers.push(new RoaringBitmapBits(u8array.slice(i,i+8192)));i+=8192}else{const end=this.cardinalities[j]*2;this.containers.push(new RoaringBitmapArray(this.cardinalities[j],u8array.slice(i,i+end),));i+=end}}}contains(keyvalue){const key=keyvalue>>16;const value=keyvalue&0xFFFF;for(let i=0;i=start&&value<=(start+lenm1)){return true}}return false}}class RoaringBitmapArray{constructor(cardinality,array){this.cardinality=cardinality;this.array=array}contains(value){const l=this.cardinality*2;for(let i=0;i>3]&(1<<(value&7)))}}class DocSearch{constructor(rawSearchIndex,rootPath,searchState){this.searchIndexDeprecated=new Map();this.searchIndexEmptyDesc=new Map();this.functionTypeFingerprint=null;this.typeNameIdMap=new Map();this.ALIASES=new Map();this.rootPath=rootPath;this.searchState=searchState;this.typeNameIdOfArray=this.buildTypeMapIndex("array");this.typeNameIdOfSlice=this.buildTypeMapIndex("slice");this.typeNameIdOfArrayOrSlice=this.buildTypeMapIndex("[]");this.typeNameIdOfTuple=this.buildTypeMapIndex("tuple");this.typeNameIdOfUnit=this.buildTypeMapIndex("unit");this.typeNameIdOfTupleOrUnit=this.buildTypeMapIndex("()");this.typeNameIdOfFn=this.buildTypeMapIndex("fn");this.typeNameIdOfFnMut=this.buildTypeMapIndex("fnmut");this.typeNameIdOfFnOnce=this.buildTypeMapIndex("fnonce");this.typeNameIdOfHof=this.buildTypeMapIndex("->");this.EMPTY_BINDINGS_MAP=new Map();this.EMPTY_GENERICS_ARRAY=[];this.TYPES_POOL=new Map();this.searchIndex=this.buildIndex(rawSearchIndex)}buildTypeMapIndex(name,isAssocType){if(name===""||name===null){return null}if(this.typeNameIdMap.has(name)){const obj=this.typeNameIdMap.get(name);obj.assocOnly=isAssocType&&obj.assocOnly;return obj.id}else{const id=this.typeNameIdMap.size;this.typeNameIdMap.set(name,{id,assocOnly:isAssocType});return id}}buildItemSearchTypeAll(types,lowercasePaths){return types.length>0?types.map(type=>this.buildItemSearchType(type,lowercasePaths)):this.EMPTY_GENERICS_ARRAY}buildItemSearchType(type,lowercasePaths,isAssocType){const PATH_INDEX_DATA=0;const GENERICS_DATA=1;const BINDINGS_DATA=2;let pathIndex,generics,bindings;if(typeof type==="number"){pathIndex=type;generics=this.EMPTY_GENERICS_ARRAY;bindings=this.EMPTY_BINDINGS_MAP}else{pathIndex=type[PATH_INDEX_DATA];generics=this.buildItemSearchTypeAll(type[GENERICS_DATA],lowercasePaths,);if(type.length>BINDINGS_DATA&&type[BINDINGS_DATA].length>0){bindings=new Map(type[BINDINGS_DATA].map(binding=>{const[assocType,constraints]=binding;return[this.buildItemSearchType(assocType,lowercasePaths,true).id,this.buildItemSearchTypeAll(constraints,lowercasePaths),]}))}else{bindings=this.EMPTY_BINDINGS_MAP}}let result;if(pathIndex<0){result={id:pathIndex,ty:TY_GENERIC,path:null,exactPath:null,generics,bindings,}}else if(pathIndex===0){result={id:null,ty:null,path:null,exactPath:null,generics,bindings,}}else{const item=lowercasePaths[pathIndex-1];result={id:this.buildTypeMapIndex(item.name,isAssocType),ty:item.ty,path:item.path,exactPath:item.exactPath,generics,bindings,}}const cr=this.TYPES_POOL.get(result.id);if(cr){if(cr.generics.length===result.generics.length&&cr.generics!==result.generics&&cr.generics.every((x,i)=>result.generics[i]===x)){result.generics=cr.generics}if(cr.bindings.size===result.bindings.size&&cr.bindings!==result.bindings){let ok=true;for(const[k,v]of cr.bindings.entries()){const v2=result.bindings.get(v);if(!v2){ok=false;break}if(v!==v2&&v.length===v2.length&&v.every((x,i)=>v2[i]===x)){result.bindings.set(k,v)}else if(v!==v2){ok=false;break}}if(ok){result.bindings=cr.bindings}}if(cr.ty===result.ty&&cr.path===result.path&&cr.bindings===result.bindings&&cr.generics===result.generics&&cr.ty===result.ty){return cr}}this.TYPES_POOL.set(result.id,result);return result}buildFunctionTypeFingerprint(type,output,fps){let input=type.id;if(input===this.typeNameIdOfArray||input===this.typeNameIdOfSlice){input=this.typeNameIdOfArrayOrSlice}if(input===this.typeNameIdOfTuple||input===this.typeNameIdOfUnit){input=this.typeNameIdOfTupleOrUnit}if(input===this.typeNameIdOfFn||input===this.typeNameIdOfFnMut||input===this.typeNameIdOfFnOnce){input=this.typeNameIdOfHof}const hashint1=k=>{k=(~~k+0x7ed55d16)+(k<<12);k=(k ^ 0xc761c23c)^(k>>>19);k=(~~k+0x165667b1)+(k<<5);k=(~~k+0xd3a2646c)^(k<<9);k=(~~k+0xfd7046c5)+(k<<3);return(k ^ 0xb55a4f09)^(k>>>16)};const hashint2=k=>{k=~k+(k<<15);k ^=k>>>12;k+=k<<2;k ^=k>>>4;k=Math.imul(k,2057);return k ^(k>>16)};if(input!==null){const h0a=hashint1(input);const h0b=hashint2(input);const h1a=~~(h0a+Math.imul(h0b,2));const h1b=~~(h0a+Math.imul(h0b,3));const h2a=~~(h0a+Math.imul(h0b,4));const h2b=~~(h0a+Math.imul(h0b,5));output[0]|=(1<<(h0a%32))|(1<<(h1b%32));output[1]|=(1<<(h1a%32))|(1<<(h2b%32));output[2]|=(1<<(h2a%32))|(1<<(h0b%32));fps.add(input)}for(const g of type.generics){this.buildFunctionTypeFingerprint(g,output,fps)}const fb={id:null,ty:0,generics:this.EMPTY_GENERICS_ARRAY,bindings:this.EMPTY_BINDINGS_MAP,};for(const[k,v]of type.bindings.entries()){fb.id=k;fb.generics=v;this.buildFunctionTypeFingerprint(fb,output,fps)}output[3]=fps.size}buildIndex(rawSearchIndex){const buildFunctionSearchTypeCallback=lowercasePaths=>{return functionSearchType=>{if(functionSearchType===0){return null}const INPUTS_DATA=0;const OUTPUT_DATA=1;let inputs,output;if(typeof functionSearchType[INPUTS_DATA]==="number"){inputs=[this.buildItemSearchType(functionSearchType[INPUTS_DATA],lowercasePaths),]}else{inputs=this.buildItemSearchTypeAll(functionSearchType[INPUTS_DATA],lowercasePaths,)}if(functionSearchType.length>1){if(typeof functionSearchType[OUTPUT_DATA]==="number"){output=[this.buildItemSearchType(functionSearchType[OUTPUT_DATA],lowercasePaths,),]}else{output=this.buildItemSearchTypeAll(functionSearchType[OUTPUT_DATA],lowercasePaths,)}}else{output=[]}const where_clause=[];const l=functionSearchType.length;for(let i=2;inoop);let descShard={crate,shard:0,start:0,len:itemDescShardDecoder.next(),promise:null,resolve:null,};const descShardList=[descShard];this.searchIndexDeprecated.set(crate,new RoaringBitmap(crateCorpus.c));this.searchIndexEmptyDesc.set(crate,new RoaringBitmap(crateCorpus.e));let descIndex=0;const crateRow={crate,ty:3,name:crate,path:"",descShard,descIndex,exactPath:"",desc:crateCorpus.doc,parent:undefined,type:null,id,word:crate,normalizedName:crate.indexOf("_")===-1?crate:crate.replace(/_/g,""),bitIndex:0,implDisambiguator:null,};id+=1;searchIndex.push(crateRow);currentIndex+=1;if(!this.searchIndexEmptyDesc.get(crate).contains(0)){descIndex+=1}const itemTypes=crateCorpus.t;const itemNames=crateCorpus.n;const itemPaths=new Map(crateCorpus.q);const itemReexports=new Map(crateCorpus.r);const itemParentIdxDecoder=new VlqHexDecoder(crateCorpus.i,noop=>noop);const implDisambiguator=new Map(crateCorpus.b);const paths=crateCorpus.p;const aliases=crateCorpus.a;const lowercasePaths=[];const itemFunctionDecoder=new VlqHexDecoder(crateCorpus.f,buildFunctionSearchTypeCallback(lowercasePaths),);let len=paths.length;let lastPath=itemPaths.get(0);for(let i=0;i2){path=itemPaths.has(elem[2])?itemPaths.get(elem[2]):lastPath;lastPath=path}const exactPath=elem.length>3?itemPaths.get(elem[3]):path;lowercasePaths.push({ty,name:name.toLowerCase(),path,exactPath});paths[i]={ty,name,path,exactPath}}lastPath="";len=itemTypes.length;let lastName="";let lastWord="";for(let i=0;i=descShard.len&&!this.searchIndexEmptyDesc.get(crate).contains(bitIndex)){descShard={crate,shard:descShard.shard+1,start:descShard.start+descShard.len,len:itemDescShardDecoder.next(),promise:null,resolve:null,};descIndex=0;descShardList.push(descShard)}const name=itemNames[i]===""?lastName:itemNames[i];const word=itemNames[i]===""?lastWord:itemNames[i].toLowerCase();const path=itemPaths.has(i)?itemPaths.get(i):lastPath;const type=itemFunctionDecoder.next();if(type!==null){if(type){const fp=this.functionTypeFingerprint.subarray(id*4,(id+1)*4);const fps=new Set();for(const t of type.inputs){this.buildFunctionTypeFingerprint(t,fp,fps)}for(const t of type.output){this.buildFunctionTypeFingerprint(t,fp,fps)}for(const w of type.where_clause){for(const t of w){this.buildFunctionTypeFingerprint(t,fp,fps)}}}}const itemParentIdx=itemParentIdxDecoder.next();const row={crate,ty:itemTypes.charCodeAt(i)-65,name,path,descShard,descIndex,exactPath:itemReexports.has(i)?itemPaths.get(itemReexports.get(i)):path,parent:itemParentIdx>0?paths[itemParentIdx-1]:undefined,type,id,word,normalizedName:word.indexOf("_")===-1?word:word.replace(/_/g,""),bitIndex,implDisambiguator:implDisambiguator.has(i)?implDisambiguator.get(i):null,};id+=1;searchIndex.push(row);lastPath=row.path;if(!this.searchIndexEmptyDesc.get(crate).contains(bitIndex)){descIndex+=1}lastName=name;lastWord=word}if(aliases){const currentCrateAliases=new Map();this.ALIASES.set(crate,currentCrateAliases);for(const alias_name in aliases){if(!Object.prototype.hasOwnProperty.call(aliases,alias_name)){continue}let currentNameAliases;if(currentCrateAliases.has(alias_name)){currentNameAliases=currentCrateAliases.get(alias_name)}else{currentNameAliases=[];currentCrateAliases.set(alias_name,currentNameAliases)}for(const local_alias of aliases[alias_name]){currentNameAliases.push(local_alias+currentIndex)}}}currentIndex+=itemTypes.length;this.searchState.descShards.set(crate,descShardList)}this.TYPES_POOL=new Map();return searchIndex}static parseQuery(userQuery){function itemTypeFromName(typename){const index=itemTypes.findIndex(i=>i===typename);if(index<0){throw["Unknown type filter ",typename]}return index}function convertTypeFilterOnElem(elem){if(elem.typeFilter!==null){let typeFilter=elem.typeFilter;if(typeFilter==="const"){typeFilter="constant"}elem.typeFilter=itemTypeFromName(typeFilter)}else{elem.typeFilter=NO_TYPE_FILTER}for(const elem2 of elem.generics){convertTypeFilterOnElem(elem2)}for(const constraints of elem.bindings.values()){for(const constraint of constraints){convertTypeFilterOnElem(constraint)}}}function newParsedQuery(userQuery){return{original:userQuery,userQuery:userQuery.toLowerCase(),elems:[],returned:[],foundElems:0,totalElems:0,literalSearch:false,hasReturnArrow:false,error:null,correction:null,proposeCorrectionFrom:null,proposeCorrectionTo:null,typeFingerprint:new Uint32Array(4),}}function parseInput(query,parserState){let foundStopChar=true;while(parserState.pos"){if(isReturnArrow(parserState)){query.hasReturnArrow=true;break}throw["Unexpected ",c," (did you mean ","->","?)"]}else if(parserState.pos>0){throw["Unexpected ",c," after ",parserState.userQuery[parserState.pos-1]]}throw["Unexpected ",c]}else if(c===" "){skipWhitespace(parserState);continue}if(!foundStopChar){let extra="";if(isLastElemGeneric(query.elems,parserState)){extra=[" after ",">"]}else if(prevIs(parserState,"\"")){throw["Cannot have more than one element if you use quotes"]}if(parserState.typeFilter!==null){throw["Expected ",","," or ","->",...extra,", found ",c,]}throw["Expected ",",",", ",":"," or ","->",...extra,", found ",c,]}const before=query.elems.length;getFilteredNextElem(query,parserState,query.elems,false);if(query.elems.length===before){parserState.pos+=1}foundStopChar=false}if(parserState.typeFilter!==null){throw["Unexpected ",":"," (expected path after type filter ",parserState.typeFilter+":",")",]}while(parserState.pos1}query.foundElems=query.elems.length+query.returned.length;query.totalElems=parserState.totalElems;return query}async execQuery(parsedQuery,filterCrates,currentCrate){const results_others=new Map(),results_in_args=new Map(),results_returned=new Map();function createQueryResults(results_in_args,results_returned,results_others,parsedQuery){return{"in_args":results_in_args,"returned":results_returned,"others":results_others,"query":parsedQuery,}}const buildHrefAndPath=item=>{let displayPath;let href;const type=itemTypes[item.ty];const name=item.name;let path=item.path;let exactPath=item.exactPath;if(type==="mod"){displayPath=path+"::";href=this.rootPath+path.replace(/::/g,"/")+"/"+name+"/index.html"}else if(type==="import"){displayPath=item.path+"::";href=this.rootPath+item.path.replace(/::/g,"/")+"/index.html#reexport."+name}else if(type==="primitive"||type==="keyword"){displayPath="";href=this.rootPath+path.replace(/::/g,"/")+"/"+type+"."+name+".html"}else if(type==="externcrate"){displayPath="";href=this.rootPath+name+"/index.html"}else if(item.parent!==undefined){const myparent=item.parent;let anchor=type+"."+name;const parentType=itemTypes[myparent.ty];let pageType=parentType;let pageName=myparent.name;exactPath=`${myparent.exactPath}::${myparent.name}`;if(parentType==="primitive"){displayPath=myparent.name+"::"}else if(type==="structfield"&&parentType==="variant"){const enumNameIdx=item.path.lastIndexOf("::");const enumName=item.path.substr(enumNameIdx+2);path=item.path.substr(0,enumNameIdx);displayPath=path+"::"+enumName+"::"+myparent.name+"::";anchor="variant."+myparent.name+".field."+name;pageType="enum";pageName=enumName}else{displayPath=path+"::"+myparent.name+"::"}if(item.implDisambiguator!==null){anchor=item.implDisambiguator+"/"+anchor}href=this.rootPath+path.replace(/::/g,"/")+"/"+pageType+"."+pageName+".html#"+anchor}else{displayPath=item.path+"::";href=this.rootPath+item.path.replace(/::/g,"/")+"/"+type+"."+name+".html"}return[displayPath,href,`${exactPath}::${name}`]};function pathSplitter(path){const tmp=""+path.replace(/::/g,"::");if(tmp.endsWith("")){return tmp.slice(0,tmp.length-6)}return tmp}const transformResults=results=>{const duplicates=new Set();const out=[];for(const result of results){if(result.id!==-1){const obj=this.searchIndex[result.id];obj.dist=result.dist;const res=buildHrefAndPath(obj);obj.displayPath=pathSplitter(res[0]);obj.fullPath=res[2]+"|"+obj.ty;if(duplicates.has(obj.fullPath)){continue}if(obj.ty===TY_IMPORT&&duplicates.has(res[2])){continue}if(duplicates.has(res[2]+"|"+TY_IMPORT)){continue}duplicates.add(obj.fullPath);duplicates.add(res[2]);obj.href=res[1];out.push(obj);if(out.length>=MAX_RESULTS){break}}}return out};const sortResults=async(results,isType,preferredCrate)=>{const userQuery=parsedQuery.userQuery;const casedUserQuery=parsedQuery.original;const result_list=[];for(const result of results.values()){result.item=this.searchIndex[result.id];result.word=this.searchIndex[result.id].word;result_list.push(result)}result_list.sort((aaa,bbb)=>{let a,b;a=(aaa.item.name!==casedUserQuery);b=(bbb.item.name!==casedUserQuery);if(a!==b){return a-b}a=(aaa.word!==userQuery);b=(bbb.word!==userQuery);if(a!==b){return a-b}a=(aaa.index<0);b=(bbb.index<0);if(a!==b){return a-b}a=aaa.path_dist;b=bbb.path_dist;if(a!==b){return a-b}a=aaa.index;b=bbb.index;if(a!==b){return a-b}a=(aaa.dist);b=(bbb.dist);if(a!==b){return a-b}a=this.searchIndexDeprecated.get(aaa.item.crate).contains(aaa.item.bitIndex);b=this.searchIndexDeprecated.get(bbb.item.crate).contains(bbb.item.bitIndex);if(a!==b){return a-b}a=(aaa.item.crate!==preferredCrate);b=(bbb.item.crate!==preferredCrate);if(a!==b){return a-b}a=aaa.word.length;b=bbb.word.length;if(a!==b){return a-b}a=aaa.word;b=bbb.word;if(a!==b){return(a>b?+1:-1)}a=this.searchIndexEmptyDesc.get(aaa.item.crate).contains(aaa.item.bitIndex);b=this.searchIndexEmptyDesc.get(bbb.item.crate).contains(bbb.item.bitIndex);if(a!==b){return a-b}a=aaa.item.ty;b=bbb.item.ty;if(a!==b){return a-b}a=aaa.item.path;b=bbb.item.path;if(a!==b){return(a>b?+1:-1)}return 0});return transformResults(result_list)};function unifyFunctionTypes(fnTypesIn,queryElems,whereClause,mgensIn,solutionCb,unboxingDepth,){if(unboxingDepth>=UNBOXING_LIMIT){return false}const mgens=mgensIn===null?null:new Map(mgensIn);if(queryElems.length===0){return!solutionCb||solutionCb(mgens)}if(!fnTypesIn||fnTypesIn.length===0){return false}const ql=queryElems.length;const fl=fnTypesIn.length;if(ql===1&&queryElems[0].generics.length===0&&queryElems[0].bindings.size===0){const queryElem=queryElems[0];for(const fnType of fnTypesIn){if(!unifyFunctionTypeIsMatchCandidate(fnType,queryElem,mgens)){continue}if(fnType.id<0&&queryElem.id<0){if(mgens&&mgens.has(fnType.id)&&mgens.get(fnType.id)!==queryElem.id){continue}const mgensScratch=new Map(mgens);mgensScratch.set(fnType.id,queryElem.id);if(!solutionCb||solutionCb(mgensScratch)){return true}}else if(!solutionCb||solutionCb(mgens?new Map(mgens):null)){return true}}for(const fnType of fnTypesIn){if(!unifyFunctionTypeIsUnboxCandidate(fnType,queryElem,whereClause,mgens,unboxingDepth+1,)){continue}if(fnType.id<0){if(mgens&&mgens.has(fnType.id)&&mgens.get(fnType.id)!==0){continue}const mgensScratch=new Map(mgens);mgensScratch.set(fnType.id,0);if(unifyFunctionTypes(whereClause[(-fnType.id)-1],queryElems,whereClause,mgensScratch,solutionCb,unboxingDepth+1,)){return true}}else if(unifyFunctionTypes([...fnType.generics,...Array.from(fnType.bindings.values()).flat()],queryElems,whereClause,mgens?new Map(mgens):null,solutionCb,unboxingDepth+1,)){return true}}return false}const fnTypes=fnTypesIn.slice();const flast=fl-1;const qlast=ql-1;const queryElem=queryElems[qlast];let queryElemsTmp=null;for(let i=flast;i>=0;i-=1){const fnType=fnTypes[i];if(!unifyFunctionTypeIsMatchCandidate(fnType,queryElem,mgens)){continue}let mgensScratch;if(fnType.id<0){mgensScratch=new Map(mgens);if(mgensScratch.has(fnType.id)&&mgensScratch.get(fnType.id)!==queryElem.id){continue}mgensScratch.set(fnType.id,queryElem.id)}else{mgensScratch=mgens}fnTypes[i]=fnTypes[flast];fnTypes.length=flast;if(!queryElemsTmp){queryElemsTmp=queryElems.slice(0,qlast)}const passesUnification=unifyFunctionTypes(fnTypes,queryElemsTmp,whereClause,mgensScratch,mgensScratch=>{if(fnType.generics.length===0&&queryElem.generics.length===0&&fnType.bindings.size===0&&queryElem.bindings.size===0){return!solutionCb||solutionCb(mgensScratch)}const solution=unifyFunctionTypeCheckBindings(fnType,queryElem,whereClause,mgensScratch,unboxingDepth,);if(!solution){return false}const simplifiedGenerics=solution.simplifiedGenerics;for(const simplifiedMgens of solution.mgens){const passesUnification=unifyFunctionTypes(simplifiedGenerics,queryElem.generics,whereClause,simplifiedMgens,solutionCb,unboxingDepth,);if(passesUnification){return true}}return false},unboxingDepth,);if(passesUnification){return true}fnTypes[flast]=fnTypes[i];fnTypes[i]=fnType;fnTypes.length=fl}for(let i=flast;i>=0;i-=1){const fnType=fnTypes[i];if(!unifyFunctionTypeIsUnboxCandidate(fnType,queryElem,whereClause,mgens,unboxingDepth+1,)){continue}let mgensScratch;if(fnType.id<0){mgensScratch=new Map(mgens);if(mgensScratch.has(fnType.id)&&mgensScratch.get(fnType.id)!==0){continue}mgensScratch.set(fnType.id,0)}else{mgensScratch=mgens}const generics=fnType.id<0?whereClause[(-fnType.id)-1]:fnType.generics;const bindings=fnType.bindings?Array.from(fnType.bindings.values()).flat():[];const passesUnification=unifyFunctionTypes(fnTypes.toSpliced(i,1,...generics,...bindings),queryElems,whereClause,mgensScratch,solutionCb,unboxingDepth+1,);if(passesUnification){return true}}return false}const unifyFunctionTypeIsMatchCandidate=(fnType,queryElem,mgensIn)=>{if(!typePassesFilter(queryElem.typeFilter,fnType.ty)){return false}if(fnType.id<0&&queryElem.id<0){if(mgensIn){if(mgensIn.has(fnType.id)&&mgensIn.get(fnType.id)!==queryElem.id){return false}for(const[fid,qid]of mgensIn.entries()){if(fnType.id!==fid&&queryElem.id===qid){return false}if(fnType.id===fid&&queryElem.id!==qid){return false}}}return true}else{if(queryElem.id===this.typeNameIdOfArrayOrSlice&&(fnType.id===this.typeNameIdOfSlice||fnType.id===this.typeNameIdOfArray)){}else if(queryElem.id===this.typeNameIdOfTupleOrUnit&&(fnType.id===this.typeNameIdOfTuple||fnType.id===this.typeNameIdOfUnit)){}else if(queryElem.id===this.typeNameIdOfHof&&(fnType.id===this.typeNameIdOfFn||fnType.id===this.typeNameIdOfFnMut||fnType.id===this.typeNameIdOfFnOnce)){}else if(fnType.id!==queryElem.id||queryElem.id===null){return false}if((fnType.generics.length+fnType.bindings.size)===0&&queryElem.generics.length!==0){return false}if(fnType.bindings.size0){const fnTypePath=fnType.path!==undefined&&fnType.path!==null?fnType.path.split("::"):[];if(queryElemPathLength>fnTypePath.length){return false}let i=0;for(const path of fnTypePath){if(path===queryElem.pathWithoutLast[i]){i+=1;if(i>=queryElemPathLength){break}}}if(i0){let mgensSolutionSet=[mgensIn];for(const[name,constraints]of queryElem.bindings.entries()){if(mgensSolutionSet.length===0){return false}if(!fnType.bindings.has(name)){return false}const fnTypeBindings=fnType.bindings.get(name);mgensSolutionSet=mgensSolutionSet.flatMap(mgens=>{const newSolutions=[];unifyFunctionTypes(fnTypeBindings,constraints,whereClause,mgens,newMgens=>{newSolutions.push(newMgens);return false},unboxingDepth,);return newSolutions})}if(mgensSolutionSet.length===0){return false}const binds=Array.from(fnType.bindings.entries()).flatMap(entry=>{const[name,constraints]=entry;if(queryElem.bindings.has(name)){return[]}else{return constraints}});if(simplifiedGenerics.length>0){simplifiedGenerics=[...simplifiedGenerics,...binds]}else{simplifiedGenerics=binds}return{simplifiedGenerics,mgens:mgensSolutionSet}}return{simplifiedGenerics,mgens:[mgensIn]}}function unifyFunctionTypeIsUnboxCandidate(fnType,queryElem,whereClause,mgens,unboxingDepth,){if(unboxingDepth>=UNBOXING_LIMIT){return false}if(fnType.id<0&&queryElem.id>=0){if(!whereClause){return false}if(mgens&&mgens.has(fnType.id)&&mgens.get(fnType.id)!==0){return false}const mgensTmp=new Map(mgens);mgensTmp.set(fnType.id,null);return checkIfInList(whereClause[(-fnType.id)-1],queryElem,whereClause,mgensTmp,unboxingDepth,)}else if(fnType.generics.length>0||fnType.bindings.size>0){const simplifiedGenerics=[...fnType.generics,...Array.from(fnType.bindings.values()).flat(),];return checkIfInList(simplifiedGenerics,queryElem,whereClause,mgens,unboxingDepth,)}return false}function checkIfInList(list,elem,whereClause,mgens,unboxingDepth){for(const entry of list){if(checkType(entry,elem,whereClause,mgens,unboxingDepth)){return true}}return false}const checkType=(row,elem,whereClause,mgens,unboxingDepth)=>{if(unboxingDepth>=UNBOXING_LIMIT){return false}if(row.bindings.size===0&&elem.bindings.size===0){if(elem.id<0&&mgens===null){return row.id<0||checkIfInList(row.generics,elem,whereClause,mgens,unboxingDepth+1,)}if(row.id>0&&elem.id>0&&elem.pathWithoutLast.length===0&&typePassesFilter(elem.typeFilter,row.ty)&&elem.generics.length===0&&elem.id!==this.typeNameIdOfArrayOrSlice&&elem.id!==this.typeNameIdOfTupleOrUnit&&elem.id!==this.typeNameIdOfHof){return row.id===elem.id||checkIfInList(row.generics,elem,whereClause,mgens,unboxingDepth,)}}return unifyFunctionTypes([row],[elem],whereClause,mgens,null,unboxingDepth)};function checkPath(contains,ty){if(contains.length===0){return 0}const maxPathEditDistance=Math.floor(contains.reduce((acc,next)=>acc+next.length,0)/3,);let ret_dist=maxPathEditDistance+1;const path=ty.path.split("::");if(ty.parent&&ty.parent.name){path.push(ty.parent.name.toLowerCase())}const length=path.length;const clength=contains.length;pathiter:for(let i=length-clength;i>=0;i-=1){let dist_total=0;for(let x=0;xmaxPathEditDistance){continue pathiter}dist_total+=dist}}ret_dist=Math.min(ret_dist,Math.round(dist_total/clength))}return ret_dist>maxPathEditDistance?null:ret_dist}function typePassesFilter(filter,type){if(filter<=NO_TYPE_FILTER||filter===type)return true;const name=itemTypes[type];switch(itemTypes[filter]){case"constant":return name==="associatedconstant";case"fn":return name==="method"||name==="tymethod";case"type":return name==="primitive"||name==="associatedtype";case"trait":return name==="traitalias"}return false}function createAliasFromItem(item){return{crate:item.crate,name:item.name,path:item.path,descShard:item.descShard,descIndex:item.descIndex,exactPath:item.exactPath,ty:item.ty,parent:item.parent,type:item.type,is_alias:true,bitIndex:item.bitIndex,implDisambiguator:item.implDisambiguator,}}const handleAliases=async(ret,query,filterCrates,currentCrate)=>{const lowerQuery=query.toLowerCase();const aliases=[];const crateAliases=[];if(filterCrates!==null){if(this.ALIASES.has(filterCrates)&&this.ALIASES.get(filterCrates).has(lowerQuery)){const query_aliases=this.ALIASES.get(filterCrates).get(lowerQuery);for(const alias of query_aliases){aliases.push(createAliasFromItem(this.searchIndex[alias]))}}}else{for(const[crate,crateAliasesIndex]of this.ALIASES){if(crateAliasesIndex.has(lowerQuery)){const pushTo=crate===currentCrate?crateAliases:aliases;const query_aliases=crateAliasesIndex.get(lowerQuery);for(const alias of query_aliases){pushTo.push(createAliasFromItem(this.searchIndex[alias]))}}}}const sortFunc=(aaa,bbb)=>{if(aaa.path{return this.searchIndexEmptyDesc.get(alias.crate).contains(alias.bitIndex)?"":this.searchState.loadDesc(alias)};const[crateDescs,descs]=await Promise.all([Promise.all(crateAliases.map(fetchDesc)),Promise.all(aliases.map(fetchDesc)),]);const pushFunc=alias=>{alias.alias=query;const res=buildHrefAndPath(alias);alias.displayPath=pathSplitter(res[0]);alias.fullPath=alias.displayPath+alias.name;alias.href=res[1];ret.others.unshift(alias);if(ret.others.length>MAX_RESULTS){ret.others.pop()}};aliases.forEach((alias,i)=>{alias.desc=descs[i]});aliases.forEach(pushFunc);crateAliases.forEach((alias,i)=>{alias.desc=crateDescs[i]});crateAliases.forEach(pushFunc)};function addIntoResults(results,fullId,id,index,dist,path_dist,maxEditDistance){if(dist<=maxEditDistance||index!==-1){if(results.has(fullId)){const result=results.get(fullId);if(result.dontValidate||result.dist<=dist){return}}results.set(fullId,{id:id,index:index,dontValidate:parsedQuery.literalSearch,dist:dist,path_dist:path_dist,})}}function handleSingleArg(row,pos,elem,results_others,results_in_args,results_returned,maxEditDistance,){if(!row||(filterCrates!==null&&row.crate!==filterCrates)){return}let path_dist=0;const fullId=row.id;const tfpDist=compareTypeFingerprints(fullId,parsedQuery.typeFingerprint,);if(tfpDist!==null){const in_args=row.type&&row.type.inputs&&checkIfInList(row.type.inputs,elem,row.type.where_clause,null,0);const returned=row.type&&row.type.output&&checkIfInList(row.type.output,elem,row.type.where_clause,null,0);if(in_args){results_in_args.max_dist=Math.max(results_in_args.max_dist||0,tfpDist);const maxDist=results_in_args.sizenormalizedIndex&&normalizedIndex!==-1)){index=normalizedIndex}if(elem.fullPath.length>1){path_dist=checkPath(elem.pathWithoutLast,row);if(path_dist===null){return}}if(parsedQuery.literalSearch){if(row.word===elem.pathLast){addIntoResults(results_others,fullId,pos,index,0,path_dist)}return}const dist=editDistance(row.normalizedName,elem.normalizedPathLast,maxEditDistance);if(index===-1&&dist>maxEditDistance){return}addIntoResults(results_others,fullId,pos,index,dist,path_dist,maxEditDistance)}function handleArgs(row,pos,results){if(!row||(filterCrates!==null&&row.crate!==filterCrates)||!row.type){return}const tfpDist=compareTypeFingerprints(row.id,parsedQuery.typeFingerprint,);if(tfpDist===null){return}if(results.size>=MAX_RESULTS&&tfpDist>results.max_dist){return}if(!unifyFunctionTypes(row.type.inputs,parsedQuery.elems,row.type.where_clause,null,mgens=>{return unifyFunctionTypes(row.type.output,parsedQuery.returned,row.type.where_clause,mgens,null,0,)},0,)){return}results.max_dist=Math.max(results.max_dist||0,tfpDist);addIntoResults(results,row.id,pos,0,tfpDist,0,Number.MAX_VALUE)}const compareTypeFingerprints=(fullId,queryFingerprint)=>{const fh0=this.functionTypeFingerprint[fullId*4];const fh1=this.functionTypeFingerprint[(fullId*4)+1];const fh2=this.functionTypeFingerprint[(fullId*4)+2];const[qh0,qh1,qh2]=queryFingerprint;const[in0,in1,in2]=[fh0&qh0,fh1&qh1,fh2&qh2];if((in0 ^ qh0)||(in1 ^ qh1)||(in2 ^ qh2)){return null}return this.functionTypeFingerprint[(fullId*4)+3]};const innerRunQuery=()=>{const queryLen=parsedQuery.elems.reduce((acc,next)=>acc+next.pathLast.length,0)+parsedQuery.returned.reduce((acc,next)=>acc+next.pathLast.length,0);const maxEditDistance=Math.floor(queryLen/3);const genericSymbols=new Map();const convertNameToId=(elem,isAssocType)=>{const loweredName=elem.pathLast.toLowerCase();if(this.typeNameIdMap.has(loweredName)&&(isAssocType||!this.typeNameIdMap.get(loweredName).assocOnly)){elem.id=this.typeNameIdMap.get(loweredName).id}else if(!parsedQuery.literalSearch){let match=null;let matchDist=maxEditDistance+1;let matchName="";for(const[name,{id,assocOnly}]of this.typeNameIdMap){const dist=Math.min(editDistance(name,loweredName,maxEditDistance),editDistance(name,elem.normalizedPathLast,maxEditDistance),);if(dist<=matchDist&&dist<=maxEditDistance&&(isAssocType||!assocOnly)){if(dist===matchDist&&matchName>name){continue}match=id;matchDist=dist;matchName=name}}if(match!==null){parsedQuery.correction=matchName}elem.id=match}if((elem.id===null&&parsedQuery.totalElems>1&&elem.typeFilter===-1&&elem.generics.length===0&&elem.bindings.size===0)||elem.typeFilter===TY_GENERIC){if(genericSymbols.has(elem.name)){elem.id=genericSymbols.get(elem.name)}else{elem.id=-(genericSymbols.size+1);genericSymbols.set(elem.name,elem.id)}if(elem.typeFilter===-1&&elem.name.length>=3){const maxPartDistance=Math.floor(elem.name.length/3);let matchDist=maxPartDistance+1;let matchName="";for(const name of this.typeNameIdMap.keys()){const dist=editDistance(name,elem.name,maxPartDistance);if(dist<=matchDist&&dist<=maxPartDistance){if(dist===matchDist&&matchName>name){continue}matchDist=dist;matchName=name}}if(matchName!==""){parsedQuery.proposeCorrectionFrom=elem.name;parsedQuery.proposeCorrectionTo=matchName}}elem.typeFilter=TY_GENERIC}if(elem.generics.length>0&&elem.typeFilter===TY_GENERIC){parsedQuery.error=["Generic type parameter ",elem.name," does not accept generic parameters",]}for(const elem2 of elem.generics){convertNameToId(elem2)}elem.bindings=new Map(Array.from(elem.bindings.entries()).map(entry=>{const[name,constraints]=entry;if(!this.typeNameIdMap.has(name)){parsedQuery.error=["Type parameter ",name," does not exist",];return[null,[]]}for(const elem2 of constraints){convertNameToId(elem2)}return[this.typeNameIdMap.get(name).id,constraints]}),)};const fps=new Set();for(const elem of parsedQuery.elems){convertNameToId(elem);this.buildFunctionTypeFingerprint(elem,parsedQuery.typeFingerprint,fps)}for(const elem of parsedQuery.returned){convertNameToId(elem);this.buildFunctionTypeFingerprint(elem,parsedQuery.typeFingerprint,fps)}if(parsedQuery.foundElems===1&&!parsedQuery.hasReturnArrow){if(parsedQuery.elems.length===1){const elem=parsedQuery.elems[0];const length=this.searchIndex.length;for(let i=0,nSearchIndex=length;i0){const sortQ=(a,b)=>{const ag=a.generics.length===0&&a.bindings.size===0;const bg=b.generics.length===0&&b.bindings.size===0;if(ag!==bg){return ag-bg}const ai=a.id>0;const bi=b.id>0;return ai-bi};parsedQuery.elems.sort(sortQ);parsedQuery.returned.sort(sortQ);for(let i=0,nSearchIndex=this.searchIndex.length;i{const descs=await Promise.all(list.map(result=>{return this.searchIndexEmptyDesc.get(result.crate).contains(result.bitIndex)?"":this.searchState.loadDesc(result)}));for(const[i,result]of list.entries()){result.desc=descs[i]}}));if(parsedQuery.error!==null&&ret.others.length!==0){ret.query.error=null}return ret}}let rawSearchIndex;let docSearch;const longItemTypes=["keyword","primitive type","module","extern crate","re-export","struct","enum","function","type alias","static","trait","","trait method","method","struct field","enum variant","macro","assoc type","constant","assoc const","union","foreign type","existential type","attribute macro","derive macro","trait alias",];let currentResults;function printTab(nb){let iter=0;let foundCurrentTab=false;let foundCurrentResultSet=false;onEachLazy(document.getElementById("search-tabs").childNodes,elem=>{if(nb===iter){addClass(elem,"selected");foundCurrentTab=true}else{removeClass(elem,"selected")}iter+=1});const isTypeSearch=(nb>0||iter===1);iter=0;onEachLazy(document.getElementById("results").childNodes,elem=>{if(nb===iter){addClass(elem,"active");foundCurrentResultSet=true}else{removeClass(elem,"active")}iter+=1});if(foundCurrentTab&&foundCurrentResultSet){searchState.currentTab=nb;const correctionsElem=document.getElementsByClassName("search-corrections");if(isTypeSearch){removeClass(correctionsElem[0],"hidden")}else{addClass(correctionsElem[0],"hidden")}}else if(nb!==0){printTab(0)}}function buildUrl(search,filterCrates){let extra="?search="+encodeURIComponent(search);if(filterCrates!==null){extra+="&filter-crate="+encodeURIComponent(filterCrates)}return getNakedUrl()+extra+window.location.hash}function getFilterCrates(){const elem=document.getElementById("crate-search");if(elem&&elem.value!=="all crates"&&window.searchIndex.has(elem.value)){return elem.value}return null}function nextTab(direction){const next=(searchState.currentTab+direction+3)%searchState.focusedByTab.length;searchState.focusedByTab[searchState.currentTab]=document.activeElement;printTab(next);focusSearchResult()}function focusSearchResult(){const target=searchState.focusedByTab[searchState.currentTab]||document.querySelectorAll(".search-results.active a").item(0)||document.querySelectorAll("#search-tabs button").item(searchState.currentTab);searchState.focusedByTab[searchState.currentTab]=null;if(target){target.focus()}}async function addTab(array,query,display){const extraClass=display?" active":"";const output=document.createElement("div");if(array.length>0){output.className="search-results "+extraClass;for(const item of array){const name=item.name;const type=itemTypes[item.ty];const longType=longItemTypes[item.ty];const typeName=longType.length!==0?`${longType}`:"?";const link=document.createElement("a");link.className="result-"+type;link.href=item.href;const resultName=document.createElement("div");resultName.className="result-name";resultName.insertAdjacentHTML("beforeend",`${typeName}`);link.appendChild(resultName);let alias=" ";if(item.is_alias){alias=`
\ +${item.alias} - see \ +
`}resultName.insertAdjacentHTML("beforeend",`
${alias}\ +${item.displayPath}${name}\ +
`);const description=document.createElement("div");description.className="desc";description.insertAdjacentHTML("beforeend",item.desc);link.appendChild(description);output.appendChild(link)}}else if(query.error===null){output.className="search-failed"+extraClass;output.innerHTML="No results :(
"+"Try on DuckDuckGo?

"+"Or try looking in one of these:"}return[output,array.length]}function makeTabHeader(tabNb,text,nbElems){const fmtNbElems=nbElems<10?`\u{2007}(${nbElems})\u{2007}\u{2007}`:nbElems<100?`\u{2007}(${nbElems})\u{2007}`:`\u{2007}(${nbElems})`;if(searchState.currentTab===tabNb){return""}return""}async function showResults(results,go_to_first,filterCrates){const search=searchState.outputElement();if(go_to_first||(results.others.length===1&&getSettingValue("go-to-only-result")==="true")){window.onunload=()=>{};searchState.removeQueryParameters();const elem=document.createElement("a");elem.href=results.others[0].href;removeClass(elem,"active");document.body.appendChild(elem);elem.click();return}if(results.query===undefined){results.query=DocSearch.parseQuery(searchState.input.value)}currentResults=results.query.userQuery;const[ret_others,ret_in_args,ret_returned]=await Promise.all([addTab(results.others,results.query,true),addTab(results.in_args,results.query,false),addTab(results.returned,results.query,false),]);let currentTab=searchState.currentTab;if((currentTab===0&&ret_others[1]===0)||(currentTab===1&&ret_in_args[1]===0)||(currentTab===2&&ret_returned[1]===0)){if(ret_others[1]!==0){currentTab=0}else if(ret_in_args[1]!==0){currentTab=1}else if(ret_returned[1]!==0){currentTab=2}}let crates="";if(rawSearchIndex.size>1){crates="
in 
"+"
"}let output=`
\ +

Results

${crates}
`;if(results.query.error!==null){const error=results.query.error;error.forEach((value,index)=>{value=value.split("<").join("<").split(">").join(">");if(index%2!==0){error[index]=`${value.replaceAll(" ", " ")}`}else{error[index]=value}});output+=`

Query parser error: "${error.join("")}".

`;output+="
"+makeTabHeader(0,"In Names",ret_others[1])+"
";currentTab=0}else if(results.query.foundElems<=1&&results.query.returned.length===0){output+="
"+makeTabHeader(0,"In Names",ret_others[1])+makeTabHeader(1,"In Parameters",ret_in_args[1])+makeTabHeader(2,"In Return Types",ret_returned[1])+"
"}else{const signatureTabTitle=results.query.elems.length===0?"In Function Return Types":results.query.returned.length===0?"In Function Parameters":"In Function Signatures";output+="
"+makeTabHeader(0,signatureTabTitle,ret_others[1])+"
";currentTab=0}if(results.query.correction!==null){const orig=results.query.returned.length>0?results.query.returned[0].name:results.query.elems[0].name;output+="

"+`Type "${orig}" not found. `+"Showing results for closest type name "+`"${results.query.correction}" instead.

`}if(results.query.proposeCorrectionFrom!==null){const orig=results.query.proposeCorrectionFrom;const targ=results.query.proposeCorrectionTo;output+="

"+`Type "${orig}" not found and used as generic parameter. `+`Consider searching for "${targ}" instead.

`}const resultsElem=document.createElement("div");resultsElem.id="results";resultsElem.appendChild(ret_others[0]);resultsElem.appendChild(ret_in_args[0]);resultsElem.appendChild(ret_returned[0]);search.innerHTML=output;if(searchState.rustdocToolbar){search.querySelector(".main-heading").appendChild(searchState.rustdocToolbar)}const crateSearch=document.getElementById("crate-search");if(crateSearch){crateSearch.addEventListener("input",updateCrate)}search.appendChild(resultsElem);searchState.showResults(search);const elems=document.getElementById("search-tabs").childNodes;searchState.focusedByTab=[];let i=0;for(const elem of elems){const j=i;elem.onclick=()=>printTab(j);searchState.focusedByTab.push(null);i+=1}printTab(currentTab)}function updateSearchHistory(url){if(!browserSupportsHistoryApi()){return}const params=searchState.getQueryStringParams();if(!history.state&&!params.search){history.pushState(null,"",url)}else{history.replaceState(null,"",url)}}async function search(forced){const query=DocSearch.parseQuery(searchState.input.value.trim());let filterCrates=getFilterCrates();if(!forced&&query.userQuery===currentResults){if(query.userQuery.length>0){putBackSearch()}return}searchState.setLoadingSearch();const params=searchState.getQueryStringParams();if(filterCrates===null&¶ms["filter-crate"]!==undefined){filterCrates=params["filter-crate"]}searchState.title="\""+query.original+"\" Search - Rust";updateSearchHistory(buildUrl(query.original,filterCrates));await showResults(await docSearch.execQuery(query,filterCrates,window.currentCrate),params.go_to_first,filterCrates)}function onSearchSubmit(e){e.preventDefault();searchState.clearInputTimeout();search()}function putBackSearch(){const search_input=searchState.input;if(!searchState.input){return}if(search_input.value!==""&&!searchState.isDisplayed()){searchState.showResults();if(browserSupportsHistoryApi()){history.replaceState(null,"",buildUrl(search_input.value,getFilterCrates()))}document.title=searchState.title}}function registerSearchEvents(){const params=searchState.getQueryStringParams();if(searchState.input.value===""){searchState.input.value=params.search||""}const searchAfter500ms=()=>{searchState.clearInputTimeout();if(searchState.input.value.length===0){searchState.hideResults()}else{searchState.timeout=setTimeout(search,500)}};searchState.input.onkeyup=searchAfter500ms;searchState.input.oninput=searchAfter500ms;document.getElementsByClassName("search-form")[0].onsubmit=onSearchSubmit;searchState.input.onchange=e=>{if(e.target!==document.activeElement){return}searchState.clearInputTimeout();setTimeout(search,0)};searchState.input.onpaste=searchState.input.onchange;searchState.outputElement().addEventListener("keydown",e=>{if(e.altKey||e.ctrlKey||e.shiftKey||e.metaKey){return}if(e.which===38){const previous=document.activeElement.previousElementSibling;if(previous){previous.focus()}else{searchState.focus()}e.preventDefault()}else if(e.which===40){const next=document.activeElement.nextElementSibling;if(next){next.focus()}const rect=document.activeElement.getBoundingClientRect();if(window.innerHeight-rect.bottom{if(e.which===40){focusSearchResult();e.preventDefault()}});searchState.input.addEventListener("focus",()=>{putBackSearch()});searchState.input.addEventListener("blur",()=>{searchState.input.placeholder=searchState.input.origPlaceholder});if(browserSupportsHistoryApi()){const previousTitle=document.title;window.addEventListener("popstate",e=>{const params=searchState.getQueryStringParams();document.title=previousTitle;currentResults=null;if(params.search&¶ms.search.length>0){searchState.input.value=params.search;e.preventDefault();search()}else{searchState.input.value="";searchState.hideResults()}})}window.onpageshow=()=>{const qSearch=searchState.getQueryStringParams().search;if(searchState.input.value===""&&qSearch){searchState.input.value=qSearch}search()}}function updateCrate(ev){if(ev.target.value==="all crates"){const query=searchState.input.value.trim();updateSearchHistory(buildUrl(query,null))}currentResults=null;search(true)}function initSearch(searchIndx){rawSearchIndex=searchIndx;if(typeof window!=="undefined"){docSearch=new DocSearch(rawSearchIndex,ROOT_PATH,searchState);registerSearchEvents();if(window.searchState.getQueryStringParams().search){search()}}else if(typeof exports!=="undefined"){docSearch=new DocSearch(rawSearchIndex,ROOT_PATH,searchState);exports.docSearch=docSearch;exports.parseQuery=DocSearch.parseQuery}}if(typeof exports!=="undefined"){exports.initSearch=initSearch}if(typeof window!=="undefined"){window.initSearch=initSearch;if(window.searchIndex!==undefined){initSearch(window.searchIndex)}}else{initSearch(new Map())}})() \ No newline at end of file diff --git a/static.files/settings-0f613d39.js b/static.files/settings-0f613d39.js new file mode 100644 index 000000000..4a30479d9 --- /dev/null +++ b/static.files/settings-0f613d39.js @@ -0,0 +1,17 @@ +"use strict";(function(){const isSettingsPage=window.location.pathname.endsWith("/settings.html");function changeSetting(settingName,value){if(settingName==="theme"){const useSystem=value==="system preference"?"true":"false";updateLocalStorage("use-system-theme",useSystem)}updateLocalStorage(settingName,value);switch(settingName){case"theme":case"preferred-dark-theme":case"preferred-light-theme":updateTheme();updateLightAndDark();break;case"line-numbers":if(value===true){window.rustdoc_add_line_numbers_to_examples()}else{window.rustdoc_remove_line_numbers_from_examples()}break;case"hide-sidebar":if(value===true){addClass(document.documentElement,"hide-sidebar")}else{removeClass(document.documentElement,"hide-sidebar")}break;case"hide-toc":if(value===true){addClass(document.documentElement,"hide-toc")}else{removeClass(document.documentElement,"hide-toc")}break;case"hide-modnav":if(value===true){addClass(document.documentElement,"hide-modnav")}else{removeClass(document.documentElement,"hide-modnav")}break}}function showLightAndDark(){removeClass(document.getElementById("preferred-light-theme"),"hidden");removeClass(document.getElementById("preferred-dark-theme"),"hidden")}function hideLightAndDark(){addClass(document.getElementById("preferred-light-theme"),"hidden");addClass(document.getElementById("preferred-dark-theme"),"hidden")}function updateLightAndDark(){const useSystem=getSettingValue("use-system-theme");if(useSystem==="true"||(useSystem===null&&getSettingValue("theme")===null)){showLightAndDark()}else{hideLightAndDark()}}function setEvents(settingsElement){updateLightAndDark();onEachLazy(settingsElement.querySelectorAll("input[type=\"checkbox\"]"),toggle=>{const settingId=toggle.id;const settingValue=getSettingValue(settingId);if(settingValue!==null){toggle.checked=settingValue==="true"}toggle.onchange=()=>{changeSetting(toggle.id,toggle.checked)}});onEachLazy(settingsElement.querySelectorAll("input[type=\"radio\"]"),elem=>{const settingId=elem.name;let settingValue=getSettingValue(settingId);if(settingId==="theme"){const useSystem=getSettingValue("use-system-theme");if(useSystem==="true"||settingValue===null){settingValue=useSystem==="false"?"light":"system preference"}}if(settingValue!==null&&settingValue!=="null"){elem.checked=settingValue===elem.value}elem.addEventListener("change",ev=>{changeSetting(ev.target.name,ev.target.value)})})}function buildSettingsPageSections(settings){let output="";for(const setting of settings){if(setting==="hr"){output+="
";continue}const js_data_name=setting["js_name"];const setting_name=setting["name"];if(setting["options"]!==undefined){output+=`\ +
+
${setting_name}
+
`;onEach(setting["options"],option=>{const checked=option===setting["default"]?" checked":"";const full=`${js_data_name}-${option.replace(/ /g,"-")}`;output+=`\ + `});output+=`\ +
+
`}else{const checked=setting["default"]===true?" checked":"";output+=`\ +
\ + \ +
`}}return output}function buildSettingsPage(){const theme_names=getVar("themes").split(",").filter(t=>t);theme_names.push("light","dark","ayu");const settings=[{"name":"Theme","js_name":"theme","default":"system preference","options":theme_names.concat("system preference"),},{"name":"Preferred light theme","js_name":"preferred-light-theme","default":"light","options":theme_names,},{"name":"Preferred dark theme","js_name":"preferred-dark-theme","default":"dark","options":theme_names,},{"name":"Auto-hide item contents for large items","js_name":"auto-hide-large-items","default":true,},{"name":"Auto-hide item methods' documentation","js_name":"auto-hide-method-docs","default":false,},{"name":"Auto-hide trait implementation documentation","js_name":"auto-hide-trait-implementations","default":false,},{"name":"Directly go to item in search if there is only one result","js_name":"go-to-only-result","default":false,},{"name":"Show line numbers on code examples","js_name":"line-numbers","default":false,},{"name":"Hide persistent navigation bar","js_name":"hide-sidebar","default":false,},{"name":"Hide table of contents","js_name":"hide-toc","default":false,},{"name":"Hide module navigation","js_name":"hide-modnav","default":false,},{"name":"Disable keyboard shortcuts","js_name":"disable-shortcuts","default":false,},];const elementKind=isSettingsPage?"section":"div";const innerHTML=`
${buildSettingsPageSections(settings)}
`;const el=document.createElement(elementKind);el.id="settings";if(!isSettingsPage){el.className="popover"}el.innerHTML=innerHTML;if(isSettingsPage){document.getElementById(MAIN_ID).appendChild(el)}else{el.setAttribute("tabindex","-1");getSettingsButton().appendChild(el)}return el}const settingsMenu=buildSettingsPage();function displaySettings(){settingsMenu.style.display="";onEachLazy(settingsMenu.querySelectorAll("input[type='checkbox']"),el=>{const val=getSettingValue(el.id);const checked=val==="true";if(checked!==el.checked&&val!==null){el.checked=checked}})}function settingsBlurHandler(event){if(!getHelpButton().contains(document.activeElement)&&!getHelpButton().contains(event.relatedTarget)&&!getSettingsButton().contains(document.activeElement)&&!getSettingsButton().contains(event.relatedTarget)){window.hidePopoverMenus()}}if(!isSettingsPage){const settingsButton=getSettingsButton();const settingsMenu=document.getElementById("settings");settingsButton.onclick=event=>{if(settingsMenu.contains(event.target)){return}event.preventDefault();const shouldDisplaySettings=settingsMenu.style.display==="none";window.hideAllModals();if(shouldDisplaySettings){displaySettings()}};settingsButton.onblur=settingsBlurHandler;settingsButton.querySelector("a").onblur=settingsBlurHandler;onEachLazy(settingsMenu.querySelectorAll("input"),el=>{el.onblur=settingsBlurHandler});settingsMenu.onblur=settingsBlurHandler}setTimeout(()=>{setEvents(settingsMenu);if(!isSettingsPage){displaySettings()}removeClass(getSettingsButton(),"rotate")},0)})() \ No newline at end of file diff --git a/static.files/src-script-56102188.js b/static.files/src-script-56102188.js new file mode 100644 index 000000000..d0aebb851 --- /dev/null +++ b/static.files/src-script-56102188.js @@ -0,0 +1 @@ +"use strict";(function(){const rootPath=getVar("root-path");const NAME_OFFSET=0;const DIRS_OFFSET=1;const FILES_OFFSET=2;const RUSTDOC_MOBILE_BREAKPOINT=700;function closeSidebarIfMobile(){if(window.innerWidth{removeClass(document.documentElement,"src-sidebar-expanded");updateLocalStorage("source-sidebar-show","false")};window.rustdocShowSourceSidebar=()=>{addClass(document.documentElement,"src-sidebar-expanded");updateLocalStorage("source-sidebar-show","true")};window.rustdocToggleSrcSidebar=()=>{if(document.documentElement.classList.contains("src-sidebar-expanded")){window.rustdocCloseSourceSidebar()}else{window.rustdocShowSourceSidebar()}};function createSrcSidebar(){const container=document.querySelector("nav.sidebar");const sidebar=document.createElement("div");sidebar.id="src-sidebar";let hasFoundFile=false;for(const[key,source]of srcIndex){source[NAME_OFFSET]=key;hasFoundFile=createDirEntry(source,sidebar,"",hasFoundFile)}container.appendChild(sidebar);const selected_elem=sidebar.getElementsByClassName("selected")[0];if(typeof selected_elem!=="undefined"){selected_elem.focus()}}function highlightSrcLines(){const match=window.location.hash.match(/^#?(\d+)(?:-(\d+))?$/);if(!match){return}let from=parseInt(match[1],10);let to=from;if(typeof match[2]!=="undefined"){to=parseInt(match[2],10)}if(to{onEachLazy(e.getElementsByTagName("a"),i_e=>{removeClass(i_e,"line-highlighted")})});for(let i=from;i<=to;++i){elem=document.getElementById(i);if(!elem){break}addClass(elem,"line-highlighted")}}const handleSrcHighlight=(function(){let prev_line_id=0;const set_fragment=name=>{const x=window.scrollX,y=window.scrollY;if(browserSupportsHistoryApi()){history.replaceState(null,null,"#"+name);highlightSrcLines()}else{location.replace("#"+name)}window.scrollTo(x,y)};return ev=>{let cur_line_id=parseInt(ev.target.id,10);if(isNaN(cur_line_id)||ev.ctrlKey||ev.altKey||ev.metaKey){return}ev.preventDefault();if(ev.shiftKey&&prev_line_id){if(prev_line_id>cur_line_id){const tmp=prev_line_id;prev_line_id=cur_line_id;cur_line_id=tmp}set_fragment(prev_line_id+"-"+cur_line_id)}else{prev_line_id=cur_line_id;set_fragment(cur_line_id)}}}());window.addEventListener("hashchange",highlightSrcLines);onEachLazy(document.getElementsByClassName("src-line-numbers"),el=>{el.addEventListener("click",handleSrcHighlight)});highlightSrcLines();window.createSrcSidebar=createSrcSidebar})() \ No newline at end of file diff --git a/static.files/storage-59e33391.js b/static.files/storage-59e33391.js new file mode 100644 index 000000000..5aac776b4 --- /dev/null +++ b/static.files/storage-59e33391.js @@ -0,0 +1,23 @@ +"use strict";const builtinThemes=["light","dark","ayu"];const darkThemes=["dark","ayu"];window.currentTheme=document.getElementById("themeStyle");const settingsDataset=(function(){const settingsElement=document.getElementById("default-settings");return settingsElement&&settingsElement.dataset?settingsElement.dataset:null})();function getSettingValue(settingName){const current=getCurrentValue(settingName);if(current===null&&settingsDataset!==null){const def=settingsDataset[settingName.replace(/-/g,"_")];if(def!==undefined){return def}}return current}const localStoredTheme=getSettingValue("theme");function hasClass(elem,className){return elem&&elem.classList&&elem.classList.contains(className)}function addClass(elem,className){if(elem&&elem.classList){elem.classList.add(className)}}function removeClass(elem,className){if(elem&&elem.classList){elem.classList.remove(className)}}function onEach(arr,func){for(const elem of arr){if(func(elem)){return true}}return false}function onEachLazy(lazyArray,func){return onEach(Array.prototype.slice.call(lazyArray),func)}function updateLocalStorage(name,value){try{window.localStorage.setItem("rustdoc-"+name,value)}catch(e){}}function getCurrentValue(name){try{return window.localStorage.getItem("rustdoc-"+name)}catch(e){return null}}const getVar=(function getVar(name){const el=document.querySelector("head > meta[name='rustdoc-vars']");return el?el.attributes["data-"+name].value:null});function switchTheme(newThemeName,saveTheme){const themeNames=getVar("themes").split(",").filter(t=>t);themeNames.push(...builtinThemes);if(themeNames.indexOf(newThemeName)===-1){return}if(saveTheme){updateLocalStorage("theme",newThemeName)}document.documentElement.setAttribute("data-theme",newThemeName);if(builtinThemes.indexOf(newThemeName)!==-1){if(window.currentTheme){window.currentTheme.parentNode.removeChild(window.currentTheme);window.currentTheme=null}}else{const newHref=getVar("root-path")+encodeURIComponent(newThemeName)+getVar("resource-suffix")+".css";if(!window.currentTheme){if(document.readyState==="loading"){document.write(``);window.currentTheme=document.getElementById("themeStyle")}else{window.currentTheme=document.createElement("link");window.currentTheme.rel="stylesheet";window.currentTheme.id="themeStyle";window.currentTheme.href=newHref;document.documentElement.appendChild(window.currentTheme)}}else if(newHref!==window.currentTheme.href){window.currentTheme.href=newHref}}}const updateTheme=(function(){const mql=window.matchMedia("(prefers-color-scheme: dark)");function updateTheme(){if(getSettingValue("use-system-theme")!=="false"){const lightTheme=getSettingValue("preferred-light-theme")||"light";const darkTheme=getSettingValue("preferred-dark-theme")||"dark";updateLocalStorage("use-system-theme","true");switchTheme(mql.matches?darkTheme:lightTheme,true)}else{switchTheme(getSettingValue("theme"),false)}}mql.addEventListener("change",updateTheme);return updateTheme})();if(getSettingValue("use-system-theme")!=="false"&&window.matchMedia){if(getSettingValue("use-system-theme")===null&&getSettingValue("preferred-dark-theme")===null&&darkThemes.indexOf(localStoredTheme)>=0){updateLocalStorage("preferred-dark-theme",localStoredTheme)}}updateTheme();if(getSettingValue("source-sidebar-show")==="true"){addClass(document.documentElement,"src-sidebar-expanded")}if(getSettingValue("hide-sidebar")==="true"){addClass(document.documentElement,"hide-sidebar")}if(getSettingValue("hide-toc")==="true"){addClass(document.documentElement,"hide-toc")}if(getSettingValue("hide-modnav")==="true"){addClass(document.documentElement,"hide-modnav")}function updateSidebarWidth(){const desktopSidebarWidth=getSettingValue("desktop-sidebar-width");if(desktopSidebarWidth&&desktopSidebarWidth!=="null"){document.documentElement.style.setProperty("--desktop-sidebar-width",desktopSidebarWidth+"px",)}const srcSidebarWidth=getSettingValue("src-sidebar-width");if(srcSidebarWidth&&srcSidebarWidth!=="null"){document.documentElement.style.setProperty("--src-sidebar-width",srcSidebarWidth+"px",)}}updateSidebarWidth();window.addEventListener("pageshow",ev=>{if(ev.persisted){setTimeout(updateTheme,0);setTimeout(updateSidebarWidth,0)}});class RustdocSearchElement extends HTMLElement{constructor(){super()}connectedCallback(){const rootPath=getVar("root-path");const currentCrate=getVar("current-crate");this.innerHTML=``}}window.customElements.define("rustdoc-search",RustdocSearchElement);class RustdocToolbarElement extends HTMLElement{constructor(){super()}connectedCallback(){if(this.firstElementChild){return}const rootPath=getVar("root-path");this.innerHTML=` +
+ Settings +
+
+ Help +
+ `}}window.customElements.define("rustdoc-toolbar",RustdocToolbarElement) \ No newline at end of file diff --git a/trait.impl/core/clone/trait.Clone.js b/trait.impl/core/clone/trait.Clone.js new file mode 100644 index 000000000..cb7b1ddd4 --- /dev/null +++ b/trait.impl/core/clone/trait.Clone.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["rand_core",[["impl<R: Clone + BlockRngCore + ?Sized> Clone for BlockRng<R>
where\n R::Results: Clone,
"],["impl<R: Clone + BlockRngCore + ?Sized> Clone for BlockRng64<R>
where\n R::Results: Clone,
"]]],["rand_mt",[["impl Clone for RecoverRngError"],["impl Clone for Mt19937GenRand32"],["impl Clone for Mt19937GenRand64"]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[2107,839]} \ No newline at end of file diff --git a/trait.impl/core/cmp/trait.Eq.js b/trait.impl/core/cmp/trait.Eq.js new file mode 100644 index 000000000..591a25a0e --- /dev/null +++ b/trait.impl/core/cmp/trait.Eq.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["rand_mt",[["impl Eq for RecoverRngError"],["impl Eq for Mt19937GenRand32"],["impl Eq for Mt19937GenRand64"]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[799]} \ No newline at end of file diff --git a/trait.impl/core/cmp/trait.Ord.js b/trait.impl/core/cmp/trait.Ord.js new file mode 100644 index 000000000..d9ee0288d --- /dev/null +++ b/trait.impl/core/cmp/trait.Ord.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["rand_mt",[["impl Ord for Mt19937GenRand32"],["impl Ord for Mt19937GenRand64"]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[549]} \ No newline at end of file diff --git a/trait.impl/core/cmp/trait.PartialEq.js b/trait.impl/core/cmp/trait.PartialEq.js new file mode 100644 index 000000000..1d076f2e9 --- /dev/null +++ b/trait.impl/core/cmp/trait.PartialEq.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["rand_mt",[["impl PartialEq for RecoverRngError"],["impl PartialEq for Mt19937GenRand32"],["impl PartialEq for Mt19937GenRand64"]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[862]} \ No newline at end of file diff --git a/trait.impl/core/cmp/trait.PartialOrd.js b/trait.impl/core/cmp/trait.PartialOrd.js new file mode 100644 index 000000000..eeccdb6f9 --- /dev/null +++ b/trait.impl/core/cmp/trait.PartialOrd.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["rand_mt",[["impl PartialOrd for Mt19937GenRand32"],["impl PartialOrd for Mt19937GenRand64"]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[591]} \ No newline at end of file diff --git a/trait.impl/core/convert/trait.From.js b/trait.impl/core/convert/trait.From.js new file mode 100644 index 000000000..4186f06e4 --- /dev/null +++ b/trait.impl/core/convert/trait.From.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["rand_core",[["impl From<NonZero<u32>> for Error"]]],["rand_mt",[["impl From<u32> for Mt19937GenRand32"],["impl From<u64> for Mt19937GenRand64"],["impl From<[u32; 624]> for Mt19937GenRand32"],["impl From<[u64; 312]> for Mt19937GenRand64"],["impl From<[u8; 4]> for Mt19937GenRand32"],["impl From<[u8; 8]> for Mt19937GenRand64"]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[534,2712]} \ No newline at end of file diff --git a/trait.impl/core/convert/trait.TryFrom.js b/trait.impl/core/convert/trait.TryFrom.js new file mode 100644 index 000000000..b9ed25488 --- /dev/null +++ b/trait.impl/core/convert/trait.TryFrom.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["rand_mt",[["impl TryFrom<&[u32]> for Mt19937GenRand32"],["impl TryFrom<&[u64]> for Mt19937GenRand64"]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[811]} \ No newline at end of file diff --git a/trait.impl/core/default/trait.Default.js b/trait.impl/core/default/trait.Default.js new file mode 100644 index 000000000..7dd1c8b5e --- /dev/null +++ b/trait.impl/core/default/trait.Default.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["rand_mt",[["impl Default for Mt19937GenRand32"],["impl Default for Mt19937GenRand64"]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[589]} \ No newline at end of file diff --git a/trait.impl/core/error/trait.Error.js b/trait.impl/core/error/trait.Error.js new file mode 100644 index 000000000..7ecdfba70 --- /dev/null +++ b/trait.impl/core/error/trait.Error.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["rand_mt",[["impl Error for RecoverRngError"]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[282]} \ No newline at end of file diff --git a/trait.impl/core/fmt/trait.Debug.js b/trait.impl/core/fmt/trait.Debug.js new file mode 100644 index 000000000..398c7bd16 --- /dev/null +++ b/trait.impl/core/fmt/trait.Debug.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["rand_core",[["impl Debug for Error"],["impl<R: BlockRngCore + Debug> Debug for BlockRng<R>"],["impl<R: BlockRngCore + Debug> Debug for BlockRng64<R>"]]],["rand_mt",[["impl Debug for RecoverRngError"],["impl Debug for Mt19937GenRand32"],["impl Debug for Mt19937GenRand64"]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[1368,827]} \ No newline at end of file diff --git a/trait.impl/core/fmt/trait.Display.js b/trait.impl/core/fmt/trait.Display.js new file mode 100644 index 000000000..9304600f8 --- /dev/null +++ b/trait.impl/core/fmt/trait.Display.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["rand_core",[["impl Display for Error"]]],["rand_mt",[["impl Display for RecoverRngError"]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[266,285]} \ No newline at end of file diff --git a/trait.impl/core/hash/trait.Hash.js b/trait.impl/core/hash/trait.Hash.js new file mode 100644 index 000000000..6a49372ab --- /dev/null +++ b/trait.impl/core/hash/trait.Hash.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["rand_mt",[["impl Hash for RecoverRngError"],["impl Hash for Mt19937GenRand32"],["impl Hash for Mt19937GenRand64"]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[823]} \ No newline at end of file diff --git a/trait.impl/core/marker/trait.Copy.js b/trait.impl/core/marker/trait.Copy.js new file mode 100644 index 000000000..9c1a1d026 --- /dev/null +++ b/trait.impl/core/marker/trait.Copy.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["rand_mt",[["impl Copy for RecoverRngError"]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[281]} \ No newline at end of file diff --git a/trait.impl/core/marker/trait.Freeze.js b/trait.impl/core/marker/trait.Freeze.js new file mode 100644 index 000000000..792d05153 --- /dev/null +++ b/trait.impl/core/marker/trait.Freeze.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["rand_core",[["impl Freeze for Error",1,["rand_core::error::Error"]],["impl<R> Freeze for BlockRng<R>
where\n <R as BlockRngCore>::Results: Freeze,\n R: Freeze + ?Sized,
",1,["rand_core::block::BlockRng"]],["impl<R> Freeze for BlockRng64<R>
where\n <R as BlockRngCore>::Results: Freeze,\n R: Freeze + ?Sized,
",1,["rand_core::block::BlockRng64"]]]],["rand_mt",[["impl Freeze for RecoverRngError",1,["rand_mt::RecoverRngError"]],["impl Freeze for Mt19937GenRand32",1,["rand_mt::mt::Mt19937GenRand32"]],["impl Freeze for Mt19937GenRand64",1,["rand_mt::mt64::Mt19937GenRand64"]]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[2523,959]} \ No newline at end of file diff --git a/trait.impl/core/marker/trait.Send.js b/trait.impl/core/marker/trait.Send.js new file mode 100644 index 000000000..19fc6c8bd --- /dev/null +++ b/trait.impl/core/marker/trait.Send.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["rand_core",[["impl Send for Error",1,["rand_core::error::Error"]],["impl<R> Send for BlockRng<R>
where\n <R as BlockRngCore>::Results: Send,\n R: Send + ?Sized,
",1,["rand_core::block::BlockRng"]],["impl<R> Send for BlockRng64<R>
where\n <R as BlockRngCore>::Results: Send,\n R: Send + ?Sized,
",1,["rand_core::block::BlockRng64"]]]],["rand_mt",[["impl Send for RecoverRngError",1,["rand_mt::RecoverRngError"]],["impl Send for Mt19937GenRand32",1,["rand_mt::mt::Mt19937GenRand32"]],["impl Send for Mt19937GenRand64",1,["rand_mt::mt64::Mt19937GenRand64"]]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[2481,941]} \ No newline at end of file diff --git a/trait.impl/core/marker/trait.StructuralPartialEq.js b/trait.impl/core/marker/trait.StructuralPartialEq.js new file mode 100644 index 000000000..29085cf57 --- /dev/null +++ b/trait.impl/core/marker/trait.StructuralPartialEq.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["rand_mt",[["impl StructuralPartialEq for RecoverRngError"],["impl StructuralPartialEq for Mt19937GenRand32"],["impl StructuralPartialEq for Mt19937GenRand64"]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[970]} \ No newline at end of file diff --git a/trait.impl/core/marker/trait.Sync.js b/trait.impl/core/marker/trait.Sync.js new file mode 100644 index 000000000..24e332fcb --- /dev/null +++ b/trait.impl/core/marker/trait.Sync.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["rand_core",[["impl Sync for Error",1,["rand_core::error::Error"]],["impl<R> Sync for BlockRng<R>
where\n <R as BlockRngCore>::Results: Sync,\n R: Sync + ?Sized,
",1,["rand_core::block::BlockRng"]],["impl<R> Sync for BlockRng64<R>
where\n <R as BlockRngCore>::Results: Sync,\n R: Sync + ?Sized,
",1,["rand_core::block::BlockRng64"]]]],["rand_mt",[["impl Sync for RecoverRngError",1,["rand_mt::RecoverRngError"]],["impl Sync for Mt19937GenRand32",1,["rand_mt::mt::Mt19937GenRand32"]],["impl Sync for Mt19937GenRand64",1,["rand_mt::mt64::Mt19937GenRand64"]]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[2481,941]} \ No newline at end of file diff --git a/trait.impl/core/marker/trait.Unpin.js b/trait.impl/core/marker/trait.Unpin.js new file mode 100644 index 000000000..9e9fe1c0f --- /dev/null +++ b/trait.impl/core/marker/trait.Unpin.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["rand_core",[["impl Unpin for Error",1,["rand_core::error::Error"]],["impl<R> Unpin for BlockRng<R>
where\n <R as BlockRngCore>::Results: Unpin,\n R: Unpin + ?Sized,
",1,["rand_core::block::BlockRng"]],["impl<R> Unpin for BlockRng64<R>
where\n <R as BlockRngCore>::Results: Unpin,\n R: Unpin + ?Sized,
",1,["rand_core::block::BlockRng64"]]]],["rand_mt",[["impl Unpin for RecoverRngError",1,["rand_mt::RecoverRngError"]],["impl Unpin for Mt19937GenRand32",1,["rand_mt::mt::Mt19937GenRand32"]],["impl Unpin for Mt19937GenRand64",1,["rand_mt::mt64::Mt19937GenRand64"]]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[2502,950]} \ No newline at end of file diff --git a/trait.impl/core/panic/unwind_safe/trait.RefUnwindSafe.js b/trait.impl/core/panic/unwind_safe/trait.RefUnwindSafe.js new file mode 100644 index 000000000..0a5a41a42 --- /dev/null +++ b/trait.impl/core/panic/unwind_safe/trait.RefUnwindSafe.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["rand_core",[["impl RefUnwindSafe for Error",1,["rand_core::error::Error"]],["impl<R> RefUnwindSafe for BlockRng<R>",1,["rand_core::block::BlockRng"]],["impl<R> RefUnwindSafe for BlockRng64<R>",1,["rand_core::block::BlockRng64"]]]],["rand_mt",[["impl RefUnwindSafe for RecoverRngError",1,["rand_mt::RecoverRngError"]],["impl RefUnwindSafe for Mt19937GenRand32",1,["rand_mt::mt::Mt19937GenRand32"]],["impl RefUnwindSafe for Mt19937GenRand64",1,["rand_mt::mt64::Mt19937GenRand64"]]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[2831,1091]} \ No newline at end of file diff --git a/trait.impl/core/panic/unwind_safe/trait.UnwindSafe.js b/trait.impl/core/panic/unwind_safe/trait.UnwindSafe.js new file mode 100644 index 000000000..789df187c --- /dev/null +++ b/trait.impl/core/panic/unwind_safe/trait.UnwindSafe.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["rand_core",[["impl UnwindSafe for Error",1,["rand_core::error::Error"]],["impl<R> UnwindSafe for BlockRng<R>
where\n <R as BlockRngCore>::Results: UnwindSafe,\n R: UnwindSafe + ?Sized,
",1,["rand_core::block::BlockRng"]],["impl<R> UnwindSafe for BlockRng64<R>
where\n <R as BlockRngCore>::Results: UnwindSafe,\n R: UnwindSafe + ?Sized,
",1,["rand_core::block::BlockRng64"]]]],["rand_mt",[["impl UnwindSafe for RecoverRngError",1,["rand_mt::RecoverRngError"]],["impl UnwindSafe for Mt19937GenRand32",1,["rand_mt::mt::Mt19937GenRand32"]],["impl UnwindSafe for Mt19937GenRand64",1,["rand_mt::mt64::Mt19937GenRand64"]]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[2768,1064]} \ No newline at end of file diff --git a/trait.impl/rand_core/trait.CryptoRng.js b/trait.impl/rand_core/trait.CryptoRng.js new file mode 100644 index 000000000..76c45ff6d --- /dev/null +++ b/trait.impl/rand_core/trait.CryptoRng.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["rand_core",[]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[16]} \ No newline at end of file diff --git a/trait.impl/rand_core/trait.CryptoRngCore.js b/trait.impl/rand_core/trait.CryptoRngCore.js new file mode 100644 index 000000000..76c45ff6d --- /dev/null +++ b/trait.impl/rand_core/trait.CryptoRngCore.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["rand_core",[]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[16]} \ No newline at end of file diff --git a/trait.impl/rand_core/trait.RngCore.js b/trait.impl/rand_core/trait.RngCore.js new file mode 100644 index 000000000..97b4027e9 --- /dev/null +++ b/trait.impl/rand_core/trait.RngCore.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["rand_core",[]],["rand_mt",[["impl RngCore for Mt19937GenRand32"],["impl RngCore for Mt19937GenRand64"]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[16,508]} \ No newline at end of file diff --git a/trait.impl/rand_core/trait.SeedableRng.js b/trait.impl/rand_core/trait.SeedableRng.js new file mode 100644 index 000000000..56140fc98 --- /dev/null +++ b/trait.impl/rand_core/trait.SeedableRng.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["rand_core",[]],["rand_mt",[["impl SeedableRng for Mt19937GenRand32"],["impl SeedableRng for Mt19937GenRand64"]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[16,532]} \ No newline at end of file diff --git a/type.impl/rand_mt/struct.Mt19937GenRand32.js b/type.impl/rand_mt/struct.Mt19937GenRand32.js new file mode 100644 index 000000000..7e880c594 --- /dev/null +++ b/type.impl/rand_mt/struct.Mt19937GenRand32.js @@ -0,0 +1,9 @@ +(function() { + var type_impls = Object.fromEntries([["rand_mt",[["
source§

impl Clone for Mt19937GenRand32

source§

fn clone(&self) -> Mt19937GenRand32

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
","Clone","rand_mt::Mt"],["
source§

impl Debug for Mt19937GenRand32

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
","Debug","rand_mt::Mt"],["
source§

impl Default for Mt19937GenRand32

source§

fn default() -> Self

Return a new Mt19937GenRand32 with the default seed.

\n

Equivalent to calling Mt19937GenRand32::new_unseeded.

\n
","Default","rand_mt::Mt"],["
source§

impl From<[u32; 624]> for Mt19937GenRand32

source§

fn from(key: [u32; 624]) -> Self

Recover the internal state of a Mersenne Twister using the past 624\nsamples.

\n

This conversion takes a history of samples from a RNG and returns a\nRNG that will produce identical output to the RNG that supplied the\nsamples.

\n
","From<[u32; 624]>","rand_mt::Mt"],["
source§

impl From<[u8; 4]> for Mt19937GenRand32

source§

fn from(seed: [u8; 4]) -> Self

Construct a Mersenne Twister RNG from 4 bytes.

\n

The given bytes are treated as a little endian encoded u32.

\n
§Examples
\n
// Default MT seed\nlet seed = 5489_u32.to_le_bytes();\nlet mut mt = Mt19937GenRand32::from(seed);\nassert_ne!(mt.next_u32(), mt.next_u32());
\n

This constructor is equivalent to passing a little endian encoded u32.

\n\n
// Default MT seed\nlet seed = 5489_u32.to_le_bytes();\nlet mt1 = Mt19937GenRand32::from(seed);\nlet mt2 = Mt19937GenRand32::new(5489_u32);\nassert_eq!(mt1, mt2);
\n
","From<[u8; 4]>","rand_mt::Mt"],["
source§

impl From<u32> for Mt19937GenRand32

source§

fn from(seed: u32) -> Self

Construct a Mersenne Twister RNG from a u32 seed.

\n

This function is equivalent to new.

\n
§Examples
\n
// Default MT seed\nlet seed = 5489_u32;\nlet mt1 = Mt19937GenRand32::from(seed);\nlet mt2 = Mt19937GenRand32::new(seed);\nassert_eq!(mt1, mt2);\n\n// Non-default MT seed\nlet seed = 9927_u32;\nlet mt1 = Mt19937GenRand32::from(seed);\nlet mt2 = Mt19937GenRand32::new(seed);\nassert_eq!(mt1, mt2);
\n
","From","rand_mt::Mt"],["
source§

impl Hash for Mt19937GenRand32

source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where\n H: Hasher,\n Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
","Hash","rand_mt::Mt"],["
source§

impl Mt19937GenRand32

source

pub const DEFAULT_SEED: u32 = 5_489u32

Default seed used by Mt19937GenRand32::new_unseeded.

\n
source

pub fn new(seed: u32) -> Self

Create a new Mersenne Twister random number generator using the given\nseed.

\n
§Examples
§Constructing with a u32 seed
\n
let seed = 123_456_789_u32;\nlet mt1 = Mt19937GenRand32::new(seed);\nlet mt2 = Mt19937GenRand32::from(seed.to_le_bytes());\nassert_eq!(mt1, mt2);
\n
§Constructing with default seed
\n
let mt1 = Mt19937GenRand32::new(Mt19937GenRand32::DEFAULT_SEED);\nlet mt2 = Mt19937GenRand32::new_unseeded();\nassert_eq!(mt1, mt2);
\n
source

pub fn new_with_key<I>(key: I) -> Self
where\n I: IntoIterator<Item = u32>,\n I::IntoIter: Clone,

Create a new Mersenne Twister random number generator using the given\nkey.

\n

Key can have any length.

\n
source

pub fn new_unseeded() -> Self

Create a new Mersenne Twister random number generator using the default\nfixed seed.

\n
§Examples
\n
// Default MT seed\nlet seed = 5489_u32;\nlet mt = Mt19937GenRand32::new(seed);\nlet unseeded = Mt19937GenRand32::new_unseeded();\nassert_eq!(mt, unseeded);
\n
source

pub fn next_u64(&mut self) -> u64

Generate next u64 output.

\n

This function is implemented by generating two u32s from the RNG and\nperforming shifting and masking to turn them into a u64 output.

\n
§Examples
\n
let mut mt = Mt19937GenRand32::new_unseeded();\nassert_ne!(mt.next_u64(), mt.next_u64());
\n
source

pub fn next_u32(&mut self) -> u32

Generate next u32 output.

\n

u32 is the native output of the generator. This function advances the\nRNG step counter by one.

\n
§Examples
\n
let mut mt = Mt19937GenRand32::new_unseeded();\nassert_ne!(mt.next_u32(), mt.next_u32());
\n
source

pub fn fill_bytes(&mut self, dest: &mut [u8])

Fill a buffer with bytes generated from the RNG.

\n

This method generates random u32s (the native output unit of the RNG)\nuntil dest is filled.

\n

This method may discard some output bits if dest.len() is not a\nmultiple of 4.

\n
§Examples
\n
let mut mt = Mt19937GenRand32::new_unseeded();\nlet mut buf = [0; 32];\nmt.fill_bytes(&mut buf);\nassert_ne!([0; 32], buf);\nlet mut buf = [0; 31];\nmt.fill_bytes(&mut buf);\nassert_ne!([0; 31], buf);
\n
source

pub fn recover<I>(key: I) -> Result<Self, RecoverRngError>
where\n I: IntoIterator<Item = u32>,

Attempt to recover the internal state of a Mersenne Twister using the\npast 624 samples.

\n

This conversion takes a history of samples from a RNG and returns a\nRNG that will produce identical output to the RNG that supplied the\nsamples.

\n

This constructor is also available as a TryFrom implementation for\n&[u32].

\n
§Errors
\n

If key has less than 624 elements, an error is returned because there\nis not enough data to fully initialize the RNG.

\n

If key has more than 624 elements, an error is returned because the\nrecovered RNG will not produce identical output to the RNG that supplied\nthe samples.

\n
source

pub fn reseed(&mut self, seed: u32)

Reseed a Mersenne Twister from a single u32.

\n
§Examples
\n
// Default MT seed\nlet mut mt = Mt19937GenRand32::new_unseeded();\nlet first = mt.next_u32();\nmt.fill_bytes(&mut [0; 512]);\n// Default MT seed\nmt.reseed(5489_u32);\nassert_eq!(first, mt.next_u32());
\n
source

pub fn reseed_with_key<I>(&mut self, key: I)
where\n I: IntoIterator<Item = u32>,\n I::IntoIter: Clone,

Reseed a Mersenne Twister from am iterator of u32s.

\n

Key can have any length.

\n
",0,"rand_mt::Mt"],["
source§

impl Ord for Mt19937GenRand32

source§

fn cmp(&self, other: &Mt19937GenRand32) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · source§

fn max(self, other: Self) -> Self
where\n Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · source§

fn min(self, other: Self) -> Self
where\n Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · source§

fn clamp(self, min: Self, max: Self) -> Self
where\n Self: Sized,

Restrict a value to a certain interval. Read more
","Ord","rand_mt::Mt"],["
source§

impl PartialEq for Mt19937GenRand32

source§

fn eq(&self, other: &Mt19937GenRand32) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient,\nand should not be overridden without very good reason.
","PartialEq","rand_mt::Mt"],["
source§

impl PartialOrd for Mt19937GenRand32

source§

fn partial_cmp(&self, other: &Mt19937GenRand32) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the\n<= operator. Read more
1.0.0 · source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the >\noperator. Read more
1.0.0 · source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by\nthe >= operator. Read more
","PartialOrd","rand_mt::Mt"],["
source§

impl RngCore for Mt19937GenRand32

source§

fn next_u64(&mut self) -> u64

Generate next u64 output.

\n

This function is implemented by generating two u32s from the RNG and\nperforming shifting and masking to turn them into a u64 output.

\n
§Examples
\n
use rand_core::RngCore;\nuse rand_mt::Mt19937GenRand32;\n\nlet mut rng = Mt19937GenRand32::new_unseeded();\nassert_ne!(rng.next_u64(), rng.next_u64());
\n
source§

fn next_u32(&mut self) -> u32

Generate next u32 output.

\n

u32 is the native output of the generator. This function advances the\nRNG step counter by one.

\n
§Examples
\n
use rand_core::RngCore;\nuse rand_mt::Mt19937GenRand32;\n\nlet mut rng = Mt19937GenRand32::new_unseeded();\nassert_ne!(rng.next_u32(), rng.next_u32());
\n
source§

fn fill_bytes(&mut self, dest: &mut [u8])

Fill a buffer with bytes generated from the RNG.

\n

This method generates random u32s (the native output unit of the RNG)\nuntil dest is filled.

\n

This method may discard some output bits if dest.len() is not a\nmultiple of 4.

\n
§Examples
\n
use rand_core::RngCore;\nuse rand_mt::Mt19937GenRand32;\n\nlet mut rng = Mt19937GenRand32::new_unseeded();\nlet mut buf = [0; 32];\nrng.fill_bytes(&mut buf);\nassert_ne!([0; 32], buf);\nlet mut buf = [0; 31];\nrng.fill_bytes(&mut buf);\nassert_ne!([0; 31], buf);
\n
source§

fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error>

Fill a buffer with bytes generated from the RNG.

\n

This method generates random u32s (the native output unit of the RNG)\nuntil dest is filled.

\n

This method may discard some output bits if dest.len() is not a\nmultiple of 4.

\n

try_fill_bytes is implemented with fill_bytes\nand is infallible.

\n
§Examples
\n
use rand_core::RngCore;\nuse rand_mt::Mt19937GenRand32;\n\nlet mut rng = Mt19937GenRand32::new_unseeded();\nlet mut buf = [0; 32];\nrng.try_fill_bytes(&mut buf)?;\nassert_ne!([0; 32], buf);\nlet mut buf = [0; 31];\nrng.try_fill_bytes(&mut buf)?;\nassert_ne!([0; 31], buf);
\n
","RngCore","rand_mt::Mt"],["
source§

impl SeedableRng for Mt19937GenRand32

source§

fn from_seed(seed: Self::Seed) -> Self

Reseed from a little endian encoded u32.

\n
§Examples
\n
use rand_core::{RngCore, SeedableRng};\nuse rand_mt::Mt19937GenRand32;\n\n// Default MT seed\nlet seed = 5489_u32.to_le_bytes();\nlet mut rng = Mt19937GenRand32::from_seed(seed);\nassert_ne!(rng.next_u32(), rng.next_u32());
\n
source§

type Seed = [u8; 4]

Seed type, which is restricted to types mutably-dereferenceable as u8\narrays (we recommend [u8; N] for some N). Read more
source§

fn seed_from_u64(state: u64) -> Self

Create a new PRNG using a u64 seed. Read more
source§

fn from_rng<R>(rng: R) -> Result<Self, Error>
where\n R: RngCore,

Create a new PRNG seeded from another Rng. Read more
","SeedableRng","rand_mt::Mt"],["
source§

impl TryFrom<&[u32]> for Mt19937GenRand32

source§

fn try_from(key: &[u32]) -> Result<Self, Self::Error>

Attempt to recover the internal state of a Mersenne Twister using the\npast 624 samples.

\n

This conversion takes a history of samples from a RNG and returns a\nRNG that will produce identical output to the RNG that supplied the\nsamples.

\n

This conversion is implemented with Mt19937GenRand32::recover.

\n
§Errors
\n

If key has less than 624 elements, an error is returned because there\nis not enough data to fully initialize the RNG.

\n

If key has more than 624 elements, an error is returned because the\nrecovered RNG will not produce identical output to the RNG that supplied\nthe samples.

\n
source§

type Error = RecoverRngError

The type returned in the event of a conversion error.
","TryFrom<&[u32]>","rand_mt::Mt"],["
source§

impl Eq for Mt19937GenRand32

","Eq","rand_mt::Mt"],["
source§

impl StructuralPartialEq for Mt19937GenRand32

","StructuralPartialEq","rand_mt::Mt"]]]]); + if (window.register_type_impls) { + window.register_type_impls(type_impls); + } else { + window.pending_type_impls = type_impls; + } +})() +//{"start":55,"fragment_lengths":[57264]} \ No newline at end of file diff --git a/type.impl/rand_mt/struct.Mt19937GenRand64.js b/type.impl/rand_mt/struct.Mt19937GenRand64.js new file mode 100644 index 000000000..b8a0af07a --- /dev/null +++ b/type.impl/rand_mt/struct.Mt19937GenRand64.js @@ -0,0 +1,9 @@ +(function() { + var type_impls = Object.fromEntries([["rand_mt",[["
source§

impl Clone for Mt19937GenRand64

source§

fn clone(&self) -> Mt19937GenRand64

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
","Clone","rand_mt::Mt64"],["
source§

impl Debug for Mt19937GenRand64

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
","Debug","rand_mt::Mt64"],["
source§

impl Default for Mt19937GenRand64

source§

fn default() -> Self

Return a new Mt19937GenRand64 with the default seed.

\n

Equivalent to calling Mt19937GenRand64::new_unseeded.

\n
","Default","rand_mt::Mt64"],["
source§

impl From<[u64; 312]> for Mt19937GenRand64

source§

fn from(key: [u64; 312]) -> Self

Recover the internal state of a Mersenne Twister using the past 312\nsamples.

\n

This conversion takes a history of samples from a RNG and returns a\nRNG that will produce identical output to the RNG that supplied the\nsamples.

\n
","From<[u64; 312]>","rand_mt::Mt64"],["
source§

impl From<[u8; 8]> for Mt19937GenRand64

source§

fn from(seed: [u8; 8]) -> Self

Construct a Mersenne Twister RNG from 8 bytes.

\n
§Examples
\n
// Default MT seed\nlet seed = 5489_u64.to_le_bytes();\nlet mut mt = Mt19937GenRand64::from(seed);\nassert_ne!(mt.next_u64(), mt.next_u64());
\n
","From<[u8; 8]>","rand_mt::Mt64"],["
source§

impl From<u64> for Mt19937GenRand64

source§

fn from(seed: u64) -> Self

Construct a Mersenne Twister RNG from a u64 seed.

\n

This function is equivalent to new.

\n
§Examples
\n
// Default MT seed\nlet seed = 5489_u64;\nlet mt1 = Mt19937GenRand64::from(seed);\nlet mt2 = Mt19937GenRand64::new(seed);\nassert_eq!(mt1, mt2);\n\n// Non-default MT seed\nlet seed = 9927_u64;\nlet mt1 = Mt19937GenRand64::from(seed);\nlet mt2 = Mt19937GenRand64::new(seed);\nassert_eq!(mt1, mt2);
\n
","From","rand_mt::Mt64"],["
source§

impl Hash for Mt19937GenRand64

source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where\n H: Hasher,\n Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
","Hash","rand_mt::Mt64"],["
source§

impl Mt19937GenRand64

source

pub const DEFAULT_SEED: u64 = 5_489u64

Default seed used by Mt19937GenRand64::new_unseeded.

\n
source

pub fn new(seed: u64) -> Self

Create a new Mersenne Twister random number generator using the given\nseed.

\n
§Examples
§Constructing with a u64 seed
\n
let seed = 123_456_789_u64;\nlet mt1 = Mt19937GenRand64::new(seed);\nlet mt2 = Mt19937GenRand64::from(seed.to_le_bytes());\nassert_eq!(mt1, mt2);
\n
§Constructing with default seed
\n
let mt1 = Mt19937GenRand64::new(Mt19937GenRand64::DEFAULT_SEED);\nlet mt2 = Mt19937GenRand64::new_unseeded();\nassert_eq!(mt1, mt2);
\n
source

pub fn new_with_key<I>(key: I) -> Self
where\n I: IntoIterator<Item = u64>,\n I::IntoIter: Clone,

Create a new Mersenne Twister random number generator using the given\nkey.

\n

Key can have any length.

\n
source

pub fn new_unseeded() -> Self

Create a new Mersenne Twister random number generator using the default\nfixed seed.

\n
§Examples
\n
// Default MT seed\nlet seed = 5489_u64;\nlet mt = Mt19937GenRand64::new(seed);\nlet unseeded = Mt19937GenRand64::new_unseeded();\nassert_eq!(mt, unseeded);
\n
source

pub fn next_u64(&mut self) -> u64

Generate next u64 output.

\n

u64 is the native output of the generator. This function advances the\nRNG step counter by one.

\n
§Examples
\n
let mut mt = Mt19937GenRand64::new_unseeded();\nassert_ne!(mt.next_u64(), mt.next_u64());
\n
source

pub fn next_u32(&mut self) -> u32

Generate next u32 output.

\n

This function is implemented by generating one u64 from the RNG and\nperforming shifting and masking to turn it into a u32 output.

\n
§Examples
\n
let mut mt = Mt19937GenRand64::new_unseeded();\nassert_ne!(mt.next_u32(), mt.next_u32());
\n
source

pub fn fill_bytes(&mut self, dest: &mut [u8])

Fill a buffer with bytes generated from the RNG.

\n

This method generates random u64s (the native output unit of the RNG)\nuntil dest is filled.

\n

This method may discard some output bits if dest.len() is not a\nmultiple of 8.

\n
§Examples
\n
let mut mt = Mt19937GenRand64::new_unseeded();\nlet mut buf = [0; 32];\nmt.fill_bytes(&mut buf);\nassert_ne!([0; 32], buf);\nlet mut buf = [0; 31];\nmt.fill_bytes(&mut buf);\nassert_ne!([0; 31], buf);
\n
source

pub fn recover<I>(key: I) -> Result<Self, RecoverRngError>
where\n I: IntoIterator<Item = u64>,

Attempt to recover the internal state of a Mersenne Twister using the\npast 312 samples.

\n

This conversion takes a history of samples from a RNG and returns a\nRNG that will produce identical output to the RNG that supplied the\nsamples.

\n

This constructor is also available as a TryFrom implementation for\n&[u32].

\n
§Errors
\n

If key has less than 312 elements, an error is returned because there\nis not enough data to fully initialize the RNG.

\n

If key has more than 312 elements, an error is returned because the\nrecovered RNG will not produce identical output to the RNG that supplied\nthe samples.

\n
source

pub fn reseed(&mut self, seed: u64)

Reseed a Mersenne Twister from a single u64.

\n
§Examples
\n
// Default MT seed\nlet mut mt = Mt19937GenRand64::new_unseeded();\nlet first = mt.next_u64();\nmt.fill_bytes(&mut [0; 512]);\n// Default MT seed\nmt.reseed(5489_u64);\nassert_eq!(first, mt.next_u64());
\n
source

pub fn reseed_with_key<I>(&mut self, key: I)
where\n I: IntoIterator<Item = u64>,\n I::IntoIter: Clone,

Reseed a Mersenne Twister from am iterator of u64s.

\n

Key can have any length.

\n
",0,"rand_mt::Mt64"],["
source§

impl Ord for Mt19937GenRand64

source§

fn cmp(&self, other: &Mt19937GenRand64) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · source§

fn max(self, other: Self) -> Self
where\n Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · source§

fn min(self, other: Self) -> Self
where\n Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · source§

fn clamp(self, min: Self, max: Self) -> Self
where\n Self: Sized,

Restrict a value to a certain interval. Read more
","Ord","rand_mt::Mt64"],["
source§

impl PartialEq for Mt19937GenRand64

source§

fn eq(&self, other: &Mt19937GenRand64) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient,\nand should not be overridden without very good reason.
","PartialEq","rand_mt::Mt64"],["
source§

impl PartialOrd for Mt19937GenRand64

source§

fn partial_cmp(&self, other: &Mt19937GenRand64) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the\n<= operator. Read more
1.0.0 · source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the >\noperator. Read more
1.0.0 · source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by\nthe >= operator. Read more
","PartialOrd","rand_mt::Mt64"],["
source§

impl RngCore for Mt19937GenRand64

source§

fn next_u64(&mut self) -> u64

Generate next u64 output.

\n

u64 is the native output of the generator. This function advances the\nRNG step counter by one.

\n
§Examples
\n
use rand_core::RngCore;\nuse rand_mt::Mt19937GenRand64;\n\nlet mut rng = Mt19937GenRand64::new_unseeded();\nassert_ne!(rng.next_u64(), rng.next_u64());
\n
source§

fn next_u32(&mut self) -> u32

Generate next u32 output.

\n

This function is implemented by generating one u64 from the RNG and\nperforming shifting and masking to turn it into a u32 output.

\n
§Examples
\n
use rand_core::RngCore;\nuse rand_mt::Mt19937GenRand64;\n\nlet mut rng = Mt19937GenRand64::new_unseeded();\nassert_ne!(rng.next_u32(), rng.next_u32());
\n
source§

fn fill_bytes(&mut self, dest: &mut [u8])

Fill a buffer with bytes generated from the RNG.

\n

This method generates random u64s (the native output unit of the RNG)\nuntil dest is filled.

\n

This method may discard some output bits if dest.len() is not a\nmultiple of 8.

\n
§Examples
\n
use rand_core::RngCore;\nuse rand_mt::Mt19937GenRand64;\n\nlet mut rng = Mt19937GenRand64::new_unseeded();\nlet mut buf = [0; 32];\nrng.fill_bytes(&mut buf);\nassert_ne!([0; 32], buf);\nlet mut buf = [0; 31];\nrng.fill_bytes(&mut buf);\nassert_ne!([0; 31], buf);
\n
source§

fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error>

Fill a buffer with bytes generated from the RNG.

\n

This method generates random u64s (the native output unit of the RNG)\nuntil dest is filled.

\n

This method may discard some output bits if dest.len() is not a\nmultiple of 8.

\n

try_fill_bytes is implemented with fill_bytes\nand is infallible.

\n
§Examples
\n
use rand_core::RngCore;\nuse rand_mt::Mt19937GenRand64;\n\nlet mut rng = Mt19937GenRand64::new_unseeded();\nlet mut buf = [0; 32];\nrng.try_fill_bytes(&mut buf)?;\nassert_ne!([0; 32], buf);\nlet mut buf = [0; 31];\nrng.try_fill_bytes(&mut buf)?;\nassert_ne!([0; 31], buf);
\n
","RngCore","rand_mt::Mt64"],["
source§

impl SeedableRng for Mt19937GenRand64

source§

fn from_seed(seed: Self::Seed) -> Self

Reseed from a little endian encoded u64.

\n
§Examples
\n
// Default MT seed\nlet seed = 5489_u64.to_le_bytes();\nlet mut mt = Mt19937GenRand64::from_seed(seed);\nassert_ne!(mt.next_u64(), mt.next_u64());
\n
source§

type Seed = [u8; 8]

Seed type, which is restricted to types mutably-dereferenceable as u8\narrays (we recommend [u8; N] for some N). Read more
source§

fn seed_from_u64(state: u64) -> Self

Create a new PRNG using a u64 seed. Read more
source§

fn from_rng<R>(rng: R) -> Result<Self, Error>
where\n R: RngCore,

Create a new PRNG seeded from another Rng. Read more
","SeedableRng","rand_mt::Mt64"],["
source§

impl TryFrom<&[u64]> for Mt19937GenRand64

source§

fn try_from(key: &[u64]) -> Result<Self, Self::Error>

Attempt to recover the internal state of a Mersenne Twister using the\npast 312 samples.

\n

This conversion takes a history of samples from a RNG and returns a\nRNG that will produce identical output to the RNG that supplied the\nsamples.

\n

This conversion is implemented with Mt19937GenRand64::recover.

\n
§Errors
\n

If key has less than 312 elements, an error is returned because there\nis not enough data to fully initialize the RNG.

\n

If key has more than 312 elements, an error is returned because the\nrecovered RNG will not produce identical output to the RNG that supplied\nthe samples.

\n
source§

type Error = RecoverRngError

The type returned in the event of a conversion error.
","TryFrom<&[u64]>","rand_mt::Mt64"],["
source§

impl Eq for Mt19937GenRand64

","Eq","rand_mt::Mt64"],["
source§

impl StructuralPartialEq for Mt19937GenRand64

","StructuralPartialEq","rand_mt::Mt64"]]]]); + if (window.register_type_impls) { + window.register_type_impls(type_impls); + } else { + window.pending_type_impls = type_impls; + } +})() +//{"start":55,"fragment_lengths":[56615]} \ No newline at end of file