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