diff options
author | Mattias Andrée <maandree@kth.se> | 2024-09-02 18:02:13 +0200 |
---|---|---|
committer | Mattias Andrée <maandree@kth.se> | 2024-09-02 18:02:13 +0200 |
commit | 6f2ccb15b1599700dc6c9c2388609eccca10a608 (patch) | |
tree | d84732290af6e0dfac683eaf2ceea4bd4f7f2493 | |
parent | Add TODO file (diff) | |
download | libsimple-6f2ccb15b1599700dc6c9c2388609eccca10a608.tar.gz libsimple-6f2ccb15b1599700dc6c9c2388609eccca10a608.tar.bz2 libsimple-6f2ccb15b1599700dc6c9c2388609eccca10a608.tar.xz |
m + add libsimple_random_bytes
Signed-off-by: Mattias Andrée <maandree@kth.se>
-rw-r--r-- | Makefile | 1 | ||||
-rw-r--r-- | libsimple/random.h | 3 | ||||
-rw-r--r-- | random_bits.c | 6 | ||||
-rw-r--r-- | random_bytes.c | 39 |
4 files changed, 47 insertions, 2 deletions
@@ -941,6 +941,7 @@ OBJ =\ qsort_ushortp.o\ qsort_ushortp_nul.o\ random_bits.o\ + random_bytes.o\ random_float.o\ random_signed.o\ random_unsigned.o\ diff --git a/libsimple/random.h b/libsimple/random.h index 29e3bbf..ecce38c 100644 --- a/libsimple/random.h +++ b/libsimple/random.h @@ -31,3 +31,6 @@ uintmax_t libsimple_random_bits(size_t bits, void *unused); uintmax_t libsimple_random_unsigned(uintmax_t (*rng)(size_t bits, void *user), void *user, uintmax_t min, uintmax_t max); intmax_t libsimple_random_signed(uintmax_t (*rng)(size_t bits, void *user), void *user, intmax_t min, intmax_t max); long double libsimple_random_float(uintmax_t (*rng)(size_t bits, void *user), void *user, long double min, long double postmax); + +/* TODO doc, man (since 1.7) */ +void *libsimple_random_bytes(uintmax_t (*rng)(size_t bits, void *user), void *user, void *buffer, size_t bytes); diff --git a/random_bits.c b/random_bits.c index 528b09e..a6d95a2 100644 --- a/random_bits.c +++ b/random_bits.c @@ -14,8 +14,10 @@ libsimple_random_bits(size_t bits, void *unused) bits -= 8; } - ret <<= bits; - ret |= (uintmax_t)(rand() & ((1 << bits) - 1)); + if (bits) { + ret <<= bits; + ret |= (uintmax_t)(rand() & ((1 << bits) - 1)); + } (void) unused; return ret; diff --git a/random_bytes.c b/random_bytes.c new file mode 100644 index 0000000..cd7416f --- /dev/null +++ b/random_bytes.c @@ -0,0 +1,39 @@ +/* See LICENSE file for copyright and license details. */ +#include "common.h" +#ifndef TEST + + +void * +libsimple_random_bytes(uintmax_t (*rng)(size_t bits, void *user), void *user, void *buffer, size_t bytes) +{ + char *buf = buffer; + uintmax_t rnd; + + while (bytes >= sizeof(uintmax_t)) { + *(uintmax_t *)buf = (*rng)(sizeof(uintmax_t) * 8U, user); + bytes -= sizeof(uintmax_t); + buf = &buf[sizeof(uintmax_t)]; + } + + if (bytes) { + rnd = (*rng)(bytes * 8U, user); + while (bytes) { + *buf++ = (char)(rnd & 255U); + rnd >>= 8; + } + } + + return buf; +} + + +#else +#include "test.h" + +int +main(void) +{ + return 0; +} + +#endif |