Skip to content

Return Error::Overflow from WeightedIndex::update_weights on integer overflow - #1846

Open
youdie006 wants to merge 1 commit into
rust-random:masterfrom
youdie006:update-weights-overflow
Open

youdie006 wants to merge 1 commit into
rust-random:masterfrom
youdie006:update-weights-overflow

Conversation

@youdie006

Copy link
Copy Markdown
  • Added a CHANGELOG.md entry

Summary

WeightedIndex::update_weights adds integer weights with a plain +=, while new uses checked_add_assign. An update whose sum overflows panics in debug builds and wraps in release builds, contrary to the documented Error::Overflow and "In case of error, self is not modified".

Motivation

let mut w = WeightedIndex::new([200u8, 50]).unwrap();
w.update_weights(&[(1, &100)])
before, debug:    panicked at src/distr/weighted/weighted_index.rs:201:13: attempt to add with overflow
before, release:  Ok(()), total_weight = 44; index 1 is never sampled again (10000 samples: [10000, 0])
after:            Err(Overflow), total_weight = 250; 10000 samples: [8022, 1978]

Details

Each weight is now added with checked_add_assign. An intermediate sum can overflow while the final sum fits ([200u8, 50] updated with (0, &255), (1, &0) returns Ok today), so a weight that does not fit yet is put aside and added after the loop, with Error::Overflow only if the final sum overflows. For floats checked_add_assign never fails, so the float arithmetic and results are unchanged: on 20,000 seeded random multi-index f64 updates the totals and sampled indices are identical to master.

This adds a Weight bound to update_weights. new already requires it, so only a WeightedIndex obtained through Deserialize could lack it.

The new update_weights_overflow test fails on master (debug: the panic; release: Ok(()) instead of Err(Overflow)), and the variant that rejects any intermediate overflow fails its second case. cargo test (default, serde,log, and --no-default-features --features=alloc,sys_rng), cargo +1.85 test --lib, cargo fmt --all -- --check and cargo clippy --workspace --lib --bins --tests -- -D warnings (stable) pass.

Written with AI assistance (Claude); I have reviewed the change.

…overflow

new() adds integer weights with checked_add_assign, but update_weights()
used a plain +=, so an update whose sum overflows panicked in debug builds
and wrapped silently in release builds, leaving a wrong total_weight.
An intermediate sum may overflow while the final sum fits, so such weights
are added at the end instead of rejected.
@youdie006
youdie006 force-pushed the update-weights-overflow branch from ebf8754 to d7ba2f6 Compare November 23, 2026 05:40

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant