summaryrefslogtreecommitdiff
path: root/appl/lib/random.b
blob: 16c7c1ef976ee56ae62db295089eef8b7a99fde6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
implement Random;

include "sys.m";
include "draw.m";
include "keyring.m";
include "security.m";

sys: Sys;

randfd(which: int): ref sys->FD
{
	file: string;

	sys = load Sys Sys->PATH;
	case(which){
	ReallyRandom =>
		file = "/dev/random";
	NotQuiteRandom =>
		file = "/dev/notquiterandom";
	}
	fd := sys->open(file, sys->OREAD);
	if(fd == nil){
		sys->print("can't open /dev/random\n");
		return nil;
	}
	return fd;
}

randomint(which: int): int
{
	fd := randfd(which);
	if(fd == nil)
		return 0;
	buf := array[4] of byte;
	sys->read(fd, buf, 4);
	rand := 0;
	for(i := 0; i < 4; i++)
		rand = (rand<<8) | int buf[i];
	return rand;
}

randombuf(which, n: int): array of byte
{
	buf := array[n] of byte;
	fd := randfd(which);
	if(fd == nil)
		return buf;
	sys->read(fd, buf, n);
	return buf;
}