pcg_engine.h 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. // Copyright 2018 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_PCG_ENGINE_H_
  15. #define ABSL_RANDOM_INTERNAL_PCG_ENGINE_H_
  16. #include <type_traits>
  17. #include "absl/base/config.h"
  18. #include "absl/meta/type_traits.h"
  19. #include "absl/numeric/bits.h"
  20. #include "absl/numeric/int128.h"
  21. #include "absl/random/internal/fastmath.h"
  22. #include "absl/random/internal/iostream_state_saver.h"
  23. namespace absl {
  24. ABSL_NAMESPACE_BEGIN
  25. namespace random_internal {
  26. // pcg_engine is a simplified implementation of Melissa O'Neil's PCG engine in
  27. // C++. PCG combines a linear congruential generator (LCG) with output state
  28. // mixing functions to generate each random variate. pcg_engine supports only a
  29. // single sequence (oneseq), and does not support streams.
  30. //
  31. // pcg_engine is parameterized by two types:
  32. // Params, which provides the multiplier and increment values;
  33. // Mix, which mixes the state into the result.
  34. //
  35. template <typename Params, typename Mix>
  36. class pcg_engine {
  37. static_assert(std::is_same<typename Params::state_type,
  38. typename Mix::state_type>::value,
  39. "Class-template absl::pcg_engine must be parameterized by "
  40. "Params and Mix with identical state_type");
  41. static_assert(std::is_unsigned<typename Mix::result_type>::value,
  42. "Class-template absl::pcg_engine must be parameterized by "
  43. "an unsigned Mix::result_type");
  44. using params_type = Params;
  45. using mix_type = Mix;
  46. using state_type = typename Mix::state_type;
  47. public:
  48. // C++11 URBG interface:
  49. using result_type = typename Mix::result_type;
  50. static constexpr result_type(min)() {
  51. return (std::numeric_limits<result_type>::min)();
  52. }
  53. static constexpr result_type(max)() {
  54. return (std::numeric_limits<result_type>::max)();
  55. }
  56. explicit pcg_engine(uint64_t seed_value = 0) { seed(seed_value); }
  57. template <class SeedSequence,
  58. typename = typename absl::enable_if_t<
  59. !std::is_same<SeedSequence, pcg_engine>::value>>
  60. explicit pcg_engine(SeedSequence&& seq) {
  61. seed(seq);
  62. }
  63. pcg_engine(const pcg_engine&) = default;
  64. pcg_engine& operator=(const pcg_engine&) = default;
  65. pcg_engine(pcg_engine&&) = default;
  66. pcg_engine& operator=(pcg_engine&&) = default;
  67. result_type operator()() {
  68. // Advance the LCG state, always using the new value to generate the output.
  69. state_ = lcg(state_);
  70. return Mix{}(state_);
  71. }
  72. void seed(uint64_t seed_value = 0) {
  73. state_type tmp = seed_value;
  74. state_ = lcg(tmp + Params::increment());
  75. }
  76. template <class SeedSequence>
  77. typename absl::enable_if_t<
  78. !std::is_convertible<SeedSequence, uint64_t>::value, void>
  79. seed(SeedSequence&& seq) {
  80. reseed(seq);
  81. }
  82. void discard(uint64_t count) { state_ = advance(state_, count); }
  83. bool operator==(const pcg_engine& other) const {
  84. return state_ == other.state_;
  85. }
  86. bool operator!=(const pcg_engine& other) const { return !(*this == other); }
  87. template <class CharT, class Traits>
  88. friend typename absl::enable_if_t<(sizeof(state_type) == 16),
  89. std::basic_ostream<CharT, Traits>&>
  90. operator<<(
  91. std::basic_ostream<CharT, Traits>& os, // NOLINT(runtime/references)
  92. const pcg_engine& engine) {
  93. auto saver = random_internal::make_ostream_state_saver(os);
  94. random_internal::stream_u128_helper<state_type> helper;
  95. helper.write(pcg_engine::params_type::multiplier(), os);
  96. os << os.fill();
  97. helper.write(pcg_engine::params_type::increment(), os);
  98. os << os.fill();
  99. helper.write(engine.state_, os);
  100. return os;
  101. }
  102. template <class CharT, class Traits>
  103. friend typename absl::enable_if_t<(sizeof(state_type) <= 8),
  104. std::basic_ostream<CharT, Traits>&>
  105. operator<<(
  106. std::basic_ostream<CharT, Traits>& os, // NOLINT(runtime/references)
  107. const pcg_engine& engine) {
  108. auto saver = random_internal::make_ostream_state_saver(os);
  109. os << pcg_engine::params_type::multiplier() << os.fill();
  110. os << pcg_engine::params_type::increment() << os.fill();
  111. os << engine.state_;
  112. return os;
  113. }
  114. template <class CharT, class Traits>
  115. friend typename absl::enable_if_t<(sizeof(state_type) == 16),
  116. std::basic_istream<CharT, Traits>&>
  117. operator>>(
  118. std::basic_istream<CharT, Traits>& is, // NOLINT(runtime/references)
  119. pcg_engine& engine) { // NOLINT(runtime/references)
  120. random_internal::stream_u128_helper<state_type> helper;
  121. auto mult = helper.read(is);
  122. auto inc = helper.read(is);
  123. auto tmp = helper.read(is);
  124. if (mult != pcg_engine::params_type::multiplier() ||
  125. inc != pcg_engine::params_type::increment()) {
  126. // signal failure by setting the failbit.
  127. is.setstate(is.rdstate() | std::ios_base::failbit);
  128. }
  129. if (!is.fail()) {
  130. engine.state_ = tmp;
  131. }
  132. return is;
  133. }
  134. template <class CharT, class Traits>
  135. friend typename absl::enable_if_t<(sizeof(state_type) <= 8),
  136. std::basic_istream<CharT, Traits>&>
  137. operator>>(
  138. std::basic_istream<CharT, Traits>& is, // NOLINT(runtime/references)
  139. pcg_engine& engine) { // NOLINT(runtime/references)
  140. state_type mult{}, inc{}, tmp{};
  141. is >> mult >> inc >> tmp;
  142. if (mult != pcg_engine::params_type::multiplier() ||
  143. inc != pcg_engine::params_type::increment()) {
  144. // signal failure by setting the failbit.
  145. is.setstate(is.rdstate() | std::ios_base::failbit);
  146. }
  147. if (!is.fail()) {
  148. engine.state_ = tmp;
  149. }
  150. return is;
  151. }
  152. private:
  153. state_type state_;
  154. // Returns the linear-congruential generator next state.
  155. static inline constexpr state_type lcg(state_type s) {
  156. return s * Params::multiplier() + Params::increment();
  157. }
  158. // Returns the linear-congruential arbitrary seek state.
  159. inline state_type advance(state_type s, uint64_t n) const {
  160. state_type mult = Params::multiplier();
  161. state_type inc = Params::increment();
  162. state_type m = 1;
  163. state_type i = 0;
  164. while (n > 0) {
  165. if (n & 1) {
  166. m *= mult;
  167. i = i * mult + inc;
  168. }
  169. inc = (mult + 1) * inc;
  170. mult *= mult;
  171. n >>= 1;
  172. }
  173. return m * s + i;
  174. }
  175. template <class SeedSequence>
  176. void reseed(SeedSequence& seq) {
  177. using sequence_result_type = typename SeedSequence::result_type;
  178. constexpr size_t kBufferSize =
  179. sizeof(state_type) / sizeof(sequence_result_type);
  180. sequence_result_type buffer[kBufferSize];
  181. seq.generate(std::begin(buffer), std::end(buffer));
  182. // Convert the seed output to a single state value.
  183. state_type tmp = buffer[0];
  184. for (size_t i = 1; i < kBufferSize; i++) {
  185. tmp <<= (sizeof(sequence_result_type) * 8);
  186. tmp |= buffer[i];
  187. }
  188. state_ = lcg(tmp + params_type::increment());
  189. }
  190. };
  191. // Parameterized implementation of the PCG 128-bit oneseq state.
  192. // This provides state_type, multiplier, and increment for pcg_engine.
  193. template <uint64_t kMultA, uint64_t kMultB, uint64_t kIncA, uint64_t kIncB>
  194. class pcg128_params {
  195. public:
  196. using state_type = absl::uint128;
  197. static inline constexpr state_type multiplier() {
  198. return absl::MakeUint128(kMultA, kMultB);
  199. }
  200. static inline constexpr state_type increment() {
  201. return absl::MakeUint128(kIncA, kIncB);
  202. }
  203. };
  204. // Implementation of the PCG xsl_rr_128_64 128-bit mixing function, which
  205. // accepts an input of state_type and mixes it into an output of result_type.
  206. struct pcg_xsl_rr_128_64 {
  207. using state_type = absl::uint128;
  208. using result_type = uint64_t;
  209. inline uint64_t operator()(state_type state) {
  210. // This is equivalent to the xsl_rr_128_64 mixing function.
  211. uint64_t rotate = static_cast<uint64_t>(state >> 122u);
  212. state ^= state >> 64;
  213. uint64_t s = static_cast<uint64_t>(state);
  214. return rotr(s, static_cast<int>(rotate));
  215. }
  216. };
  217. // Parameterized implementation of the PCG 64-bit oneseq state.
  218. // This provides state_type, multiplier, and increment for pcg_engine.
  219. template <uint64_t kMult, uint64_t kInc>
  220. class pcg64_params {
  221. public:
  222. using state_type = uint64_t;
  223. static inline constexpr state_type multiplier() { return kMult; }
  224. static inline constexpr state_type increment() { return kInc; }
  225. };
  226. // Implementation of the PCG xsh_rr_64_32 64-bit mixing function, which accepts
  227. // an input of state_type and mixes it into an output of result_type.
  228. struct pcg_xsh_rr_64_32 {
  229. using state_type = uint64_t;
  230. using result_type = uint32_t;
  231. inline uint32_t operator()(uint64_t state) {
  232. return rotr(static_cast<uint32_t>(((state >> 18) ^ state) >> 27),
  233. state >> 59);
  234. }
  235. };
  236. // Stable pcg_engine implementations:
  237. // This is a 64-bit generator using 128-bits of state.
  238. // The output sequence is equivalent to Melissa O'Neil's pcg64_oneseq.
  239. using pcg64_2018_engine = pcg_engine<
  240. random_internal::pcg128_params<0x2360ed051fc65da4ull, 0x4385df649fccf645ull,
  241. 0x5851f42d4c957f2d, 0x14057b7ef767814f>,
  242. random_internal::pcg_xsl_rr_128_64>;
  243. // This is a 32-bit generator using 64-bits of state.
  244. // This is equivalent to Melissa O'Neil's pcg32_oneseq.
  245. using pcg32_2018_engine = pcg_engine<
  246. random_internal::pcg64_params<0x5851f42d4c957f2dull, 0x14057b7ef767814full>,
  247. random_internal::pcg_xsh_rr_64_32>;
  248. } // namespace random_internal
  249. ABSL_NAMESPACE_END
  250. } // namespace absl
  251. #endif // ABSL_RANDOM_INTERNAL_PCG_ENGINE_H_