2022-10-13 18:13:11 +05:30
|
|
|
// Copyright 2013-2022 Nicholas J. Kain <njkain at gmail dot com>
|
2022-02-07 06:35:29 +05:30
|
|
|
// SPDX-License-Identifier: MIT
|
2020-10-20 16:14:31 +05:30
|
|
|
#include <stdint.h>
|
|
|
|
#include "nk/hwrng.h"
|
|
|
|
#include "nk/random.h"
|
|
|
|
|
2022-10-13 18:13:11 +05:30
|
|
|
// SFC64 modified to use a Weyl counter.
|
2020-10-20 16:14:31 +05:30
|
|
|
|
|
|
|
void nk_random_init(struct nk_random_state *s)
|
|
|
|
{
|
2022-10-13 18:13:11 +05:30
|
|
|
nk_hwrng_bytes(s->seed, sizeof(uint64_t) * 3);
|
|
|
|
s->seed[3] = 1;
|
|
|
|
for (size_t i = 0; i < 12; ++i) nk_random_u64(s);
|
2020-10-20 16:14:31 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
static inline uint64_t rotl64(const uint64_t x, int k) {
|
|
|
|
return (x << k) | (x >> (64 - k));
|
|
|
|
}
|
|
|
|
|
|
|
|
uint64_t nk_random_u64(struct nk_random_state *s)
|
|
|
|
{
|
2022-10-13 18:13:11 +05:30
|
|
|
const uint64_t t = (s->seed[0] + s->seed[1]) ^ s->seed[3];
|
|
|
|
s->seed[3] += 0x6a09e667a7541669ull;
|
|
|
|
s->seed[0] = s->seed[1] ^ (s->seed[1] >> 11);
|
|
|
|
s->seed[1] = s->seed[2] + (s->seed[2] << 3);
|
|
|
|
s->seed[2] = rotl64(s->seed[2], 24) + t;
|
|
|
|
return t;
|
2020-10-20 16:14:31 +05:30
|
|
|
}
|
|
|
|
|