Replace random_device/mt19937 with folly/Random
authorShuo Li <shuoli@fb.com>
Tue, 4 Mar 2014 19:55:59 +0000 (11:55 -0800)
committerDave Watson <davejwatson@fb.com>
Mon, 10 Mar 2014 20:50:27 +0000 (13:50 -0700)
Summary: Replace random_device/mt19937 with folly/Random to increase hygiene of using Random

Test Plan:
For each file is changed, fbmake -opt is run; except one file: stealing_test.cc, since the TARGETS file is not under the path.
All fbmake are successfully passing

Reviewed By: bmaurer@fb.com

FB internal diff: D1199483

Blame Revision: v1

folly/Random.h

index f5874188c9a32497fe7fa87932d4e591867e1086..d10f2d645472d24ae0dc2c7c6ad4449f15c2b85b 100644 (file)
@@ -114,6 +114,20 @@ class Random {
     return std::uniform_int_distribution<uint32_t>(0, max - 1)(rng);
   }
 
+  /**
+   * Returns a random uint32_t in [min, max). If min == max, returns 0.
+   */
+  template<class RNG = ThreadLocalPRNG>
+  static uint32_t rand32(uint32_t min,
+                         uint32_t max,
+                         ValidRNG<RNG> rng = RNG()) {
+    if (min == max) {
+      return 0;
+    }
+
+    return std::uniform_int_distribution<uint32_t>(min, max - 1)(rng);
+  }
+
   /**
    * Returns a random uint64_t
    */
@@ -134,6 +148,20 @@ class Random {
     return std::uniform_int_distribution<uint64_t>(0, max - 1)(rng);
   }
 
+  /**
+   * Returns a random uint64_t in [min, max). If min == max, returns 0.
+   */
+  template<class RNG = ThreadLocalPRNG>
+  static uint64_t rand64(uint64_t min,
+                         uint64_t max,
+                         ValidRNG<RNG> rng = RNG()) {
+    if (min == max) {
+      return 0;
+    }
+
+    return std::uniform_int_distribution<uint64_t>(min, max - 1)(rng);
+  }
+
   /**
    * Returns true 1/n of the time. If n == 0, always returns false
    */
@@ -155,6 +183,17 @@ class Random {
       (rng);
   }
 
+  /**
+    * Returns a double in [min, max), if min == max, returns 0.
+    */
+  template<class RNG = ThreadLocalPRNG>
+  static double randDouble(double min, double max, ValidRNG<RNG> rng = RNG()) {
+    if (std::fabs(max - min) < std::numeric_limits<double>::epsilon()) {
+      return 0;
+    }
+    return std::uniform_real_distribution<double>(min, max)(rng);
+  }
+
 };
 
 }