From 09d9c2c9f6c1f148d08c0d875aa1b59770502989 Mon Sep 17 00:00:00 2001 From: Squirrel Date: Thu, 24 Jun 2021 08:20:15 +0100 Subject: [PATCH] Fix to support u32::MAX (#9188) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Fix to support u32::MAX * Update primitives/runtime/src/random_number_generator.rs Co-authored-by: Andronik Ordian Co-authored-by: Bastian Köcher Co-authored-by: Andronik Ordian --- .../runtime/src/random_number_generator.rs | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/substrate/primitives/runtime/src/random_number_generator.rs b/substrate/primitives/runtime/src/random_number_generator.rs index a4d1a66370..41ca7c723e 100644 --- a/substrate/primitives/runtime/src/random_number_generator.rs +++ b/substrate/primitives/runtime/src/random_number_generator.rs @@ -27,6 +27,8 @@ use crate::traits::{Hash, TrailingZeroInput}; /// /// It can be saved and later reloaded using the Codec traits. /// +/// (It is recommended to use the `rand_chacha` crate as an alternative to this where possible.) +/// /// Example: /// ``` /// use sp_runtime::traits::{Hash, BlakeTwo256}; @@ -63,7 +65,7 @@ impl RandomNumberGenerator { /// Returns a number at least zero, at most `max`. pub fn pick_u32(&mut self, max: u32) -> u32 { let needed = (4 - max.leading_zeros() / 8) as usize; - let top = ((1 << (needed as u64 * 8)) / ((max + 1) as u64) * ((max + 1) as u64) - 1) as u32; + let top = ((1 << (needed as u64 * 8)) / (max as u64 + 1) * (max as u64 + 1) - 1) as u32; loop { if self.offset() + needed > self.current.as_ref().len() { // rehash @@ -102,3 +104,15 @@ impl RandomNumberGenerator { } } } + +#[cfg(test)] +mod tests { + use super::RandomNumberGenerator; + use crate::traits::{Hash, BlakeTwo256}; + + #[test] + fn does_not_panic_on_max() { + let seed = BlakeTwo256::hash(b"Fourty-two"); + let _random = RandomNumberGenerator::::new(seed).pick_u32(u32::MAX); + } +}