summaryrefslogtreecommitdiff
path: root/absl/random/internal/fast_uniform_bits.h
blob: 184a2708b2af5daee03a8b26cd282d9ad8ac354b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
// Copyright 2017 The Abseil Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef ABSL_RANDOM_INTERNAL_FAST_UNIFORM_BITS_H_
#define ABSL_RANDOM_INTERNAL_FAST_UNIFORM_BITS_H_

#include <cstddef>
#include <cstdint>
#include <limits>
#include <type_traits>

namespace absl {
namespace random_internal {
// Computes the length of the range of values producible by the URBG, or returns
// zero if that would encompass the entire range of representable values in
// URBG::result_type.
template <typename URBG>
constexpr typename URBG::result_type constexpr_range() {
  using result_type = typename URBG::result_type;
  return ((URBG::max)() == (std::numeric_limits<result_type>::max)() &&
          (URBG::min)() == std::numeric_limits<result_type>::lowest())
             ? result_type{0}
             : (URBG::max)() - (URBG::min)() + result_type{1};
}

// FastUniformBits implements a fast path to acquire uniform independent bits
// from a type which conforms to the [rand.req.urbg] concept.
// Parameterized by:
//  `UIntType`: the result (output) type
//
// The std::independent_bits_engine [rand.adapt.ibits] adaptor can be
// instantiated from an existing generator through a copy or a move. It does
// not, however, facilitate the production of pseudorandom bits from an un-owned
// generator that will outlive the std::independent_bits_engine instance.
template <typename UIntType = uint64_t>
class FastUniformBits {
  static_assert(std::is_unsigned<UIntType>::value,
                "Class-template FastUniformBits<> must be parameterized using "
                "an unsigned type.");

  // `kWidth` is the width, in binary digits, of the output. By default it is
  // the number of binary digits in the `result_type`.
  static constexpr size_t kWidth = std::numeric_limits<UIntType>::digits;

 public:
  using result_type = UIntType;

  static constexpr result_type(min)() { return 0; }
  static constexpr result_type(max)() {
    return (std::numeric_limits<result_type>::max)();
  }

  template <typename URBG>
  result_type operator()(URBG& g);  // NOLINT(runtime/references)

 private:
  // Variate() generates a single random variate, always returning a value
  // in the closed interval [0 ... FastUniformBitsURBGConstants::kRangeMask]
  // (kRangeMask+1 is a power of 2).
  template <typename URBG>
  typename URBG::result_type Variate(URBG& g);  // NOLINT(runtime/references)

  // generate() generates a random value, dispatched on whether
  // the underlying URNG must loop over multiple calls or not.
  template <typename URBG>
  result_type Generate(URBG& g,  // NOLINT(runtime/references)
                       std::true_type /* avoid_looping */);

  template <typename URBG>
  result_type Generate(URBG& g,  // NOLINT(runtime/references)
                       std::false_type /* avoid_looping */);
};

// FastUniformBitsURBGConstants computes the URBG-derived constants used
// by FastUniformBits::Generate and FastUniformBits::Variate.
// Parameterized by the FastUniformBits parameter:
//   `URBG`: The underlying UniformRandomNumberGenerator.
//
// The values here indicate the URBG range as well as providing an indicator
// whether the URBG output is a power of 2, and kRangeMask, which allows masking
// the generated output to kRangeBits.
template <typename URBG>
class FastUniformBitsURBGConstants {
  // Computes the floor of the log. (i.e., std::floor(std::log2(N));
  static constexpr size_t constexpr_log2(size_t n) {
    return (n <= 1) ? 0 : 1 + constexpr_log2(n / 2);
  }

  // Computes a mask of n bits for the URBG::result_type.
  static constexpr typename URBG::result_type constexpr_mask(size_t n) {
    return (typename URBG::result_type(1) << n) - 1;
  }

 public:
  using result_type = typename URBG::result_type;

  // The range of the URNG, max - min + 1, or zero if that result would cause
  // overflow.
  static constexpr result_type kRange = constexpr_range<URBG>();

  static constexpr bool kPowerOfTwo =
      (kRange == 0) || ((kRange & (kRange - 1)) == 0);

  // kRangeBits describes the number number of bits suitable to mask off of URNG
  // variate, which is:
  // kRangeBits = floor(log2(kRange))
  static constexpr size_t kRangeBits =
      kRange == 0 ? std::numeric_limits<result_type>::digits
                  : constexpr_log2(kRange);

  // kRangeMask is the mask used when sampling variates from the URNG when the
  // width of the URNG range is not a power of 2.
  // Y = (2 ^ kRange) - 1
  static constexpr result_type kRangeMask =
      kRange == 0 ? (std::numeric_limits<result_type>::max)()
                  : constexpr_mask(kRangeBits);

  static_assert((URBG::max)() != (URBG::min)(),
                "Class-template FastUniformBitsURBGConstants<> "
                "URBG::max and URBG::min may not be equal.");

  static_assert(std::is_unsigned<result_type>::value,
                "Class-template FastUniformBitsURBGConstants<> "
                "URBG::result_type must be unsigned.");

  static_assert(kRangeMask > 0,
                "Class-template FastUniformBitsURBGConstants<> "
                "URBG does not generate sufficient random bits.");

