1 // Copyright 2017 The Abseil Authors.
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
7 // https://www.apache.org/licenses/LICENSE-2.0
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.
15 #ifndef ABSL_RANDOM_INTERNAL_FAST_UNIFORM_BITS_H_
16 #define ABSL_RANDOM_INTERNAL_FAST_UNIFORM_BITS_H_
21 #include <type_traits>
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
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())
34 : (URBG::max)() - (URBG::min)() + result_type{1};
37 // FastUniformBits implements a fast path to acquire uniform independent bits
38 // from a type which conforms to the [rand.req.urbg] concept.
40 // `UIntType`: the result (output) type
41 // `Width`: binary output width
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 "
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");
60 static_assert(kWidth <= std::numeric_limits<UIntType>::digits,
61 "Class-template FastUniformBits<> Width argument must be <= "
62 "width of UIntType.");
64 static constexpr bool kIsMaxWidth =
65 (kWidth >= std::numeric_limits<UIntType>::digits);
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;
73 using result_type = UIntType;
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);
81 template <typename URBG>
82 result_type operator()(URBG& g); // NOLINT(runtime/references)
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)
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 */);
97 template <typename URBG>
98 result_type Generate(URBG& g, // NOLINT(runtime/references)
99 std::false_type /* avoid_looping */);
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.
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);
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;
123 using result_type = typename URBG::result_type;
125 // The range of the URNG, max - min + 1, or zero if that result would cause
127 static constexpr result_type kRange = constexpr_range<URBG>();
129 static constexpr bool kPowerOfTwo =
130 (kRange == 0) || ((kRange & (kRange - 1)) == 0);
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);
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);
146 static_assert((URBG::max)() != (URBG::min)(),
147 "Class-template FastUniformBitsURBGConstants<> "
148 "URBG::max and URBG::min may not be equal.");
150 static_assert(std::is_unsigned<result_type>::value,
151 "Class-template FastUniformBitsURBGConstants<> "
152 "URBG::result_type must be unsigned.");
154 static_assert(kRangeMask > 0,
155 "Class-template FastUniformBitsURBGConstants<> "
156 "URBG does not generate sufficient random bits.");
158 static_assert(kRange == 0 ||
159 kRangeBits < std::numeric_limits<result_type>::digits,
160 "Class-template FastUniformBitsURBGConstants<> "
161 "URBG range computation error.");
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.
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
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 {
183 static constexpr size_t kWidth = Width;
184 using urbg_result_type = typename URBG::result_type;
185 using uint_result_type = UIntType;
189 typename std::conditional<(sizeof(urbg_result_type) <=
190 sizeof(uint_result_type)),
191 uint_result_type, urbg_result_type>::type;
194 // Estimate N as ceil(width / urng width), and W0 as (width / N).
195 static constexpr size_t kRangeBits =
196 FastUniformBitsURBGConstants<URBG>::kRangeBits;
198 // The range of the URNG, max - min + 1, or zero if that result would cause
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)
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.
212 static constexpr size_t kN1 = (kRange - kEstimateY0) >
213 (kEstimateY0 / 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;
220 static constexpr result_type kM0 = (result_type(1) << kW0) - 1;
221 static constexpr result_type kM1 = (result_type(1) << kW1) - 1;
225 "Class-template FastUniformBitsLoopingConstants::kW0 too large.");
229 "Class-template FastUniformBitsLoopingConstants::kW0 too small.");
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>;
239 g, std::integral_constant<bool, constants::kRangeMask >= (max)()>{});
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)();
251 // Use rejection sampling to ensure uniformity across the range.
252 typename URBG::result_type u;
254 u = g() - (URBG::min)();
255 } while (u > constants::kRangeMask);
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)();
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
282 using constants = FastUniformBitsLoopingConstants<UIntType, Width, URBG>;
285 for (size_t n = 0; n < constants::kN0; ++n) {
287 s = (s << constants::kW0) + (u & constants::kM0);
289 for (size_t n = constants::kN0; n < constants::kN1; ++n) {
291 s = (s << constants::kW1) + (u & constants::kM1);
296 } // namespace random_internal
299 #endif // ABSL_RANDOM_INTERNAL_FAST_UNIFORM_BITS_H_