crypto.rand: rename read_u64 to int_u64 + clean up
parent
f187c35fb2
commit
b9cc6535f6
|
@ -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
|
||||
}
|
||||
|
|
|
@ -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)
|
||||
|
|
Loading…
Reference in New Issue