util/rand: Extend, add functions to init with seed, rand u8, u16, array

This commit is contained in:
icex2
2021-01-17 00:51:22 +01:00
parent 628a5d040e
commit 2871238427
2 changed files with 50 additions and 1 deletions
+34 -1
View File
@@ -1,7 +1,8 @@
#include <time.h>
#include <stdlib.h>
#include "rand.h"
#include "util/log.h"
#include "util/rand.h"
static int _util_rand_init = 0;
@@ -13,6 +14,22 @@ static void _util_rand_initialize()
}
}
void util_rand_init(uint32_t seed)
{
_util_rand_init = 1;
srand(seed);
}
uint8_t util_rand_gen_8()
{
return (uint8_t) util_rand_gen_32();
}
uint16_t util_rand_gen_16()
{
return (uint16_t) util_rand_gen_32();
}
uint32_t util_rand_gen_32()
{
_util_rand_initialize();
@@ -20,6 +37,11 @@ uint32_t util_rand_gen_32()
return (uint32_t) rand();
}
uint32_t util_rand_gen_range_32(uint32_t max)
{
return util_rand_gen_32() % max;
}
uint64_t util_rand_gen_64()
{
uint64_t value;
@@ -31,4 +53,15 @@ uint64_t util_rand_gen_64()
value |= ((uint64_t) rand());
return value;
}
void util_rand_gen_bytes(uint8_t* buffer, size_t len)
{
log_assert(buffer);
_util_rand_initialize();
for (size_t i = 0; i < len; i++) {
buffer[i] = (uint8_t) rand();
}
}
+16
View File
@@ -3,8 +3,24 @@
#include <stdint.h>
/**
* General note for this module: The implementations provided are supposed to
* be used for non-security related randomness, e.g. generate some random data
* for testing something.
*/
void util_rand_init(uint32_t seed);
uint8_t util_rand_gen_8();
uint16_t util_rand_gen_16();
uint32_t util_rand_gen_32();
uint32_t util_rand_gen_range_32(uint32_t max);
uint64_t util_rand_gen_64();
void util_rand_gen_bytes(uint8_t* buffer, size_t len);
#endif