1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

rand: add PRNG interface and unit-tests (#9083)

This commit is contained in:
Subhomoy Haldar
2021-03-03 17:11:00 +05:30
committed by GitHub
parent 412c17ccda
commit a5dd7faf3c
4 changed files with 105 additions and 12 deletions

View File

@@ -8,11 +8,42 @@ import rand.wyrand
import time
// PRNGConfigStruct is a configuration struct for creating a new instance of the default RNG.
// Note that the RNGs may have a different number of u32s required for seeding. The default
// generator WyRand used 64 bits, ie. 2 u32s so that is the default. In case your desired generator
// uses a different number of u32s, use the `seed.time_seed_array()` method with the correct
// number of u32s.
pub struct PRNGConfigStruct {
seed []u32 = seed.time_seed_array(2)
}
__global ( default_rng &wyrand.WyRandRNG )
// PRNG is a common interface for all PRNGs that can be used seamlessly with the rand
// modules's API. It defines all the methods that a PRNG (in the vlib or custom made) must
// implement in order to ensure that _all_ functions can be used with the generator.
pub interface PRNG {
seed(seed_data []u32)
u32() u32
u64() u64
u32n(max u32) u32
u64n(max u64) u64
u32_in_range(min u32, max u32) u32
u64_in_range(min u64, max u64) u64
int() int
i64() i64
int31() int
int63() i64
intn(max int) int
i64n(max i64) i64
int_in_range(min int, max int) int
i64_in_range(min i64, max i64) i64
f32() f32
f64() f64
f32n(max f32) f32
f64n(max f64) f64
f32_in_range(min f32, max f32) f32
f64_in_range(min f64, max f64) f64
}
__global ( default_rng &PRNG )
// init initializes the default RNG.
fn init() {
@@ -20,13 +51,27 @@ fn init() {
}
// new_default returns a new instance of the default RNG. If the seed is not provided, the current time will be used to seed the instance.
pub fn new_default(config PRNGConfigStruct) &wyrand.WyRandRNG {
pub fn new_default(config PRNGConfigStruct) &PRNG {
mut rng := &wyrand.WyRandRNG{}
rng.seed(config.seed)
return rng
}
// seed sets the given array of `u32` values as the seed for the `default_rng`.
// get_current_rng returns the PRNG instance currently in use. If it is not changed, it will be an instance of wyrand.WyRandRNG.
pub fn get_current_rng() &PRNG {
return default_rng
}
// set_rng changes the default RNG from wyrand.WyRandRNG (or whatever the last RNG was) to the one
// provided by the user. Note that this new RNG must be seeded manually with a constant seed or the
// `seed.time_seed_array()` method. Also, it is recommended to store the old RNG in a variable and
// should be restored if work with the custom RNG is complete. It is not necessary to restore if the
// program terminates soon afterwards.
pub fn set_rng(rng &PRNG) {
default_rng = rng
}
// seed sets the given array of `u32` values as the seed for the `default_rng`. It is recommended to use
pub fn seed(seed []u32) {
default_rng.seed(seed)
}