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