  static_assert(kRange == 0 ||
                    kRangeBits < std::numeric_limits<result_type>::digits,
                "Class-template FastUniformBitsURBGConstants<> "
                "URBG range computation error.");
};

// FastUniformBitsLoopingConstants computes the looping constants used
// by FastUniformBits::Generate. These constants indicate how multiple
// URBG::result_type values are combined into an output_value.
// Parameterized by the FastUniformBits parameters:
//  `UIntType`: output type.
//  `URNG`: The underlying UniformRandomNumberGenerator.
//
// The looping constants describe the sets of loop counters and mask values
// which control how individual variates are combined the final output.  The
// algorithm ensures that the number of bits used by any individual call differs
// by at-most one bit from any other call. This is simplified into constants
// which describe two loops, with the second loop parameters providing one extra
// bit per variate.
//
// See [rand.adapt.ibits] for more details on the use of these constants.
template <typename UIntType, typename URBG>
class FastUniformBitsLoopingConstants {
 private:
  static constexpr size_t kWidth = std::numeric_limits<UIntType>::digits;
  using urbg_result_type = typename URBG::result_type;
  using uint_result_type = UIntType;

 public:
  using result_type =
      typename std::conditional<(sizeof(urbg_result_type) <=
                                 sizeof(uint_result_type)),
                                uint_result_type, urbg_result_type>::type;

 private:
  // Estimate N as ceil(width / urng width), and W0 as (width / N).
  static constexpr size_t kRangeBits =
      FastUniformBitsURBGConstants<URBG>::kRangeBits;

  // The range of the URNG, max - min + 1, or zero if that result would cause
  // overflow.
  static constexpr result_type kRange = constexpr_range<URBG>();
  static constexpr size_t kEstimateN =
      kWidth / kRangeBits + (kWidth % kRangeBits != 0);
  static constexpr size_t kEstimateW0 = kWidth / kEstimateN;
  static constexpr result_type kEstimateY0 = (kRange >> kEstimateW0)
                                             << kEstimateW0;

 public:
  // Parameters for the two loops:
  // kN0, kN1 are the number of underlying calls required for each loop.
  // KW0, kW1 are shift widths for each loop.
  //
  static constexpr size_t kN1 = (kRange - kEstimateY0) >
                                        (kEstimateY0 / kEstimateN)
                                    ? kEstimateN + 1
                                    : kEstimateN;
  static constexpr size_t kN0 = kN1 - (kWidth % kN1);
  static constexpr size_t kW0 = kWidth / kN1;
  static constexpr size_t kW1 = kW0 + 1;

  static constexpr result_type kM0 = (result_type(1) << kW0) - 1;
  static constexpr result_type kM1 = (result_type(1) << kW1) - 1;

  static_assert(
      kW0 <= kRangeBits,
      "Class-template FastUniformBitsLoopingConstants::kW0 too large.");

  static_assert(
      kW0 > 0,
      "Class-template FastUniformBitsLoopingConstants::kW0 too small.");
};

template <typename UIntType>
template <typename URBG>
typename FastUniformBits<UIntType>::result_type
FastUniformBits<UIntType>::operator()(
    URBG& g) {  // NOLINT(runtime/references)
  using constants = FastUniformBitsURBGConstants<URBG>;
  return Generate(
      g, std::integral_constant<bool, constants::kRangeMask >= (max)()>{});
}

template <typename UIntType>
template <typename URBG>
typename URBG::result_type FastUniformBits<UIntType>::Variate(
    URBG& g) {  // NOLINT(runtime/references)
  using constants = FastUniformBitsURBGConstants<URBG>;
  if (constants::kPowerOfTwo) {
    return g() - (URBG::min)();
  }

  // Use rejection sampling to ensure uniformity across the range.
  typename URBG::result_type u;
  do {
    u = g() - (URBG::min)();
  } while (u > constants::kRangeMask);
  return u;
}

template <typename UIntType>
template <typename URBG>
typename FastUniformBits<UIntType>::result_type
FastUniformBits<UIntType>::Generate(
    URBG& g,  // NOLINT(runtime/references)
    std::true_type /* avoid_looping */) {
  // The width of the result_type is less than than the width of the random bits
  // provided by URNG.  Thus, generate a single value and then simply mask off
  // the required bits.
  return Variate(g) & (max)();
}

template <typename UIntType>
template <typename URBG>
typename FastUniformBits<UIntType>::result_type
FastUniformBits<UIntType>::Generate(
    URBG& g,  // NOLINT(runtime/references)
    std::false_type /* avoid_looping */) {
  // The width of the result_type is wider than the number of random bits
  // provided by URNG. Thus we merge several variates of URNG into the result
  // using a shift and mask.  The constants type generates the parameters used
  // ensure that the bits are distributed across all the invocations of the
  // underlying URNG.
  using constants = FastUniformBitsLoopingConstants<UIntType, URBG>;

  result_type s = 0;
  for (size_t n = 0; n < constants::kN0; ++n) {
    auto u = Variate(g);
    s = (s << constants::kW0) + (u & constants::kM0);
  }
  for (size_t n = constants::kN0; n < constants::kN1; ++n) {
    auto u = Variate(g);
    s = (s << constants::kW1) + (u & constants::kM1);
  }
  return s;
}

}  // namespace random_internal
}  // namespace absl

#endif  // ABSL_RANDOM_INTERNAL_FAST_UNIFORM_BITS_H_