From 022fae1e7f704266b3c339de5eb7c18a59447c72 Mon Sep 17 00:00:00 2001 From: Subhomoy Haldar Date: Thu, 7 Apr 2022 18:30:30 +0530 Subject: [PATCH] rand: make mt19937 automatically seeded, add seed_len to wyrand (#13966) --- vlib/rand/mt19937/mt19937.v | 12 +++++++++--- vlib/rand/wyrand/wyrand.v | 2 ++ 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/vlib/rand/mt19937/mt19937.v b/vlib/rand/mt19937/mt19937.v index 43a80e7455..6b0a173884 100644 --- a/vlib/rand/mt19937/mt19937.v +++ b/vlib/rand/mt19937/mt19937.v @@ -3,6 +3,8 @@ // that can be found in the LICENSE file. module mt19937 +import rand.seed + /* C++ functions for MT19937, with initialization improved 2002/2/10. Coded by Takuji Nishimura and Makoto Matsumoto. @@ -59,12 +61,18 @@ const ( // **NOTE**: The RNG is not seeded when instantiated so remember to seed it before use. pub struct MT19937RNG { mut: - state []u64 = []u64{len: mt19937.nn} + state []u64 = get_first_state(seed.time_seed_array(2)) mti int = mt19937.nn bytes_left int buffer u64 } +fn get_first_state(seed_data []u32) []u64 { + mut state := []u64{len: mt19937.nn} + calculate_state(seed_data, mut state) + return state +} + // calculate_state returns a random state array calculated from the `seed_data`. fn calculate_state(seed_data []u32, mut state []u64) []u64 { lo := u64(seed_data[0]) @@ -83,8 +91,6 @@ pub fn (mut rng MT19937RNG) seed(seed_data []u32) { eprintln('mt19937 needs only two 32bit integers as seed: [lower, higher]') exit(1) } - // calculate 2 times because MT19937RNG init didn't call calculate_state. - rng.state = calculate_state(seed_data, mut rng.state) rng.state = calculate_state(seed_data, mut rng.state) rng.mti = mt19937.nn rng.bytes_left = 0 diff --git a/vlib/rand/wyrand/wyrand.v b/vlib/rand/wyrand/wyrand.v index 52e4e06f84..c20a049dba 100644 --- a/vlib/rand/wyrand/wyrand.v +++ b/vlib/rand/wyrand/wyrand.v @@ -12,6 +12,8 @@ const ( wyp1 = u64(0xe7037ed1a0b428db) ) +pub const seed_len = 2 + // WyRandRNG is a RNG based on the WyHash hashing algorithm. pub struct WyRandRNG { mut: