Random number generator utilities for folly
[folly.git] / folly / Random.h
1 /*
2  * Copyright 2014 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #ifndef FOLLY_BASE_RANDOM_H_
18 #define FOLLY_BASE_RANDOM_H_
19
20 #include <stdint.h>
21 #include "folly/ThreadLocal.h"
22
23 namespace folly {
24
25 /*
26  * Return a good seed for a random number generator.
27  */
28 uint32_t randomNumberSeed();
29
30 class Random;
31
32 /**
33  * A PRNG with one instance per thread. This PRNG uses a mersenne twister random
34  * number generator and is seeded from /dev/urandom. It should not be used for
35  * anything which requires security, only for statistical randomness.
36  *
37  * An instance of this class represents the current threads PRNG. This means
38  * copying an instance of this class across threads will result in corruption
39  *
40  * Most users will use the Random class which implicitly creates this class.
41  * However, if you are worried about performance, you can memoize the TLS
42  * lookups that get the per thread state by manually using this class:
43  *
44  * ThreadLocalPRNG rng = Random::threadLocalPRNG()
45  * for (...) {
46  *   Random::rand32(rng);
47  * }
48  */
49 class ThreadLocalPRNG {
50  public:
51   typedef uint32_t result_type;
52
53   uint32_t operator()() {
54     // Using a static method allows the compiler to avoid allocating stack space
55     // for this class.
56     return getImpl(local_);
57   }
58
59   static constexpr result_type min() {
60     return std::numeric_limits<result_type>::min();
61   }
62   static constexpr result_type max() {
63     return std::numeric_limits<result_type>::max();
64   }
65   friend class Random;
66
67   ThreadLocalPRNG() {
68     local_ = localInstance.get();
69     if (!local_) {
70       local_ = initLocal();
71     }
72   }
73
74  private:
75   class LocalInstancePRNG;
76   static LocalInstancePRNG* initLocal();
77   static folly::ThreadLocalPtr<ThreadLocalPRNG::LocalInstancePRNG>
78     localInstance;
79
80   static result_type getImpl(LocalInstancePRNG* local);
81   LocalInstancePRNG* local_;
82 };
83
84
85
86 class Random {
87
88  private:
89   template<class RNG>
90   using ValidRNG = typename std::enable_if<
91    std::is_unsigned<typename std::result_of<RNG&()>::type>::value,
92    RNG>::type;
93
94  public:
95
96   /**
97    * Returns a random uint32_t
98    */
99   template<class RNG = ThreadLocalPRNG>
100   static uint32_t rand32(ValidRNG<RNG>  rrng = RNG()) {
101     uint32_t r = rrng.operator()();
102     return r;
103   }
104
105   /**
106    * Returns a random uint32_t in [0, max). If max == 0, returns 0.
107    */
108   template<class RNG = ThreadLocalPRNG>
109   static uint32_t rand32(uint32_t max, ValidRNG<RNG> rng = RNG()) {
110     if (max == 0) {
111       return 0;
112     }
113
114     return std::uniform_int_distribution<uint32_t>(0, max - 1)(rng);
115   }
116
117   /**
118    * Returns a random uint64_t
119    */
120   template<class RNG = ThreadLocalPRNG>
121   static uint64_t rand64(ValidRNG<RNG> rng = RNG()) {
122     return ((uint64_t) rng() << 32) | rng();
123   }
124
125   /**
126    * Returns a random uint64_t in [0, max). If max == 0, returns 0.
127    */
128   template<class RNG = ThreadLocalPRNG>
129   static uint64_t rand64(uint64_t max, ValidRNG<RNG> rng = RNG()) {
130     if (max == 0) {
131       return 0;
132     }
133
134     return std::uniform_int_distribution<uint64_t>(0, max - 1)(rng);
135   }
136
137   /**
138    * Returns true 1/n of the time. If n == 0, always returns false
139    */
140   template<class RNG = ThreadLocalPRNG>
141   static bool oneIn(uint32_t n, ValidRNG<RNG> rng = RNG()) {
142     if (n == 0) {
143       return false;
144     }
145
146     return rand32(n, rng) == 0;
147   }
148
149   /**
150    * Returns a double in [0, 1)
151    */
152   template<class RNG = ThreadLocalPRNG>
153   static double randDouble01(ValidRNG<RNG> rng = RNG()) {
154     return std::generate_canonical<double, std::numeric_limits<double>::digits>
155       (rng);
156   }
157
158 };
159
160 }
161
162 #endif