Built motion from commit 6a09e18b.|2.6.11
[motion2.git] / legacy-libs / grpc / deps / grpc / third_party / abseil-cpp / absl / random / internal / fast_uniform_bits.h
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
15 #ifndef ABSL_RANDOM_INTERNAL_FAST_UNIFORM_BITS_H_
16 #define ABSL_RANDOM_INTERNAL_FAST_UNIFORM_BITS_H_
17
18 #include <cstddef>
19 #include <cstdint>
20 #include <limits>
21 #include <type_traits>
22
23 namespace absl {
24 namespace random_internal {
25 // Computes the length of the range of values producible by the URBG, or returns
26 // zero if that would encompass the entire range of representable values in
27 // URBG::result_type.
28 template <typename URBG>
29 constexpr typename URBG::result_type constexpr_range() {
30   using result_type = typename URBG::result_type;
31   return ((URBG::max)() == (std::numeric_limits<result_type>::max)() &&
32           (URBG::min)() == std::numeric_limits<result_type>::lowest())
33              ? result_type{0}
34              : (URBG::max)() - (URBG::min)() + result_type{1};
35 }
36
37 // FastUniformBits implements a fast path to acquire uniform independent bits
38 // from a type which conforms to the [rand.req.urbg] concept.
39 // Parameterized by:
40 //  `UIntType`: the result (output) type
41 //  `Width`: binary output width
42 //
43 // The std::independent_bits_engine [rand.adapt.ibits] adaptor can be
44 // instantiated from an existing generator through a copy or a move. It does
45 // not, however, facilitate the production of pseudorandom bits from an un-owned
46 // generator that will outlive the std::independent_bits_engine instance.
47 template <typename UIntType = uint64_t,
48           size_t Width = std::numeric_limits<UIntType>::digits>
49 class FastUniformBits {
50   static_assert(std::is_unsigned<UIntType>::value,
51                 "Class-template FastUniformBits<> must be parameterized using "
52                 "an unsigned type.");
53
54   // `kWidth` is the width, in binary digits, of the output. By default it is
55   // the number of binary digits in the `result_type`.
56   static constexpr size_t kWidth = Width;
57   static_assert(kWidth > 0,
58                 "Class-template FastUniformBits<> Width argument must be > 0");
59
60   static_assert(kWidth <= std::numeric_limits<UIntType>::digits,
61                 "Class-template FastUniformBits<> Width argument must be <= "
62                 "width of UIntType.");
63
64   static constexpr bool kIsMaxWidth =
65       (kWidth >= std::numeric_limits<UIntType>::digits);
66
67   // Computes a mask of `n` bits for the `UIntType`.
68   static constexpr UIntType constexpr_mask(size_t n) {
69     return (UIntType(1) << n) - 1;
70   }
71
72  public:
73   using result_type = UIntType;
74
75   static constexpr result_type(min)() { return 0; }
76   static constexpr result_type(max)() {
77     return kIsMaxWidth ? (std::numeric_limits<result_type>::max)()
78                        : constexpr_mask(kWidth);
79   }
80
81   template <typename URBG>
82   result_type operator()(URBG& g);  // NOLINT(runtime/references)
83
84  private:
85   // Variate() generates a single random variate, always returning a value
86   // in the closed interval [0 ... FastUniformBitsURBGConstants::kRangeMask]
87   // (kRangeMask+1 is a power of 2).
88   template <typename URBG>
89   typename URBG::result_type Variate(URBG& g);  // NOLINT(runtime/references)
90
91   // generate() generates a random value, dispatched on whether
92   // the underlying URNG must loop over multiple calls or not.
93   template <typename URBG>
94   result_type Generate(URBG& g,  // NOLINT(runtime/references)
95                        std::true_type /* avoid_looping */);
96
97   template <typename URBG>
98   result_type Generate(URBG& g,  // NOLINT(runtime/references)
99                        std::false_type /* avoid_looping */);
100 };
101
102 // FastUniformBitsURBGConstants computes the URBG-derived constants used
103 // by FastUniformBits::Generate and FastUniformBits::Variate.
104 // Parameterized by the FastUniformBits parameter:
105 //   `URBG`: The underlying UniformRandomNumberGenerator.
106 //
107 // The values here indicate the URBG range as well as providing an indicator
108 // whether the URBG output is a power of 2, and kRangeMask, which allows masking
109 // the generated output to kRangeBits.
110 template <typename URBG>
111 class FastUniformBitsURBGConstants {
112   // Computes the floor of the log. (i.e., std::floor(std::log2(N));
113   static constexpr size_t constexpr_log2(size_t n) {
114     return (n <= 1) ? 0 : 1 + constexpr_log2(n / 2);
115   }
116
117   // Computes a mask of n bits for the URBG::result_type.
118   static constexpr typename URBG::result_type constexpr_mask(size_t n) {
119     return (typename URBG::result_type(1) << n) - 1;
120   }
121
122  public:
123   using result_type = typename URBG::result_type;
124
125   // The range of the URNG, max - min + 1, or zero if that result would cause
126   // overflow.
127   static constexpr result_type kRange = constexpr_range<URBG>();
128
129   static constexpr bool kPowerOfTwo =
130       (kRange == 0) || ((kRange & (kRange - 1)) == 0);
131
132   // kRangeBits describes the number number of bits suitable to mask off of URNG
133   // variate, which is:
134   // kRangeBits = floor(log2(kRange))
135   static constexpr size_t kRangeBits =
136       kRange == 0 ? std::numeric_limits<result_type>::digits
137                   : constexpr_log2(kRange);
138
139   // kRangeMask is the mask used when sampling variates from the URNG when the
140   // width of the URNG range is not a power of 2.
141   // Y = (2 ^ kRange) - 1
142   static constexpr result_type kRangeMask =
143       kRange == 0 ? (std::numeric_limits<result_type>::max)()
144                   : constexpr_mask(kRangeBits);
145
146   static_assert((URBG::max)() != (URBG::min)(),
147                 "Class-template FastUniformBitsURBGConstants<> "
148                 "URBG::max and URBG::min may not be equal.");
149
150   static_assert(std::is_unsigned<result_type>::value,
151                 "Class-template FastUniformBitsURBGConstants<> "
152                 "URBG::result_type must be unsigned.");
153
154   static_assert(kRangeMask > 0,
155                 "Class-template FastUniformBitsURBGConstants<> "
156                 "URBG does not generate sufficient random bits.");
157
158   static_assert(kRange == 0 ||
159                     kRangeBits < std::numeric_limits<result_type>::digits,
160                 "Class-template FastUniformBitsURBGConstants<> "
161                 "URBG range computation error.");
162 };
163
164 // FastUniformBitsLoopingConstants computes the looping constants used
165 // by FastUniformBits::Generate. These constants indicate how multiple
166 // URBG::result_type values are combined into an output_value.
167 // Parameterized by the FastUniformBits parameters:
168 //  `UIntType`: output type.
169 //  `Width`: binary output width,
170 //  `URNG`: The underlying UniformRandomNumberGenerator.
171 //
172 // The looping constants describe the sets of loop counters and mask values
173 // which control how individual variates are combined the final output.  The
174 // algorithm ensures that the number of bits used by any individual call differs
175 // by at-most one bit from any other call. This is simplified into constants
176 // which describe two loops, with the second loop parameters providing one extra
177 // bit per variate.
178 //
179 // See [rand.adapt.ibits] for more details on the use of these constants.
180 template <typename UIntType, size_t Width, typename URBG>
181 class FastUniformBitsLoopingConstants {
182  private:
183   static constexpr size_t kWidth = Width;
184   using urbg_result_type = typename URBG::result_type;
185   using uint_result_type = UIntType;
186
187  public:
188   using result_type =
189       typename std::conditional<(sizeof(urbg_result_type) <=
190                                  sizeof(uint_result_type)),
191                                 uint_result_type, urbg_result_type>::type;
192
193  private:
194   // Estimate N as ceil(width / urng width), and W0 as (width / N).
195   static constexpr size_t kRangeBits =
196       FastUniformBitsURBGConstants<URBG>::kRangeBits;
197
198   // The range of the URNG, max - min + 1, or zero if that result would cause
199   // overflow.
200   static constexpr result_type kRange = constexpr_range<URBG>();
201   static constexpr size_t kEstimateN =
202       kWidth / kRangeBits + (kWidth % kRangeBits != 0);
203   static constexpr size_t kEstimateW0 = kWidth / kEstimateN;
204   static constexpr result_type kEstimateY0 = (kRange >> kEstimateW0)
205                                              << kEstimateW0;
206
207  public:
208   // Parameters for the two loops:
209   // kN0, kN1 are the number of underlying calls required for each loop.
210   // KW0, kW1 are shift widths for each loop.
211   //
212   static constexpr size_t kN1 = (kRange - kEstimateY0) >
213                                         (kEstimateY0 / kEstimateN)
214                                     ? kEstimateN + 1
215                                     : kEstimateN;
216   static constexpr size_t kN0 = kN1 - (kWidth % kN1);
217   static constexpr size_t kW0 = kWidth / kN1;
218   static constexpr size_t kW1 = kW0 + 1;
219
220   static constexpr result_type kM0 = (result_type(1) << kW0) - 1;
221   static constexpr result_type kM1 = (result_type(1) << kW1) - 1;
222
223   static_assert(
224       kW0 <= kRangeBits,
225       "Class-template FastUniformBitsLoopingConstants::kW0 too large.");
226
227   static_assert(
228       kW0 > 0,
229       "Class-template FastUniformBitsLoopingConstants::kW0 too small.");
230 };
231
232 template <typename UIntType, size_t Width>
233 template <typename URBG>
234 typename FastUniformBits<UIntType, Width>::result_type
235 FastUniformBits<UIntType, Width>::operator()(
236     URBG& g) {  // NOLINT(runtime/references)
237   using constants = FastUniformBitsURBGConstants<URBG>;
238   return Generate(
239       g, std::integral_constant<bool, constants::kRangeMask >= (max)()>{});
240 }
241
242 template <typename UIntType, size_t Width>
243 template <typename URBG>
244 typename URBG::result_type FastUniformBits<UIntType, Width>::Variate(
245     URBG& g) {  // NOLINT(runtime/references)
246   using constants = FastUniformBitsURBGConstants<URBG>;
247   if (constants::kPowerOfTwo) {
248     return g() - (URBG::min)();
249   }
250
251   // Use rejection sampling to ensure uniformity across the range.
252   typename URBG::result_type u;
253   do {
254     u = g() - (URBG::min)();
255   } while (u > constants::kRangeMask);
256   return u;
257 }
258
259 template <typename UIntType, size_t Width>
260 template <typename URBG>
261 typename FastUniformBits<UIntType, Width>::result_type
262 FastUniformBits<UIntType, Width>::Generate(
263     URBG& g,  // NOLINT(runtime/references)
264     std::true_type /* avoid_looping */) {
265   // The width of the result_type is less than than the width of the random bits
266   // provided by URNG.  Thus, generate a single value and then simply mask off
267   // the required bits.
268   return Variate(g) & (max)();
269 }
270
271 template <typename UIntType, size_t Width>
272 template <typename URBG>
273 typename FastUniformBits<UIntType, Width>::result_type
274 FastUniformBits<UIntType, Width>::Generate(
275     URBG& g,  // NOLINT(runtime/references)
276     std::false_type /* avoid_looping */) {
277   // The width of the result_type is wider than the number of random bits
278   // provided by URNG. Thus we merge several variates of URNG into the result
279   // using a shift and mask.  The constants type generates the parameters used
280   // ensure that the bits are distributed across all the invocations of the
281   // underlying URNG.
282   using constants = FastUniformBitsLoopingConstants<UIntType, Width, URBG>;
283
284   result_type s = 0;
285   for (size_t n = 0; n < constants::kN0; ++n) {
286     auto u = Variate(g);
287     s = (s << constants::kW0) + (u & constants::kM0);
288   }
289   for (size_t n = constants::kN0; n < constants::kN1; ++n) {
290     auto u = Variate(g);
291     s = (s << constants::kW1) + (u & constants::kM1);
292   }
293   return s;
294 }
295
296 }  // namespace random_internal
297 }  // namespace absl
298
299 #endif  // ABSL_RANDOM_INTERNAL_FAST_UNIFORM_BITS_H_