From b9cc6535f657e662d66457824ee78da78121527e Mon Sep 17 00:00:00 2001 From: joe-conigliaro <joe-conigliaro@users.noreply.github.com> Date: Wed, 18 Sep 2019 23:12:16 +1000 Subject: [PATCH] crypto.rand: rename read_u64 to int_u64 + clean up --- vlib/crypto/rand/rand_test.v | 6 +++--- vlib/crypto/rand/utils.v | 24 ++++++++++-------------- 2 files changed, 13 insertions(+), 17 deletions(-) diff --git a/vlib/crypto/rand/rand_test.v b/vlib/crypto/rand/rand_test.v index d4913f38b9..b1edad268d 100644 --- a/vlib/crypto/rand/rand_test.v +++ b/vlib/crypto/rand/rand_test.v @@ -29,13 +29,13 @@ fn test_crypto_rand_read() { assert diff_percentage <= max_percentage_diff } -fn test_crypto_rand_read_u64() { +fn test_crypto_rand_int_u64() { max := u64(200) - r1 := rand.read_u64(max) or { + r1 := rand.int_u64(max) or { assert false return } - r2 := rand.read_u64(max) or { + r2 := rand.int_u64(max) or { assert false return } diff --git a/vlib/crypto/rand/utils.v b/vlib/crypto/rand/utils.v index 7e7be7c36b..1f20f272ea 100644 --- a/vlib/crypto/rand/utils.v +++ b/vlib/crypto/rand/utils.v @@ -9,10 +9,7 @@ import( encoding.binary ) -pub fn read_u64(max u64) u64? { - if max <= u64(0) { - return error('crypto.rand: argument to read_u64 is <= 0') - } +pub fn int_u64(max u64) u64? { // bitlen := int(math.floor(math.log2(f64(max))+1)) bitlen := int(math.floor(math.log(f64(max))/math.log(2)) + 1) if bitlen == 0 { @@ -31,12 +28,10 @@ pub fn read_u64(max u64) u64? { bytes[0] &= byte(int(u64(1)<<b) - 1) x := bytes_to_u64(bytes) n = x[0] - if x.len > 1 { - n = u64(u32(x[1])<<u32(32)) | n - } - if int(n) < 0 { - n = -n - } + // NOTE: maybe until we have bigint could do it another way? + // if x.len > 1 { + // n = u64(u32(x[1])<<u32(32)) | n + // } if n < max { return n } @@ -45,11 +40,12 @@ pub fn read_u64(max u64) 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 - for k := 0; i >= 8; k++ { - z[k] = binary.big_endian_u64(b.slice(i-8, i)) - i -= 8 + for k := 0; i >= ws; k++ { + z[k] = binary.big_endian_u64(b.slice(i-ws, i)) + i -= ws } if i > 0 { mut d := u64(0)