HikoGUI
A low latency retained GUI
Loading...
Searching...
No Matches
xorshift128p.hpp
1// Copyright Take Vos 2021-2022.
2// Distributed under the Boost Software License, Version 1.0.
3// (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
4
5#pragma once
6
7#include "seed.hpp"
8#include "../SIMD/module.hpp"
9#include "../utility/utility.hpp"
10#include "../macros.hpp"
11#include <random>
12
13
14
15namespace hi::inline v1 {
16
20public:
21 constexpr xorshift128p(xorshift128p const &) noexcept = default;
22 constexpr xorshift128p(xorshift128p &&) noexcept = default;
23 constexpr xorshift128p &operator=(xorshift128p const &) noexcept = default;
24 constexpr xorshift128p &operator=(xorshift128p &&) noexcept = default;
25
26 [[nodiscard]] constexpr explicit xorshift128p(u64x2 new_state) noexcept : _state(new_state) {}
27
28 [[nodiscard]] xorshift128p() noexcept : _state{}
29 {
30 while (_state.x() == 0 or _state.y() == 0) {
31 _state = seed<u64x2>{}();
32 }
33 }
34
35 template<typename T>
36 [[nodiscard]] T next() noexcept;
37
40 template<>
41 [[nodiscard]] uint64_t next() noexcept
42 {
43 auto s = _state[0];
44 hilet t = _state[1];
45
46 s ^= s << 23; // a
47 s ^= s >> 17; // b
48 s ^= t ^ (t >> 26); // c
49
50 _state[0] = t;
51 _state[1] = s;
52 return s + t;
53 }
54
60 template<>
61 u64x2 next() noexcept
62 {
63 // scalar: uint64_t x = _state[0];
64 // scalar: uint64_t y = y_ = _state[1];
65 auto s = _state;
66 auto t = s.yx();
67
68 // scalar: x ^= x << 23;
69 // scalar: y ^= y << 23;
70 s ^= (s << 23);
71
72 // scalar: x ^= x >> 17;
73 // scalar: y ^= y >> 17;
74 s ^= (s >> 17);
75
76 // scalar: x ^= y_ ^ (y_ >> 26)
77 hilet tmp = s ^ t ^ (t >> 26);
78
79 // scalar: auto x_ = x;
80 // scalar: t.y() = tmp.x();
81 t = insert<0, 1>(t, tmp);
82
83 // scalar: y ^= x_ ^ (x_ >> 26);
84 s ^= t ^ (t >> 26);
85
86 // scalar: state[0] = x
87 // scalar: state[1] = y
88 _state = s;
89
90 // scalar: return {x + y_, y + x_}
91 return s + t;
92 }
93
94 template<>
95 [[nodiscard]] u32x4 next() noexcept
96 {
97 return u32x4::cast_from(next<u64x2>());
98 }
99
100 template<>
101 [[nodiscard]] i32x4 next() noexcept
102 {
103 return i32x4::cast_from(next<u64x2>());
104 }
105
106 template<>
107 [[nodiscard]] i16x8 next() noexcept
108 {
109 return i16x8::cast_from(next<u64x2>());
110 }
111
112private:
113 u64x2 _state;
114};
115
116} // namespace hi::inline v1
Cryptographically secure entropy.
DOXYGEN BUG.
Definition algorithm.hpp:16
constexpr Out narrow_cast(In const &rhs) noexcept
Cast numeric values without loss of precision.
Definition cast.hpp:377
Randomly generate an object.
Definition seed_intf.hpp:38
xorshift128+
Definition xorshift128p.hpp:19
uint64_t next() noexcept
Get the next 64 bit of random value.
Definition xorshift128p.hpp:41
u64x2 next() noexcept
Get next 128 bit of random value.
Definition xorshift128p.hpp:61
T next(T... args)