Add Download.ShowDangerousDownloadConfirmationPrompt for Windows/CrOS
[chromium-blink-merge.git] / base / rand_util.cc
blob9641ff4f9c7c4ffe87aa5c7af7f9918d498799c4
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.
5 #include "base/rand_util.h"
7 #include <math.h>
9 #include <algorithm>
10 #include <limits>
12 #include "base/basictypes.h"
13 #include "base/logging.h"
14 #include "base/strings/string_util.h"
16 namespace base {
18 int RandInt(int min, int max) {
19 DCHECK_LE(min, max);
21 uint64 range = static_cast<uint64>(max) - min + 1;
22 int result = min + static_cast<int>(base::RandGenerator(range));
23 DCHECK_GE(result, min);
24 DCHECK_LE(result, max);
25 return result;
28 double RandDouble() {
29 return BitsToOpenEndedUnitInterval(base::RandUint64());
32 double BitsToOpenEndedUnitInterval(uint64 bits) {
33 // We try to get maximum precision by masking out as many bits as will fit
34 // in the target type's mantissa, and raising it to an appropriate power to
35 // produce output in the range [0, 1). For IEEE 754 doubles, the mantissa
36 // is expected to accommodate 53 bits.
38 COMPILE_ASSERT(std::numeric_limits<double>::radix == 2, otherwise_use_scalbn);
39 static const int kBits = std::numeric_limits<double>::digits;
40 uint64 random_bits = bits & ((GG_UINT64_C(1) << kBits) - 1);
41 double result = ldexp(static_cast<double>(random_bits), -1 * kBits);
42 DCHECK_GE(result, 0.0);
43 DCHECK_LT(result, 1.0);
44 return result;
47 uint64 RandGenerator(uint64 range) {
48 DCHECK_GT(range, 0u);
49 // We must discard random results above this number, as they would
50 // make the random generator non-uniform (consider e.g. if
51 // MAX_UINT64 was 7 and |range| was 5, then a result of 1 would be twice
52 // as likely as a result of 3 or 4).
53 uint64 max_acceptable_value =
54 (std::numeric_limits<uint64>::max() / range) * range - 1;
56 uint64 value;
57 do {
58 value = base::RandUint64();
59 } while (value > max_acceptable_value);
61 return value % range;
64 void RandBytes(void* output, size_t output_length) {
65 uint64 random_int;
66 size_t random_int_size = sizeof(random_int);
67 for (size_t i = 0; i < output_length; i += random_int_size) {
68 random_int = base::RandUint64();
69 size_t copy_count = std::min(output_length - i, random_int_size);
70 memcpy(((uint8*)output) + i, &random_int, copy_count);
74 std::string RandBytesAsString(size_t length) {
75 DCHECK_GT(length, 0u);
76 std::string result;
77 RandBytes(WriteInto(&result, length + 1), length);
78 return result;
81 } // namespace base