From: Ben Pfaff Date: Wed, 24 Dec 2008 01:02:46 +0000 (-0800) Subject: New functions random_uint8(), random_uint16(). X-Git-Url: https://pintos-os.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=8638a791704d19b689c1f23d55d1bb040a0cdcdf;p=openvswitch New functions random_uint8(), random_uint16(). Also, reimplement random_uint32() to make fewer calls to rand(). --- diff --git a/lib/random.c b/lib/random.c index f4fab4c8..14be87e5 100644 --- a/lib/random.c +++ b/lib/random.c @@ -64,12 +64,40 @@ random_bytes(void *p_, size_t n) } } +uint8_t +random_uint8(void) +{ + random_init(); + return rand(); +} + +uint16_t +random_uint16(void) +{ + if (RAND_MAX >= UINT16_MAX) { + random_init(); + return rand(); + } else { + uint16_t x; + random_bytes(&x, sizeof x); + return x; + } +} + uint32_t random_uint32(void) { - uint32_t x; - random_bytes(&x, sizeof x); - return x; + if (RAND_MAX >= UINT32_MAX) { + random_init(); + return rand(); + } else if (RAND_MAX == INT32_MAX) { + random_init(); + return rand() | ((rand() & 1u) << 31); + } else { + uint32_t x; + random_bytes(&x, sizeof x); + return x; + } } int diff --git a/lib/random.h b/lib/random.h index d9f5f9d0..80332308 100644 --- a/lib/random.h +++ b/lib/random.h @@ -38,6 +38,8 @@ #include void random_bytes(void *, size_t); +uint8_t random_uint8(void); +uint16_t random_uint16(void); uint32_t random_uint32(void); int random_range(int max);