Chromium Code Reviews| OLD | NEW |
|---|---|
| 1 // Copyright (c) 2011 The Chromium Authors. All rights reserved. | 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 | 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. | 3 // found in the LICENSE file. |
| 4 | 4 |
| 5 #include "base/rand_util.h" | 5 #include "base/rand_util.h" |
| 6 | 6 |
| 7 #include <math.h> | 7 #include <math.h> |
| 8 #include <stdint.h> | 8 #include <stdint.h> |
| 9 | 9 |
| 10 #include <algorithm> | 10 #include <algorithm> |
| 11 #include <limits> | 11 #include <limits> |
| 12 | 12 |
| 13 #include "base/basictypes.h" | 13 #include "base/basictypes.h" |
| 14 #include "base/logging.h" | 14 #include "base/logging.h" |
| 15 #include "base/strings/string_util.h" | 15 #include "base/strings/string_util.h" |
| 16 | 16 |
| 17 namespace base { | 17 namespace base { |
| 18 | 18 |
| 19 int RandInt(int min, int max) { | 19 int RandInt(int min, int max) { |
| 20 DCHECK_LE(min, max); | 20 DCHECK_LE(min, max); |
| 21 | 21 |
| 22 uint64 range = static_cast<uint64>(max) - min + 1; | 22 uint64 range = static_cast<uint64>(max) - min + 1; |
| 23 int result = min + static_cast<int>(base::RandGenerator(range)); | 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 to int64. | |
| 25 int result = | |
| 26 static_cast<int>(min + static_cast<int64>(base::RandGenerator(range))); | |
|
Lei Zhang
2015/10/29 16:38:15
int64_t, and fix line 22 as well?
Nico
2015/10/29 16:46:45
Done.
| |
| 24 DCHECK_GE(result, min); | 27 DCHECK_GE(result, min); |
| 25 DCHECK_LE(result, max); | 28 DCHECK_LE(result, max); |
| 26 return result; | 29 return result; |
| 27 } | 30 } |
| 28 | 31 |
| 29 double RandDouble() { | 32 double RandDouble() { |
| 30 return BitsToOpenEndedUnitInterval(base::RandUint64()); | 33 return BitsToOpenEndedUnitInterval(base::RandUint64()); |
| 31 } | 34 } |
| 32 | 35 |
| 33 double BitsToOpenEndedUnitInterval(uint64 bits) { | 36 double BitsToOpenEndedUnitInterval(uint64 bits) { |
| (...skipping 29 matching lines...) Expand all Loading... | |
| 63 } | 66 } |
| 64 | 67 |
| 65 std::string RandBytesAsString(size_t length) { | 68 std::string RandBytesAsString(size_t length) { |
| 66 DCHECK_GT(length, 0u); | 69 DCHECK_GT(length, 0u); |
| 67 std::string result; | 70 std::string result; |
| 68 RandBytes(WriteInto(&result, length + 1), length); | 71 RandBytes(WriteInto(&result, length + 1), length); |
| 69 return result; | 72 return result; |
| 70 } | 73 } |
| 71 | 74 |
| 72 } // namespace base | 75 } // namespace base |
| OLD | NEW |