Debian Codegraph @

crypto/random/random.ha

raw
1 // SPDX-License-Identifier: MPL-2.0
2 // (c) Hare authors <https://harelang.org>
3
4 use io;
5
6 let _stream_vt: io::vtable = io::vtable {
7 reader = &rand_reader,
8 ...
9 };
10
11 const _stream: io::stream = &_stream_vt;
12
13 // An [[io::handle]] which returns cryptographically random data on reads. Be
14 // aware, it may return less than you asked for!
15 export let stream: *io::stream = &_stream;
16
17 @test fn buffer() void = {
18 let buf: [4096]u8 = [0...];
19 buffer(buf[..]);
20
21 let sum = 0z;
22 for (let i = 0z; i < len(buf); i += 1) {
23 sum += buf[i];
24 };
25 let avg = sum / len(buf);
26 assert(avg < 0xA0 && avg > 0x60);
27 };
28
29 @test fn reader() void = {
30 let buf: [4096]u8 = [0...];
31 let test: []u8 = [];
32 match (io::readall(stream, buf[..])) {
33 case (io::error | io::EOF) =>
34 abort();
35 case let n: size =>
36 test = buf[..n];
37 };
38
39 assert(len(test) > 0);
40
41 let sum = 0z;
42 for (let i = 0z; i < len(test); i += 1) {
43 sum += test[i];
44 };
45 let avg = sum / len(test);
46 assert(avg < 0xA0 && avg > 0x60);
47 };