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