aboutsummaryrefslogtreecommitdiff
path: root/libgloss/m68k/atari/atari-getentropy.c
blob: 0b5b461b91bd8880c906d3165728d7e615b7fb9a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*
	Copyright (C) 2025 Mikael Hildenborg
	SPDX-License-Identifier: BSD-2-Clause
*/

#include <_ansi.h>
#include <_syslist.h>
#include <errno.h>
#include "atari-gem_errno.h"
#include "atari-traps.h"

/*
    Xorshift pseudorandom number generator.
    https://en.wikipedia.org/wiki/Xorshift
    Inited with random seed.
*/

int getentropy(void *buf, size_t buflen)
{
    unsigned int a;
    unsigned int state[4];

    // Init state
    a = trap14_11();     // Atari Random func.
    for (int i = 0; i < 4; ++i)
    {
        // xorshift32
        a ^= (a << 13);
        a ^= (a >> 17);
        a ^= (a << 5);
        state[i] = a;
    }

    for (size_t i = 0; i < buflen; ++i)
    {
        // xorshift128
        unsigned int t = state[3];
        unsigned int s = state[0];
        state[3] = state[2];
        state[2] = state[1];
        state[1] = s;

        t ^= t << 11;
        t ^= t >> 7;
        state[0] = t ^ s ^ (s >> 19);

        // use lowest byte (could be optimized to adapt to buf len and output whole 32 bits when possible.)
        ((unsigned char*)buf)[i] = (unsigned char)state[0];
    }

    return 0;
}