Files

52 lines
1020 B
C
Raw Permalink Normal View History

#include <assert.h>
#include <fcntl.h>
#include <limits.h>
#include <string.h>
2016-02-22 14:45:18 -08:00
#include <sys/types.h>
#include <sys/stat.h>
2016-02-22 14:57:27 -08:00
#include <sys/uio.h>
2016-02-22 14:45:18 -08:00
#include <unistd.h>
2016-02-22 14:57:27 -08:00
2016-02-22 16:41:34 -08:00
#include "buf.h"
2016-02-22 14:45:18 -08:00
#include "rand.h"
static struct buf rand_buf = BUF_INIT;
2016-02-22 14:45:18 -08:00
static int rand_fd;
void rand_init() {
rand_fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOCTTY);
2016-02-22 14:45:18 -08:00
assert(rand_fd >= 0);
2016-02-22 14:57:27 -08:00
assert(read(rand_fd, buf_at(&rand_buf, 0), BUF_LEN_MAX) == BUF_LEN_MAX);
rand_buf.length = BUF_LEN_MAX;
2016-02-22 14:45:18 -08:00
}
void rand_cleanup() {
assert(!close(rand_fd));
}
void rand_fill(void *value, size_t size) {
2016-02-22 14:57:27 -08:00
if (size <= rand_buf.length) {
memcpy(value, buf_at(&rand_buf, 0), size);
buf_consume(&rand_buf, size);
return;
}
struct iovec iov[2] = {
{
.iov_base = rand_buf.buf,
.iov_len = rand_buf.start,
},
{
.iov_base = value,
.iov_len = size,
},
};
size_t bytes = rand_buf.start + size;
assert(bytes < SSIZE_MAX);
assert(readv(rand_fd, iov, 2) == (ssize_t) bytes);
2016-02-22 14:57:27 -08:00
rand_buf.start = 0;
rand_buf.length = BUF_LEN_MAX;
2016-02-22 14:45:18 -08:00
}