A random number library for C99
Added stdlib `lrand48(3)` generator.
Added the `stdlib random_r()` generator.
Add some stars to make section comments stand out.


browse  log 



You can also use your local clone with git send-email.


A C99 library for generating random numbers.

builds.sr.ht status


The lrnd library contains functions for generating random numbers using pluggable random number generators.


The lrnd structure exposes a common interface to different random number generators.

struct lrnd {
    uint32_t const max_value;
    void (*const clean_up)(struct lrnd *lrnd);
    bool (*const next_value)(struct lrnd *lrnd, uint32_t *value_out);

The max_value field contains the inclusive maximum value that the generator can produce. The clean_up field points to a function that releases any resources this generator uses; it may be NULL if no clean up is needed. The next_value field points to a function that generates the next random value for this generator.

#Global Variables

These variables are singleton instances of generators that wrap functions that maintain their own global state.

extern struct lrnd *const lrnd_stdlib_rand;

A global generator that uses rand(3).

extern struct lrnd *const lrnd_stdlib_random;

A global generator that uses random(3).

extern struct lrnd *const lrnd_stdlib_lrand48;

A global generator that uses lrand48(3).


These functions allocate and initialize an instance of different generators that have local state.

struct lrnd *
lrnd_alloc_poor(uint32_t seed);

Allocate a poor random number generator. This returns a poor PRNG that might be useful for testing or when a consistent pseudo-random sequence is needed across different systems.

struct lrnd *
lrnd_alloc_stdlib_rand_r(unsigned int seed);

Allocate a generator that uses rand_r(3) initialized with the given seed value.

struct lrnd *
lrnd_alloc_stdlib_random_r(size_t state_array_size, unsigned int seed);

Allocate a generator that uses random_r(3) with a state array of the given size, initialized with the given seed value. Use state_array_size values of 8, 32, 64, 128 or 256, where the larger sizes produce better random numbers.


These functions provide the common interface to the random number generators.

lrnd_free(struct lrnd *lrnd);

Clean up and deallocate a generator that was created by one of the lrnd_alloc_() functions.

lrnd_next_value(struct lrnd *lrnd, uint32_t *value_out);

Generate the next random value for the given generator. Returns false and sets errno if generation fails.


lrnd is made available under a BSD-style license; see the LICENSE file for details.