Interface to generate pseudo-random numbers.
This module generates non-cryptographically-secure random numbers in an easy to use and fast way.
There is a single global state that must be initialised by calling Random_seedAutomatic() or Random_seedManual(). Afterwards, you can call Random_getNumber() or Random_getBytes() as desired. Both are thread-safe and protect the internal state.
The pseudo-random number generator used is the "xorwow" algorithm specified in Marsaglia's "Xorshift RNGs" paper. It keeps 20 bytes of state that must be seeded and has a period of 2^160 - 2^32 before a sequence wraps.
Generating a random number with this algorithm is quite fast. Random_getNumber() only requires 82 instructions which is 1.7us on a 48MHz Cortex M4. That includes disabling interrupts.
#include <stdint.h>
#include <stdbool.h>
#include <stddef.h>
Go to the source code of this file.
Macros | |
#define | Random_STATUS_SUCCESS (0) |
#define | Random_STATUS_ERROR (-1) |
#define | Random_SEED_LENGTH (20) |
Length of the seed in bytes. More... | |
Functions | |
int_fast16_t | Random_seedAutomatic (void) |
Seed internal state automatically. More... | |
void | Random_seedManual (uint8_t seed[(20)]) |
Set the internal state to a specified seed. More... | |
uint32_t | Random_getNumber (void) |
Returns a random number. More... | |
void | Random_getBytes (void *buffer, size_t bufferSize) |
#define Random_STATUS_SUCCESS (0) |
#define Random_STATUS_ERROR (-1) |
#define Random_SEED_LENGTH (20) |
Length of the seed in bytes.
int_fast16_t Random_seedAutomatic | ( | void | ) |
Seed internal state automatically.
This function seeds or reseeds the internal state. The method for generating the seed is device dependent.
If a TRNG is available, it will be used to generate the seed.
If a TRNG is not available, information unique to the device running the code will be used. This may be a unique device identifier or other information such as a MAC address. Since the seed is constant per device for devices without a TRNG, the number sequence will restart after each call to Random_seedAutomatic(). This will usually occur after rebooting the device.
If neither a TRNG nor a unique device identifier is available, a constant will be used.
void Random_seedManual | ( | uint8_t | seed[(20)] | ) |
Set the internal state to a specified seed.
This function sets the internal state to the seed specified by the application.
seed | Seed to set the internal state to |
uint32_t Random_getNumber | ( | void | ) |
Returns a random number.
This function returns a random number and updates the internal state.
void Random_getBytes | ( | void * | buffer, |
size_t | bufferSize | ||
) |
Returns a number of random bytes
This is a convenience function that fills the specified array with random bytes by repeatedly calling Random_getNumber().
buffer | Buffer to fill with random bytes |
bufferSize | Size of buffer. Any value is permitted, including those that are not multiples of sizeof(uint32_t). |