blob: b823fa095c98a2897be1a132bfdb21e2da7125df [file] [log] [blame]
[email protected]d7a93ad2011-04-22 13:13:071// Copyright (c) 2011 The Chromium Authors. All rights reserved.
[email protected]05f9b682008-09-29 22:18:012// 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 <math.h>
8
[email protected]94a0f312008-09-30 14:26:339#include <limits>
10
[email protected]05f9b682008-09-29 22:18:0111#include "base/basictypes.h"
12#include "base/logging.h"
13
[email protected]05f9b682008-09-29 22:18:0114namespace base {
15
16int RandInt(int min, int max) {
[email protected]d7a93ad2011-04-22 13:13:0717 DCHECK_LE(min, max);
[email protected]05f9b682008-09-29 22:18:0118
[email protected]a74dcae2010-08-30 21:07:0519 uint64 range = static_cast<uint64>(max) - min + 1;
20 int result = min + static_cast<int>(base::RandGenerator(range));
[email protected]e1be56d2011-05-04 01:29:3821 DCHECK_GE(result, min);
22 DCHECK_LE(result, max);
[email protected]05f9b682008-09-29 22:18:0123 return result;
24}
25
26double RandDouble() {
[email protected]780702c2011-05-05 02:22:1127 return BitsToOpenEndedUnitInterval(base::RandUint64());
28}
29
30double BitsToOpenEndedUnitInterval(uint64 bits) {
[email protected]94a0f312008-09-30 14:26:3331 // We try to get maximum precision by masking out as many bits as will fit
32 // in the target type's mantissa, and raising it to an appropriate power to
33 // produce output in the range [0, 1). For IEEE 754 doubles, the mantissa
34 // is expected to accommodate 53 bits.
[email protected]05f9b682008-09-29 22:18:0135
[email protected]94a0f312008-09-30 14:26:3336 COMPILE_ASSERT(std::numeric_limits<double>::radix == 2, otherwise_use_scalbn);
37 static const int kBits = std::numeric_limits<double>::digits;
[email protected]780702c2011-05-05 02:22:1138 uint64 random_bits = bits & ((GG_UINT64_C(1) << kBits) - 1);
[email protected]94a0f312008-09-30 14:26:3339 double result = ldexp(static_cast<double>(random_bits), -1 * kBits);
[email protected]e1be56d2011-05-04 01:29:3840 DCHECK_GE(result, 0.0);
41 DCHECK_LT(result, 1.0);
[email protected]05f9b682008-09-29 22:18:0142 return result;
43}
44
[email protected]a74dcae2010-08-30 21:07:0545uint64 RandGenerator(uint64 max) {
[email protected]88563f62011-03-13 22:13:3346 DCHECK_GT(max, 0ULL);
[email protected]a74dcae2010-08-30 21:07:0547 return base::RandUint64() % max;
48}
49
[email protected]29548d82011-04-29 21:03:5450std::string RandBytesAsString(size_t length) {
51 const size_t kBitsPerChar = 8;
52 const int kCharsPerInt64 = sizeof(uint64)/sizeof(char);
53
54 std::string result(length, '\0');
55 uint64 entropy = 0;
56 for (size_t i = 0; i < result.size(); ++i) {
57 if (i % kCharsPerInt64 == 0)
58 entropy = RandUint64();
59 result[i] = static_cast<char>(entropy);
60 entropy >>= kBitsPerChar;
61 }
62
63 return result;
64}
65
[email protected]05f9b682008-09-29 22:18:0166} // namespace base