Function try_sample
pub fn try_sample(
weights: &[u64],
random: &mut Random,
) -> Result<usize, WeightValidationError>Expand description
Validate and sample directly from weights without allocating a table.
Returns the original index, never a zero-weight entry. Validation completes
before any random draw: every WeightValidationError leaves random
unchanged, even when overflow occurs late in the slice. Successful selection
uses exactly the same stream consumption and ticket mapping as
WeightedTable::sample. Work is O(n) per call, plus random rejection
sampling; prepare a WeightedTable for repeated draws with unchanged weights.
use ferravex_engine::{random::Random, weighted::{try_sample, WeightValidationError}};
let mut random = Random::new(42);
let mut expected = random.clone();
assert_eq!(try_sample(&[0, 0], &mut random), Err(WeightValidationError::ZeroTotal));
assert_eq!(random.next_u64(), expected.next_u64());
assert_eq!(try_sample(&[0, 9, 0], &mut random)?, 1);