crypto.rand: fix linux/solaris rand.read() compilation

pull/5674/head
Delyan Angelov 2020-07-05 01:33:36 +03:00
parent 188bad4f38
commit 770ffa1ebd
2 changed files with 31 additions and 32 deletions

View File

@ -1,34 +1,34 @@
// Copyright (c) 2019-2020 Alexander Medvednikov. All rights reserved.
// Use of this source code is governed by an MIT license
// that can be found in the LICENSE file.
module rand
import math
#include <sys/syscall.h>
const (
read_batch_size = 256
)
pub fn read(bytes_needed int) ?[]byte {
buffer := malloc(bytes_needed)
mut buffer := &byte(0)
unsafe {
buffer = malloc(bytes_needed)
}
mut bstart := buffer
mut bytes_read := 0
mut remaining_bytes := bytes_needed
// getrandom syscall wont block if requesting <= 256 bytes
if bytes_needed > read_batch_size {
no_batches := int(math.floor(f64(bytes_needed/read_batch_size)))
for i:=0; i < no_batches; i++ {
if getrandom(read_batch_size, buffer+bytes_read) == -1 {
return read_error
}
bytes_read += read_batch_size
for bytes_read < bytes_needed {
batch_size := if remaining_bytes > read_batch_size { read_batch_size } else { remaining_bytes }
unsafe {
bstart = buffer + bytes_read
}
rbytes := getrandom(batch_size, bstart)
if rbytes == -1 {
free(buffer)
return read_error
}
bytes_read += rbytes
}
if getrandom(bytes_needed-bytes_read, buffer+bytes_read) == -1 {
return read_error
}
return c_array_to_bytes_tmp(bytes_needed, buffer)
}

View File

@ -4,8 +4,6 @@
module rand
import math
#include <sys/random.h>
fn C.getrandom(p byteptr, n size_t, flags u32) int
@ -17,23 +15,24 @@ const (
pub fn read(bytes_needed int) ?[]byte {
mut buffer := &byte(0)
unsafe {
buffer = malloc(bytes_needed)
buffer = malloc(bytes_needed)
}
mut bstart := buffer
mut bytes_read := 0
mut remaining_bytes := bytes_needed
// getrandom syscall wont block if requesting <= 256 bytes
if bytes_needed > read_batch_size {
no_batches := int(math.floor(f64(bytes_needed/read_batch_size)))
for i:=0; i<no_batches; i++ {
if v_getrandom(read_batch_size, buffer+bytes_read) == -1 {
return read_error
}
bytes_read += read_batch_size
for bytes_read < bytes_needed {
batch_size := if remaining_bytes > read_batch_size { read_batch_size } else { remaining_bytes }
unsafe {
bstart = buffer + bytes_read
}
rbytes := getrandom(batch_size, bstart)
if rbytes == -1 {
free(buffer)
return read_error
}
bytes_read += rbytes
}
if v_getrandom(bytes_needed-bytes_read, buffer+bytes_read) == -1 {
return read_error
}
return c_array_to_bytes_tmp(bytes_needed, buffer)
}