Skip to content

Commit 022fae1

Browse files
rand: make mt19937 automatically seeded, add seed_len to wyrand (#13966)
1 parent 95753ff commit 022fae1

File tree

2 files changed

+11
-3
lines changed

2 files changed

+11
-3
lines changed

vlib/rand/mt19937/mt19937.v

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
// that can be found in the LICENSE file.
44
module mt19937
55

6+
import rand.seed
7+
68
/*
79
C++ functions for MT19937, with initialization improved 2002/2/10.
810
Coded by Takuji Nishimura and Makoto Matsumoto.
@@ -59,12 +61,18 @@ const (
5961
// **NOTE**: The RNG is not seeded when instantiated so remember to seed it before use.
6062
pub struct MT19937RNG {
6163
mut:
62-
state []u64 = []u64{len: mt19937.nn}
64+
state []u64 = get_first_state(seed.time_seed_array(2))
6365
mti int = mt19937.nn
6466
bytes_left int
6567
buffer u64
6668
}
6769

70+
fn get_first_state(seed_data []u32) []u64 {
71+
mut state := []u64{len: mt19937.nn}
72+
calculate_state(seed_data, mut state)
73+
return state
74+
}
75+
6876
// calculate_state returns a random state array calculated from the `seed_data`.
6977
fn calculate_state(seed_data []u32, mut state []u64) []u64 {
7078
lo := u64(seed_data[0])
@@ -83,8 +91,6 @@ pub fn (mut rng MT19937RNG) seed(seed_data []u32) {
8391
eprintln('mt19937 needs only two 32bit integers as seed: [lower, higher]')
8492
exit(1)
8593
}
86-
// calculate 2 times because MT19937RNG init didn't call calculate_state.
87-
rng.state = calculate_state(seed_data, mut rng.state)
8894
rng.state = calculate_state(seed_data, mut rng.state)
8995
rng.mti = mt19937.nn
9096
rng.bytes_left = 0

vlib/rand/wyrand/wyrand.v

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ const (
1212
wyp1 = u64(0xe7037ed1a0b428db)
1313
)
1414

15+
pub const seed_len = 2
16+
1517
// WyRandRNG is a RNG based on the WyHash hashing algorithm.
1618
pub struct WyRandRNG {
1719
mut:

0 commit comments

Comments
 (0)