Skip to content

Commit

Permalink
random: Use sfc64 instead of gjrand.
Browse files Browse the repository at this point in the history
  • Loading branch information
niklata committed Oct 13, 2022
1 parent 1c1ea86 commit 1b8dc7f
Showing 1 changed file with 11 additions and 18 deletions.
29 changes: 11 additions & 18 deletions nk/random.c
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
// Copyright 2013-2018 Nicholas J. Kain <njkain at gmail dot com>
// Copyright 2013-2022 Nicholas J. Kain <njkain at gmail dot com>
// SPDX-License-Identifier: MIT
#include <stdint.h>
#include "nk/hwrng.h"
#include "nk/random.h"

// GJrand64: https://gjrand.sourceforge.net
// SFC64 modified to use a Weyl counter.

void nk_random_init(struct nk_random_state *s)
{
nk_hwrng_bytes(s->seed, sizeof(uint64_t) * 2);
s->seed[2] = 2000001;
s->seed[3] = 0;
for (size_t i = 0; i < 14; ++i) nk_random_u64(s);
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);
}

static inline uint64_t rotl64(const uint64_t x, int k) {
Expand All @@ -20,17 +19,11 @@ static inline uint64_t rotl64(const uint64_t x, int k) {

uint64_t nk_random_u64(struct nk_random_state *s)
{
s->seed[1] += s->seed[2];
s->seed[0] = rotl64(s->seed[0], 32);
s->seed[2] ^= s->seed[1];
s->seed[3] += 0x55aa96a5;
s->seed[0] += s->seed[1];
s->seed[2] = rotl64(s->seed[2], 23);
s->seed[1] ^= s->seed[0];
s->seed[0] += s->seed[2];
s->seed[1] = rotl64(s->seed[1], 19);
s->seed[2] += s->seed[0];
s->seed[1] += s->seed[3];
return s->seed[0];
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;
}

0 comments on commit 1b8dc7f

Please sign in to comment.