crypto.rand: rename read_u64 to int_u64 + clean up

pull/2023/head
joe-conigliaro 2019-09-18 23:12:16 +10:00 committed by Alexander Medvednikov
parent f187c35fb2
commit b9cc6535f6
2 changed files with 13 additions and 17 deletions

View File

@ -29,13 +29,13 @@ fn test_crypto_rand_read() {
assert diff_percentage <= max_percentage_diff assert diff_percentage <= max_percentage_diff
} }
fn test_crypto_rand_read_u64() { fn test_crypto_rand_int_u64() {
max := u64(200) max := u64(200)
r1 := rand.read_u64(max) or { r1 := rand.int_u64(max) or {
assert false assert false
return return
} }
r2 := rand.read_u64(max) or { r2 := rand.int_u64(max) or {
assert false assert false
return return
} }

View File

@ -9,10 +9,7 @@ import(
encoding.binary encoding.binary
) )
pub fn read_u64(max u64) u64? { pub fn int_u64(max u64) u64? {
if max <= u64(0) {
return error('crypto.rand: argument to read_u64 is <= 0')
}
// bitlen := int(math.floor(math.log2(f64(max))+1)) // bitlen := int(math.floor(math.log2(f64(max))+1))
bitlen := int(math.floor(math.log(f64(max))/math.log(2)) + 1) bitlen := int(math.floor(math.log(f64(max))/math.log(2)) + 1)
if bitlen == 0 { if bitlen == 0 {
@ -31,12 +28,10 @@ pub fn read_u64(max u64) u64? {
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]
if x.len > 1 { // NOTE: maybe until we have bigint could do it another way?
n = u64(u32(x[1])<<u32(32)) | n // if x.len > 1 {
} // n = u64(u32(x[1])<<u32(32)) | n
if int(n) < 0 { // }
n = -n
}
if n < max { if n < max {
return n return n
} }
@ -45,11 +40,12 @@ pub fn read_u64(max u64) u64? {
} }
fn bytes_to_u64(b []byte) []u64 { fn bytes_to_u64(b []byte) []u64 {
mut z := [u64(0)].repeat((b.len + 8 - 1) / 8) ws := 64/8
mut z := [u64(0)].repeat((b.len + ws - 1) / ws)
mut i := b.len mut i := b.len
for k := 0; i >= 8; k++ { for k := 0; i >= ws; k++ {
z[k] = binary.big_endian_u64(b.slice(i-8, i)) z[k] = binary.big_endian_u64(b.slice(i-ws, i))
i -= 8 i -= ws
} }
if i > 0 { if i > 0 {
mut d := u64(0) mut d := u64(0)