Skip to content
This repository was archived by the owner on Nov 15, 2023. It is now read-only.

Commit 63ab278

Browse files
gilescopebkchrAndronik Ordian
authored
Fix to support u32::MAX (#9188)
* Fix to support u32::MAX * Update primitives/runtime/src/random_number_generator.rs Co-authored-by: Andronik Ordian <write@reusable.software> Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com> Co-authored-by: Andronik Ordian <write@reusable.software>
1 parent 550d64c commit 63ab278

File tree

1 file changed

+15
-1
lines changed

1 file changed

+15
-1
lines changed

primitives/runtime/src/random_number_generator.rs

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@ use crate::traits::{Hash, TrailingZeroInput};
2727
///
2828
/// It can be saved and later reloaded using the Codec traits.
2929
///
30+
/// (It is recommended to use the `rand_chacha` crate as an alternative to this where possible.)
31+
///
3032
/// Example:
3133
/// ```
3234
/// use sp_runtime::traits::{Hash, BlakeTwo256};
@@ -63,7 +65,7 @@ impl<Hashing: Hash> RandomNumberGenerator<Hashing> {
6365
/// Returns a number at least zero, at most `max`.
6466
pub fn pick_u32(&mut self, max: u32) -> u32 {
6567
let needed = (4 - max.leading_zeros() / 8) as usize;
66-
let top = ((1 << (needed as u64 * 8)) / ((max + 1) as u64) * ((max + 1) as u64) - 1) as u32;
68+
let top = ((1 << (needed as u64 * 8)) / (max as u64 + 1) * (max as u64 + 1) - 1) as u32;
6769
loop {
6870
if self.offset() + needed > self.current.as_ref().len() {
6971
// rehash
@@ -102,3 +104,15 @@ impl<Hashing: Hash> RandomNumberGenerator<Hashing> {
102104
}
103105
}
104106
}
107+
108+
#[cfg(test)]
109+
mod tests {
110+
use super::RandomNumberGenerator;
111+
use crate::traits::{Hash, BlakeTwo256};
112+
113+
#[test]
114+
fn does_not_panic_on_max() {
115+
let seed = BlakeTwo256::hash(b"Fourty-two");
116+
let _random = RandomNumberGenerator::<BlakeTwo256>::new(seed).pick_u32(u32::MAX);
117+
}
118+
}

0 commit comments

Comments
 (0)