aboutsummaryrefslogtreecommitdiff
path: root/src/libsec/port/nfastrand.c
blob: a4d640dd7d04d2e5e6afa6976a59c85371c82b3d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <u.h>
#include <libc.h>
#include <libsec.h>

#define Maxrand	((1UL<<31)-1)

ulong
nfastrand(ulong n)
{
	ulong m, r;

	/*
	 * set m to the maximum multiple of n <= 2^31-1
	 * so we want a random number < m.
	 */
	if(n > Maxrand)
		sysfatal("nfastrand: n too large");

	m = Maxrand - Maxrand % n;
	while((r = fastrand()) >= m)
		;
	return r%n;
}