| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| #ifndef ABSL_RANDOM_INTERNAL_POOL_URBG_H_ |
| #define ABSL_RANDOM_INTERNAL_POOL_URBG_H_ |
|
|
| #include <cinttypes> |
| #include <limits> |
|
|
| #include "absl/random/internal/traits.h" |
| #include "absl/types/span.h" |
|
|
| namespace absl { |
| ABSL_NAMESPACE_BEGIN |
| namespace random_internal { |
|
|
| |
| |
| |
| |
| template <typename T> |
| class RandenPool { |
| public: |
| using result_type = T; |
| static_assert(std::is_unsigned<result_type>::value, |
| "RandenPool template argument must be a built-in unsigned " |
| "integer type"); |
|
|
| static constexpr result_type(min)() { |
| return (std::numeric_limits<result_type>::min)(); |
| } |
|
|
| static constexpr result_type(max)() { |
| return (std::numeric_limits<result_type>::max)(); |
| } |
|
|
| RandenPool() {} |
|
|
| |
| inline result_type operator()() { return Generate(); } |
|
|
| |
| static void Fill(absl::Span<result_type> data); |
|
|
| protected: |
| |
| static result_type Generate(); |
| }; |
|
|
| extern template class RandenPool<uint8_t>; |
| extern template class RandenPool<uint16_t>; |
| extern template class RandenPool<uint32_t>; |
| extern template class RandenPool<uint64_t>; |
|
|
| |
| |
| |
| template <typename T, size_t kBufferSize> |
| class PoolURBG { |
| |
| using unsigned_type = typename make_unsigned_bits<T>::type; |
| using PoolType = RandenPool<unsigned_type>; |
| using SpanType = absl::Span<unsigned_type>; |
|
|
| static constexpr size_t kInitialBuffer = kBufferSize + 1; |
| static constexpr size_t kHalfBuffer = kBufferSize / 2; |
|
|
| public: |
| using result_type = T; |
|
|
| static_assert(std::is_unsigned<result_type>::value, |
| "PoolURBG must be parameterized by an unsigned integer type"); |
|
|
| static_assert(kBufferSize > 1, |
| "PoolURBG must be parameterized by a buffer-size > 1"); |
|
|
| static_assert(kBufferSize <= 256, |
| "PoolURBG must be parameterized by a buffer-size <= 256"); |
|
|
| static constexpr result_type(min)() { |
| return (std::numeric_limits<result_type>::min)(); |
| } |
|
|
| static constexpr result_type(max)() { |
| return (std::numeric_limits<result_type>::max)(); |
| } |
|
|
| PoolURBG() : next_(kInitialBuffer) {} |
|
|
| |
| PoolURBG(const PoolURBG&) : next_(kInitialBuffer) {} |
| const PoolURBG& operator=(const PoolURBG&) { |
| next_ = kInitialBuffer; |
| return *this; |
| } |
|
|
| |
| PoolURBG(PoolURBG&&) = default; |
| PoolURBG& operator=(PoolURBG&&) = default; |
|
|
| inline result_type operator()() { |
| if (next_ >= kBufferSize) { |
| next_ = (kBufferSize > 2 && next_ > kBufferSize) ? kHalfBuffer : 0; |
| PoolType::Fill(SpanType(reinterpret_cast<unsigned_type*>(state_ + next_), |
| kBufferSize - next_)); |
| } |
| return state_[next_++]; |
| } |
|
|
| private: |
| |
| size_t next_; |
| result_type state_[kBufferSize]; |
| }; |
|
|
| } |
| ABSL_NAMESPACE_END |
| } |
|
|
| #endif |
|
|