Skip to main content

Module portable_random

Module portable_random 

Source
Expand description

Sampling routines whose results depend only on the bytes an RNG produces, never on which version of rand is in the dependency graph.

rand’s own shuffle, choose, choose_multiple and choose_multiple_weighted are free to change between releases, and they have: 0.9 replaced the range sampler and the weighted-selection wrapper, so the same seed produces a different permutation. That is fine for a test fixture and unacceptable for a permutation every validator has to agree on.

The routines here reproduce rand 0.8’s algorithms and are fixed by tests against captured vectors, so callers that need a permutation to stay the same forever can bump rand freely.

Two rules for callers:

  • Seed [rand::rngs::ChaCha12Rng], not StdRng. StdRng is documented as non-portable — rand reserves the right to swap the algorithm under it — whereas ChaCha12Rng names the generator and is what StdRng currently happens to be.
  • Draw floats through f64_unit rather than rand’s random::<f64>(), which is another conversion rand owns and could change.

Functions§

choose
Returns a uniformly drawn element, or None if slice is empty.
f64_unit
Draws a f64 uniformly from [0, 1), using the top 53 bits of one 64-bit word.
index
Draws an index uniformly from 0..ubound.
sample_indices
Draws amount distinct indices from 0..length, in random order.
sample_weighted
Draws amount distinct indices from 0..length with probability proportional to weight, in descending order of the keys drawn.
shuffle
Permutes slice in place (Fisher-Yates, from the back).