randen_engine.h 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. // Copyright 2017 The Abseil Authors.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // https://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #ifndef ABSL_RANDOM_INTERNAL_RANDEN_ENGINE_H_
  15. #define ABSL_RANDOM_INTERNAL_RANDEN_ENGINE_H_
  16. #include <algorithm>
  17. #include <cinttypes>
  18. #include <cstdlib>
  19. #include <iostream>
  20. #include <iterator>
  21. #include <limits>
  22. #include <type_traits>
  23. #include "absl/base/internal/endian.h"
  24. #include "absl/meta/type_traits.h"
  25. #include "absl/random/internal/iostream_state_saver.h"
  26. #include "absl/random/internal/randen.h"
  27. namespace absl {
  28. ABSL_NAMESPACE_BEGIN
  29. namespace random_internal {
  30. // Deterministic pseudorandom byte generator with backtracking resistance
  31. // (leaking the state does not compromise prior outputs). Based on Reverie
  32. // (see "A Robust and Sponge-Like PRNG with Improved Efficiency") instantiated
  33. // with an improved Simpira-like permutation.
  34. // Returns values of type "T" (must be a built-in unsigned integer type).
  35. //
  36. // RANDen = RANDom generator or beetroots in Swiss High German.
  37. // 'Strong' (well-distributed, unpredictable, backtracking-resistant) random
  38. // generator, faster in some benchmarks than std::mt19937_64 and pcg64_c32.
  39. template <typename T>
  40. class alignas(16) randen_engine {
  41. public:
  42. // C++11 URBG interface:
  43. using result_type = T;
  44. static_assert(std::is_unsigned<result_type>::value,
  45. "randen_engine template argument must be a built-in unsigned "
  46. "integer type");
  47. static constexpr result_type(min)() {
  48. return (std::numeric_limits<result_type>::min)();
  49. }
  50. static constexpr result_type(max)() {
  51. return (std::numeric_limits<result_type>::max)();
  52. }
  53. explicit randen_engine(result_type seed_value = 0) { seed(seed_value); }
  54. template <class SeedSequence,
  55. typename = typename absl::enable_if_t<
  56. !std::is_same<SeedSequence, randen_engine>::value>>
  57. explicit randen_engine(SeedSequence&& seq) {
  58. seed(seq);
  59. }
  60. randen_engine(const randen_engine&) = default;
  61. // Returns random bits from the buffer in units of result_type.
  62. result_type operator()() {
  63. // Refill the buffer if needed (unlikely).
  64. if (next_ >= kStateSizeT) {
  65. next_ = kCapacityT;
  66. impl_.Generate(state_);
  67. }
  68. return little_endian::ToHost(state_[next_++]);
  69. }
  70. template <class SeedSequence>
  71. typename absl::enable_if_t<
  72. !std::is_convertible<SeedSequence, result_type>::value>
  73. seed(SeedSequence&& seq) {
  74. // Zeroes the state.
  75. seed();
  76. reseed(seq);
  77. }
  78. void seed(result_type seed_value = 0) {
  79. next_ = kStateSizeT;
  80. // Zeroes the inner state and fills the outer state with seed_value to
  81. // mimics behaviour of reseed
  82. std::fill(std::begin(state_), std::begin(state_) + kCapacityT, 0);
  83. std::fill(std::begin(state_) + kCapacityT, std::end(state_), seed_value);
  84. }
  85. // Inserts entropy into (part of) the state. Calling this periodically with
  86. // sufficient entropy ensures prediction resistance (attackers cannot predict
  87. // future outputs even if state is compromised).
  88. template <class SeedSequence>
  89. void reseed(SeedSequence& seq) {
  90. using sequence_result_type = typename SeedSequence::result_type;
  91. static_assert(sizeof(sequence_result_type) == 4,
  92. "SeedSequence::result_type must be 32-bit");
  93. constexpr size_t kBufferSize =
  94. Randen::kSeedBytes / sizeof(sequence_result_type);
  95. alignas(16) sequence_result_type buffer[kBufferSize];
  96. // Randen::Absorb XORs the seed into state, which is then mixed by a call
  97. // to Randen::Generate. Seeding with only the provided entropy is preferred
  98. // to using an arbitrary generate() call, so use [rand.req.seed_seq]
  99. // size as a proxy for the number of entropy units that can be generated
  100. // without relying on seed sequence mixing...
  101. const size_t entropy_size = seq.size();
  102. if (entropy_size < kBufferSize) {
  103. // ... and only request that many values, or 256-bits, when unspecified.
  104. const size_t requested_entropy = (entropy_size == 0) ? 8u : entropy_size;
  105. std::fill(std::begin(buffer) + requested_entropy, std::end(buffer), 0);
  106. seq.generate(std::begin(buffer), std::begin(buffer) + requested_entropy);
  107. #ifdef ABSL_IS_BIG_ENDIAN
  108. // Randen expects the seed buffer to be in Little Endian; reverse it on
  109. // Big Endian platforms.
  110. for (sequence_result_type& e : buffer) {
  111. e = absl::little_endian::FromHost(e);
  112. }
  113. #endif
  114. // The Randen paper suggests preferentially initializing even-numbered
  115. // 128-bit vectors of the randen state (there are 16 such vectors).
  116. // The seed data is merged into the state offset by 128-bits, which
  117. // implies prefering seed bytes [16..31, ..., 208..223]. Since the
  118. // buffer is 32-bit values, we swap the corresponding buffer positions in
  119. // 128-bit chunks.
  120. size_t dst = kBufferSize;
  121. while (dst > 7) {
  122. // leave the odd bucket as-is.
  123. dst -= 4;
  124. size_t src = dst >> 1;
  125. // swap 128-bits into the even bucket
  126. std::swap(buffer[--dst], buffer[--src]);
  127. std::swap(buffer[--dst], buffer[--src]);
  128. std::swap(buffer[--dst], buffer[--src]);
  129. std::swap(buffer[--dst], buffer[--src]);
  130. }
  131. } else {
  132. seq.generate(std::begin(buffer), std::end(buffer));
  133. }
  134. impl_.Absorb(buffer, state_);
  135. // Generate will be called when operator() is called
  136. next_ = kStateSizeT;
  137. }
  138. void discard(uint64_t count) {
  139. uint64_t step = std::min<uint64_t>(kStateSizeT - next_, count);
  140. count -= step;
  141. constexpr uint64_t kRateT = kStateSizeT - kCapacityT;
  142. while (count > 0) {
  143. next_ = kCapacityT;
  144. impl_.Generate(state_);
  145. step = std::min<uint64_t>(kRateT, count);
  146. count -= step;
  147. }
  148. next_ += step;
  149. }
  150. bool operator==(const randen_engine& other) const {
  151. return next_ == other.next_ &&
  152. std::equal(std::begin(state_), std::end(state_),
  153. std::begin(other.state_));
  154. }
  155. bool operator!=(const randen_engine& other) const {
  156. return !(*this == other);
  157. }
  158. template <class CharT, class Traits>
  159. friend std::basic_ostream<CharT, Traits>& operator<<(
  160. std::basic_ostream<CharT, Traits>& os, // NOLINT(runtime/references)
  161. const randen_engine<T>& engine) { // NOLINT(runtime/references)
  162. using numeric_type =
  163. typename random_internal::stream_format_type<result_type>::type;
  164. auto saver = random_internal::make_ostream_state_saver(os);
  165. for (const auto& elem : engine.state_) {
  166. // In the case that `elem` is `uint8_t`, it must be cast to something
  167. // larger so that it prints as an integer rather than a character. For
  168. // simplicity, apply the cast all circumstances.
  169. os << static_cast<numeric_type>(little_endian::FromHost(elem))
  170. << os.fill();
  171. }
  172. os << engine.next_;
  173. return os;
  174. }
  175. template <class CharT, class Traits>
  176. friend std::basic_istream<CharT, Traits>& operator>>(
  177. std::basic_istream<CharT, Traits>& is, // NOLINT(runtime/references)
  178. randen_engine<T>& engine) { // NOLINT(runtime/references)
  179. using numeric_type =
  180. typename random_internal::stream_format_type<result_type>::type;
  181. result_type state[kStateSizeT];
  182. size_t next;
  183. for (auto& elem : state) {
  184. // It is not possible to read uint8_t from wide streams, so it is
  185. // necessary to read a wider type and then cast it to uint8_t.
  186. numeric_type value;
  187. is >> value;
  188. elem = little_endian::ToHost(static_cast<result_type>(value));
  189. }
  190. is >> next;
  191. if (is.fail()) {
  192. return is;
  193. }
  194. std::memcpy(engine.state_, state, sizeof(engine.state_));
  195. engine.next_ = next;
  196. return is;
  197. }
  198. private:
  199. static constexpr size_t kStateSizeT =
  200. Randen::kStateBytes / sizeof(result_type);
  201. static constexpr size_t kCapacityT =
  202. Randen::kCapacityBytes / sizeof(result_type);
  203. // First kCapacityT are `inner', the others are accessible random bits.
  204. alignas(16) result_type state_[kStateSizeT];
  205. size_t next_; // index within state_
  206. Randen impl_;
  207. };
  208. } // namespace random_internal
  209. ABSL_NAMESPACE_END
  210. } // namespace absl
  211. #endif // ABSL_RANDOM_INTERNAL_RANDEN_ENGINE_H_