]> git.localhorst.tv Git - blank.git/blob - src/rand/GaloisLFSR.hpp
some code reorganization
[blank.git] / src / rand / GaloisLFSR.hpp
1 #ifndef BLANK_RAND_GALOISLFSR_HPP_
2 #define BLANK_RAND_GALOISLFSR_HPP_
3
4 #include <cstdint>
5 #include <limits>
6
7
8 namespace blank {
9
10 class GaloisLFSR {
11
12 public:
13         // seed should be non-zero
14         explicit GaloisLFSR(std::uint64_t seed) noexcept;
15
16         // get the next bit
17         bool operator ()() noexcept;
18
19         template<class T>
20         T operator ()(T &out) noexcept {
21                 constexpr int num_bits =
22                         std::numeric_limits<T>::digits +
23                         std::numeric_limits<T>::is_signed;
24                 for (int i = 0; i < num_bits; ++i) {
25                         operator ()();
26                 }
27                 return out = static_cast<T>(state);
28         }
29
30 private:
31         std::uint64_t state;
32         // bits 64, 63, 61, and 60 set to 1 (counting from 1 lo to hi)
33         static constexpr std::uint64_t mask = 0xD800000000000000;
34
35 };
36 }
37
38 #endif