Module weighted
Expand description
See weighted for the system contract and examples.
Checked integer-weight sampling for engine content and procedural variants.
Weights are u64: negative, fractional and non-finite values are outside
this API and should be rejected by content parsers rather than cast. Individual
zero weights disable an entry without changing the other entries’ indices.
An empty slice, more than 4096 entries, an all-zero slice, or a total above
u64::MAX is invalid.
WeightedTable is already a prepared distribution: build it once for
repeated allocation-free draws. try_sample validates and selects directly
from a slice without allocating, useful for occasional or changing weights.
Both use the same Random::below rejection sampler and preserve the original
table’s ticket mapping and stream consumption, including single-entry tables.
Invalid weights consume no random draws. Neither API normalizes weights;
scaling even equivalent ratios can change the seeded sequence.
use ferravex_engine::{random::Random, weighted::WeightedTable};
let loot = ["disabled", "common", "rare"];
let table = WeightedTable::try_new(&[0, 3, 1])?;
let mut random = Random::new(42);
for _ in 0..4 {
let item = loot[table.sample(&mut random)];
assert_ne!(item, "disabled");
}
assert_eq!(table.total(), 4);
assert_eq!(table.ticket(3), Some(2)); // Replay-supplied ticket.
assert_eq!(table.ticket(4), None); // Exclusive upper bound, never wrapped.Structs§
- Weighted
Table - A validated, owned cumulative distribution for repeated sampling.
Enums§
- Weight
Error - Compatibility error categories returned by
WeightedTable::new. UseWeightedTable::try_newfor entry-specific diagnostics. - Weight
Validation Error - Detailed validation failure, without consuming randomness or allocating.
Functions§
- try_
sample - Validate and sample directly from weights without allocating a table.