random.h 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. // Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
  2. // This source code is licensed under both the GPLv2 (found in the
  3. // COPYING file in the root directory) and Apache 2.0 License
  4. // (found in the LICENSE.Apache file in the root directory).
  5. //
  6. // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
  7. // Use of this source code is governed by a BSD-style license that can be
  8. // found in the LICENSE file. See the AUTHORS file for names of contributors.
  9. #pragma once
  10. #include <stdint.h>
  11. #include <algorithm>
  12. #include <random>
  13. #include "rocksdb/rocksdb_namespace.h"
  14. namespace ROCKSDB_NAMESPACE {
  15. // A very simple random number generator. Not especially good at
  16. // generating truly random bits, but good enough for our needs in this
  17. // package.
  18. class Random {
  19. private:
  20. enum : uint32_t {
  21. M = 2147483647L // 2^31-1
  22. };
  23. enum : uint64_t {
  24. A = 16807 // bits 14, 8, 7, 5, 2, 1, 0
  25. };
  26. uint32_t seed_;
  27. static uint32_t GoodSeed(uint32_t s) { return (s & M) != 0 ? (s & M) : 1; }
  28. public:
  29. // This is the largest value that can be returned from Next()
  30. enum : uint32_t { kMaxNext = M };
  31. explicit Random(uint32_t s) : seed_(GoodSeed(s)) {}
  32. void Reset(uint32_t s) { seed_ = GoodSeed(s); }
  33. uint32_t Next() {
  34. // We are computing
  35. // seed_ = (seed_ * A) % M, where M = 2^31-1
  36. //
  37. // seed_ must not be zero or M, or else all subsequent computed values
  38. // will be zero or M respectively. For all other values, seed_ will end
  39. // up cycling through every number in [1,M-1]
  40. uint64_t product = seed_ * A;
  41. // Compute (product % M) using the fact that ((x << 31) % M) == x.
  42. seed_ = static_cast<uint32_t>((product >> 31) + (product & M));
  43. // The first reduction may overflow by 1 bit, so we may need to
  44. // repeat. mod == M is not possible; using > allows the faster
  45. // sign-bit-based test.
  46. if (seed_ > M) {
  47. seed_ -= M;
  48. }
  49. return seed_;
  50. }
  51. uint64_t Next64() { return (uint64_t{Next()} << 32) | Next(); }
  52. // Returns a uniformly distributed value in the range [0..n-1]
  53. // REQUIRES: n > 0
  54. uint32_t Uniform(int n) { return Next() % n; }
  55. // Randomly returns true ~"1/n" of the time, and false otherwise.
  56. // REQUIRES: n > 0
  57. bool OneIn(int n) { return Uniform(n) == 0; }
  58. // "Optional" one-in-n, where 0 or negative always returns false
  59. // (may or may not consume a random value)
  60. bool OneInOpt(int n) { return n > 0 && OneIn(n); }
  61. // Returns random bool that is true for the given percentage of
  62. // calls on average. Zero or less is always false and 100 or more
  63. // is always true (may or may not consume a random value)
  64. bool PercentTrue(int percentage) {
  65. return static_cast<int>(Uniform(100)) < percentage;
  66. }
  67. // Skewed: pick "base" uniformly from range [0,max_log] and then
  68. // return "base" random bits. The effect is to pick a number in the
  69. // range [0,2^max_log-1] with exponential bias towards smaller numbers.
  70. uint32_t Skewed(int max_log) { return Uniform(1 << Uniform(max_log + 1)); }
  71. // Returns a random string of length "len"
  72. std::string RandomString(int len);
  73. // Generates a random string of len bytes using human-readable characters
  74. std::string HumanReadableString(int len);
  75. // Generates a random binary data
  76. std::string RandomBinaryString(int len);
  77. // Returns a Random instance for use by the current thread without
  78. // additional locking
  79. static Random* GetTLSInstance();
  80. };
  81. // A good 32-bit random number generator based on std::mt19937.
  82. // This exists in part to avoid compiler variance in warning about coercing
  83. // uint_fast32_t from mt19937 to uint32_t.
  84. class Random32 {
  85. private:
  86. std::mt19937 generator_;
  87. public:
  88. explicit Random32(uint32_t s) : generator_(s) {}
  89. // Generates the next random number
  90. uint32_t Next() { return static_cast<uint32_t>(generator_()); }
  91. // Returns a uniformly distributed value in the range [0..n-1]
  92. // REQUIRES: n > 0
  93. uint32_t Uniform(uint32_t n) {
  94. return static_cast<uint32_t>(
  95. std::uniform_int_distribution<std::mt19937::result_type>(
  96. 0, n - 1)(generator_));
  97. }
  98. // Returns an *almost* uniformly distributed value in the range [0..n-1].
  99. // Much faster than Uniform().
  100. // REQUIRES: n > 0
  101. uint32_t Uniformish(uint32_t n) {
  102. // fastrange (without the header)
  103. return static_cast<uint32_t>((uint64_t(generator_()) * uint64_t(n)) >> 32);
  104. }
  105. // Randomly returns true ~"1/n" of the time, and false otherwise.
  106. // REQUIRES: n > 0
  107. bool OneIn(uint32_t n) { return Uniform(n) == 0; }
  108. // Skewed: pick "base" uniformly from range [0,max_log] and then
  109. // return "base" random bits. The effect is to pick a number in the
  110. // range [0,2^max_log-1] with exponential bias towards smaller numbers.
  111. uint32_t Skewed(int max_log) {
  112. return Uniform(uint32_t{1} << Uniform(max_log + 1));
  113. }
  114. // Reset the seed of the generator to the given value
  115. void Seed(uint32_t new_seed) { generator_.seed(new_seed); }
  116. };
  117. // A good 64-bit random number generator based on std::mt19937_64
  118. class Random64 {
  119. private:
  120. std::mt19937_64 generator_;
  121. public:
  122. explicit Random64(uint64_t s) : generator_(s) {}
  123. // Generates the next random number
  124. uint64_t Next() { return generator_(); }
  125. // Returns a uniformly distributed value in the range [0..n-1]
  126. // REQUIRES: n > 0
  127. uint64_t Uniform(uint64_t n) {
  128. return std::uniform_int_distribution<uint64_t>(0, n - 1)(generator_);
  129. }
  130. // Randomly returns true ~"1/n" of the time, and false otherwise.
  131. // REQUIRES: n > 0
  132. bool OneIn(uint64_t n) { return Uniform(n) == 0; }
  133. // Skewed: pick "base" uniformly from range [0,max_log] and then
  134. // return "base" random bits. The effect is to pick a number in the
  135. // range [0,2^max_log-1] with exponential bias towards smaller numbers.
  136. uint64_t Skewed(int max_log) {
  137. return Uniform(uint64_t(1) << Uniform(max_log + 1));
  138. }
  139. };
  140. // A seeded replacement for removed std::random_shuffle
  141. template <class RandomIt>
  142. void RandomShuffle(RandomIt first, RandomIt last, uint32_t seed) {
  143. std::mt19937 rng(seed);
  144. std::shuffle(first, last, rng);
  145. }
  146. // A replacement for removed std::random_shuffle
  147. template <class RandomIt>
  148. void RandomShuffle(RandomIt first, RandomIt last) {
  149. RandomShuffle(first, last, std::random_device{}());
  150. }
  151. } // namespace ROCKSDB_NAMESPACE