xref: /plan9-contrib/sys/src/cmd/random.c (revision acf6de95b6ffd3398ad10f755c8f2060e03260dd)
1 /*
2  * random - print a random number or string
3  */
4 
5 #include <u.h>
6 #include <libc.h>
7 #include <mp.h>
8 #include <libsec.h>
9 
10 static int string, prchars, low, high;
11 
12 static void
usage(void)13 usage(void)
14 {
15 	fprint(2, "usage: %s [-s nch]\n", argv0);
16 	exits("usage");
17 }
18 
19 void
main(int argc,char * argv[])20 main(int argc, char *argv[])
21 {
22 	char *buf, *out;
23 
24 	ARGBEGIN {
25 	case 's':
26 		++string;
27 		prchars = atoi(EARGF(usage()));
28 		break;
29 	default:
30 		usage();
31 		break;
32 	} ARGEND
33 
34 	if (!string) {
35 		print("%f\n", (double)ntruerand(~0ul) / (1ull<<32));
36 		exits(0);
37 	}
38 
39 	/* fill buf from /dev/random */
40 	buf = malloc(prchars + 1);
41 	if (buf == nil)
42 		sysfatal("out of memory: %r");
43 	genrandom((uchar *)buf, prchars);
44 	buf[prchars] = '\0';
45 
46 	/* encode as printable (base64) and print truncated */
47 	fmtinstall('[', encodefmt);
48 	out = smprint("%.*[", prchars, buf);
49 	if (out == nil)
50 		sysfatal("out of memory: %r");
51 	print("%.*s\n", prchars, out);
52 	exits(0);
53 }
54