Struct WeightedTable

pub struct WeightedTable { /* private fields */ }
Expand description

A validated, owned cumulative distribution for repeated sampling.

Preparation uses O(n) time and stores one u64 per input entry, including zero weights. Self::ticket and Self::sample search in O(log n) time without allocations; random rejection sampling may require multiple draws. Changing the original slice cannot change a prepared table.

Implementations§

§

impl WeightedTable

pub const MAX_ENTRIES: usize = 4_096usize

Maximum number of entries, including those with zero weight.

pub fn new(weights: &[u64]) -> Result<WeightedTable, WeightError>

Prepare a distribution using the original error categories.

This retains the original validation and seeded sampling behavior. Prefer Self::try_new when reporting invalid authored weights.

use ferravex_engine::weighted::{WeightError, WeightedTable};
assert_eq!(WeightedTable::new(&[0, 0]).unwrap_err(), WeightError::ZeroTotal);
assert_eq!(WeightedTable::new(&[0, 2, 1])?.ticket(2), Some(2));

pub fn validate(weights: &[u64]) -> Result<u64, WeightValidationError>

Check the entry count and sum without allocating; return the nonzero total.

§Errors

Returns WeightValidationError::Empty or WeightValidationError::Capacity before examining entries. Otherwise reports the first WeightValidationError::Overflow, or WeightValidationError::ZeroTotal if all entries are zero.

use ferravex_engine::weighted::{WeightValidationError, WeightedTable};
assert_eq!(WeightedTable::validate(&[0, 2, 3]), Ok(5));
assert_eq!(WeightedTable::validate(&[u64::MAX, 0, 1]), Err(
    WeightValidationError::Overflow {
        index: 2, partial_total: u64::MAX, weight: 1,
    }
));

pub fn try_new(weights: &[u64]) -> Result<WeightedTable, WeightValidationError>

Prepare a reusable distribution with detailed validation errors.

Performs Self::validate before allocating cumulative storage. The table owns its weights’ cumulative sums, so the source may be dropped or changed after this call. Use try_sample for allocation-free selection when a reusable table is unnecessary.

use ferravex_engine::weighted::WeightedTable;
let mut weights = [0, 2, 1];
let table = WeightedTable::try_new(&weights)?;
weights[1] = 0;
assert_eq!(table.ticket(0), Some(1)); // Prepared weights are retained.

pub fn ticket(&self, ticket: u64) -> Option<usize>

Resolve a ticket in [0, total) to its original entry index.

Zero-weight entries are never returned. A ticket at or above the total returns None, without wrapping or clamping. Useful when a replay host supplies draws; no randomness is consumed.

pub fn sample(&self, random: &mut Random) -> usize

Sample an original entry index using the existing rejection sampler.

The prepared table is always valid, so selection cannot fail. No allocation or revalidation is needed. Even a single selectable entry consumes randomness, preserving the original stream position.

pub fn total(&self) -> u64

Sum of the validated weights, always in 1..=u64::MAX.

Trait Implementations§

§

impl Debug for WeightedTable

§

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

Formats the value using the given formatter. Read more

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