• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "base/rand_util.h"
6 
7 #include <limits.h>
8 #include <math.h>
9 #include <stdint.h>
10 
11 #include <algorithm>
12 #include <limits>
13 
14 #include "base/logging.h"
15 #include "base/strings/string_util.h"
16 
17 namespace base {
18 
RandInt(int min,int max)19 int RandInt(int min, int max) {
20   DCHECK_LE(min, max);
21 
22   uint64_t range = static_cast<uint64_t>(max) - min + 1;
23   // |range| is at most UINT_MAX + 1, so the result of RandGenerator(range)
24   // is at most UINT_MAX.  Hence it's safe to cast it from uint64_t to int64_t.
25   int result =
26       static_cast<int>(min + static_cast<int64_t>(base::RandGenerator(range)));
27   DCHECK_GE(result, min);
28   DCHECK_LE(result, max);
29   return result;
30 }
31 
RandDouble()32 double RandDouble() {
33   return BitsToOpenEndedUnitInterval(base::RandUint64());
34 }
35 
BitsToOpenEndedUnitInterval(uint64_t bits)36 double BitsToOpenEndedUnitInterval(uint64_t bits) {
37   // We try to get maximum precision by masking out as many bits as will fit
38   // in the target type's mantissa, and raising it to an appropriate power to
39   // produce output in the range [0, 1).  For IEEE 754 doubles, the mantissa
40   // is expected to accommodate 53 bits.
41 
42   static_assert(std::numeric_limits<double>::radix == 2,
43                 "otherwise use scalbn");
44   static const int kBits = std::numeric_limits<double>::digits;
45   uint64_t random_bits = bits & ((UINT64_C(1) << kBits) - 1);
46   double result = ldexp(static_cast<double>(random_bits), -1 * kBits);
47   DCHECK_GE(result, 0.0);
48   DCHECK_LT(result, 1.0);
49   return result;
50 }
51 
RandGenerator(uint64_t range)52 uint64_t RandGenerator(uint64_t range) {
53   DCHECK_GT(range, 0u);
54   // We must discard random results above this number, as they would
55   // make the random generator non-uniform (consider e.g. if
56   // MAX_UINT64 was 7 and |range| was 5, then a result of 1 would be twice
57   // as likely as a result of 3 or 4).
58   uint64_t max_acceptable_value =
59       (std::numeric_limits<uint64_t>::max() / range) * range - 1;
60 
61   uint64_t value;
62   do {
63     value = base::RandUint64();
64   } while (value > max_acceptable_value);
65 
66   return value % range;
67 }
68 
RandBytesAsString(size_t length)69 std::string RandBytesAsString(size_t length) {
70   DCHECK_GT(length, 0u);
71   std::string result;
72   RandBytes(WriteInto(&result, length + 1), length);
73   return result;
74 }
75 
76 }  // namespace base
77