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

crypto: document rest of rand submodule (#8580)

This commit is contained in:
Larpon 2021-02-05 19:26:34 +01:00 committed by GitHub
parent 59c1c77bfe
commit 1101533dea
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -7,6 +7,7 @@ module rand
import math.bits import math.bits
import encoding.binary import encoding.binary
// int_u64 returns a random unsigned 64-bit integer `u64` read from a real OS source of entropy.
pub fn int_u64(max u64) ?u64 { pub fn int_u64(max u64) ?u64 {
bitlen := bits.len_64(max) bitlen := bits.len_64(max)
if bitlen == 0 { if bitlen == 0 {
@ -19,8 +20,8 @@ pub fn int_u64(max u64) ?u64 {
} }
mut n := u64(0) mut n := u64(0)
for { for {
mut bytes := read(k)? mut bytes := read(k) ?
bytes[0] &= byte(int(u64(1)<<b) - 1) bytes[0] &= byte(int(u64(1) << b) - 1)
x := bytes_to_u64(bytes) x := bytes_to_u64(bytes)
n = x[0] n = x[0]
// NOTE: maybe until we have bigint could do it another way? // NOTE: maybe until we have bigint could do it another way?
@ -35,20 +36,20 @@ pub fn int_u64(max u64) ?u64 {
} }
fn bytes_to_u64(b []byte) []u64 { fn bytes_to_u64(b []byte) []u64 {
ws := 64/8 ws := 64 / 8
mut z := []u64{len:((b.len + ws - 1) / ws)} mut z := []u64{len: ((b.len + ws - 1) / ws)}
mut i := b.len mut i := b.len
for k := 0; i >= ws; k++ { for k := 0; i >= ws; k++ {
z[k] = binary.big_endian_u64(b[i-ws..i]) z[k] = binary.big_endian_u64(b[i - ws..i])
i -= ws i -= ws
} }
if i > 0 { if i > 0 {
mut d := u64(0) mut d := u64(0)
for s := u64(0); i > 0; s += u64(8) { for s := u64(0); i > 0; s += u64(8) {
d |= u64(b[i-1]) << s d |= u64(b[i - 1]) << s
i-- i--
} }
z[z.len-1] = d z[z.len - 1] = d
} }
return z return z
} }