From: Martin Mares Date: Fri, 15 Sep 2006 19:00:12 +0000 (+0200) Subject: Added random_u64() and random_max_u64(). X-Git-Tag: holmes-import~539^2~1 X-Git-Url: http://mj.ucw.cz/gitweb/?a=commitdiff_plain;h=998c357a4f0c645fd73f69c9f18c5f78c0cfe9ca;p=libucw.git Added random_u64() and random_max_u64(). --- diff --git a/lib/lib.h b/lib/lib.h index b20ba7e9..5ab134f0 100644 --- a/lib/lib.h +++ b/lib/lib.h @@ -208,7 +208,9 @@ int rx_subst(regex *r, byte *by, byte *src, byte *dest, uns destlen); /* random.c */ -uns random_max(uns); +uns random_max(uns max); +u64 random_u64(void); +u64 random_max_u64(u64 max); /* mmap.c */ diff --git a/lib/random.c b/lib/random.c index 7f88489d..87f7f544 100644 --- a/lib/random.c +++ b/lib/random.c @@ -1,7 +1,7 @@ /* - * UCW Library -- Unbiased Range Correction for random() + * UCW Library -- Unbiased Random Numbers * - * (c) 1998 Martin Mares + * (c) 1998--2006 Martin Mares * * This software may be freely distributed and used according to the terms * of the GNU Lesser General Public License. @@ -11,6 +11,9 @@ #include +/* We expect the random generator in libc to give at least 30 bits of randomness */ +COMPILE_ASSERT(RAND_MAX_RANGE_TEST, RAND_MAX >= (1 << 30)-1); + uns random_max(uns max) { @@ -22,3 +25,27 @@ random_max(uns max) while (r >= l); return r % max; } + +u64 +random_u64(void) +{ + return + ((u64)(random() & 0xffff) << 48) | + ((u64)(random() & 0xffffff) << 24) | + (random() & 0xffffff); +} + +u64 +random_max_u64(u64 max) +{ + if (max < (1 << 30)) + return random_max(max); + + u64 r, l, m; + m = 0xffffffffffffffff; + l = m - (m % max); + do + r = random_u64(); + while (r >= l); + return r % max; +}