From 50c23d300aef05e55b07b069a0455d5cab489cdd Mon Sep 17 00:00:00 2001 From: Alice Ryhl Date: Sat, 2 May 2026 19:01:15 +0200 Subject: [PATCH] runtime: avoid illegal state in `FastRand` (#8078) Co-authored-by: Martin Tzvetanov Grigorov --- tokio/src/util/rand.rs | 32 +++++++++++++++++++++++++------- 1 file changed, 25 insertions(+), 7 deletions(-) diff --git a/tokio/src/util/rand.rs b/tokio/src/util/rand.rs index 67c45693c..efd235154 100644 --- a/tokio/src/util/rand.rs +++ b/tokio/src/util/rand.rs @@ -39,18 +39,17 @@ impl RngSeed { fn from_u64(seed: u64) -> Self { let one = (seed >> 32) as u32; - let mut two = seed as u32; - - if two == 0 { - // This value cannot be zero - two = 1; - } + let two = seed as u32; Self::from_pair(one, two) } fn from_pair(s: u32, r: u32) -> Self { - Self { s, r } + if s == 0 && r == 0 { + Self { s: 0, r: 1 } + } else { + Self { s, r } + } } } @@ -93,3 +92,22 @@ impl FastRand { s0.wrapping_add(s1) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn non_zero_seed_from_u64() { + let seed = RngSeed::from_u64(0); + assert_eq!(seed.s, 0); + assert_eq!(seed.r, 1); + } + + #[test] + fn non_zero_seed_from_pair() { + let seed = RngSeed::from_pair(0, 0); + assert_eq!(seed.s, 0); + assert_eq!(seed.r, 1); + } +}