mirror of
https://github.com/vlang/v.git
synced 2023-08-10 21:13:21 +03:00
rand: use time microseconds too in default rand initialization; generate proper uuid_v4
This commit is contained in:
parent
c429fa7e27
commit
289974dd15
@ -25,12 +25,15 @@ fn gen_randoms(seed_data []u32, bound int) []u32 {
|
||||
}
|
||||
|
||||
fn test_pcg32_reproducibility() {
|
||||
randoms1 := gen_randoms(util.time_seed_array(4), 1000)
|
||||
randoms2 := gen_randoms(util.time_seed_array(4), 1000)
|
||||
seed_data := util.time_seed_array(4)
|
||||
randoms1 := gen_randoms(seed_data, 1000)
|
||||
randoms2 := gen_randoms(seed_data, 1000)
|
||||
assert randoms1.len == randoms2.len
|
||||
len := randoms1.len
|
||||
for i in 0 .. len {
|
||||
assert randoms1[i] == randoms2[i]
|
||||
r1 := randoms1[i]
|
||||
r2 := randoms2[i]
|
||||
assert r1 == r2
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -149,13 +149,18 @@ pub fn string(len int) string {
|
||||
pub fn uuid_v4() string {
|
||||
mut buf := malloc(37)
|
||||
for i in 0..36 {
|
||||
mut v := intn(16)
|
||||
if i == 19 {
|
||||
v = (v & 0x3) | 0x8
|
||||
}
|
||||
unsafe {
|
||||
buf[i] = hex_chars[intn(16)]
|
||||
buf[i] = hex_chars[v]
|
||||
}
|
||||
}
|
||||
unsafe {
|
||||
buf[8] = `-`
|
||||
buf[13] = `-`
|
||||
buf[14] = `4`
|
||||
buf[18] = `-`
|
||||
buf[23] = `-`
|
||||
buf[36] = 0
|
||||
|
@ -186,4 +186,7 @@ fn test_rand_uuid_v4() {
|
||||
assert uuid1.len == 36
|
||||
assert uuid2.len == 36
|
||||
assert uuid3.len == 36
|
||||
assert uuid1[14] == `4`
|
||||
assert uuid2[14] == `4`
|
||||
assert uuid3[14] == `4`
|
||||
}
|
||||
|
@ -25,7 +25,8 @@ fn nr_next(prev u32) u32 {
|
||||
// time_seed_array is a utility function that returns the required number of u32s generated from system time
|
||||
[inline]
|
||||
pub fn time_seed_array(count int) []u32 {
|
||||
mut seed := u32(time.now().unix_time())
|
||||
ctime := time.now()
|
||||
mut seed := u32(ctime.unix_time() ^ ctime.microsecond)
|
||||
mut seed_data := []u32{cap: count}
|
||||
for _ in 0 .. count {
|
||||
seed = nr_next(seed)
|
||||
|
Loading…
Reference in New Issue
Block a user