OLD | NEW |
1 // Copyright 2013 the V8 project authors. All rights reserved. | 1 // Copyright 2013 the V8 project 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 "src/base/utils/random-number-generator.h" | 5 #include "src/base/utils/random-number-generator.h" |
6 | 6 |
7 #include <stdio.h> | 7 #include <stdio.h> |
8 #include <stdlib.h> | 8 #include <stdlib.h> |
9 | 9 |
10 #include <new> | 10 #include <new> |
(...skipping 61 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
72 // https://code.google.com/p/v8/issues/detail?id=2905 | 72 // https://code.google.com/p/v8/issues/detail?id=2905 |
73 int64_t seed = Time::NowFromSystemTime().ToInternalValue() << 24; | 73 int64_t seed = Time::NowFromSystemTime().ToInternalValue() << 24; |
74 seed ^= TimeTicks::HighResolutionNow().ToInternalValue() << 16; | 74 seed ^= TimeTicks::HighResolutionNow().ToInternalValue() << 16; |
75 seed ^= TimeTicks::Now().ToInternalValue() << 8; | 75 seed ^= TimeTicks::Now().ToInternalValue() << 8; |
76 SetSeed(seed); | 76 SetSeed(seed); |
77 #endif // V8_OS_CYGWIN || V8_OS_WIN | 77 #endif // V8_OS_CYGWIN || V8_OS_WIN |
78 } | 78 } |
79 | 79 |
80 | 80 |
81 int RandomNumberGenerator::NextInt(int max) { | 81 int RandomNumberGenerator::NextInt(int max) { |
82 DCHECK_LE(0, max); | 82 DCHECK_LT(0, max); |
83 | 83 |
84 // Fast path if max is a power of 2. | 84 // Fast path if max is a power of 2. |
85 if (IS_POWER_OF_TWO(max)) { | 85 if (IS_POWER_OF_TWO(max)) { |
86 return static_cast<int>((max * static_cast<int64_t>(Next(31))) >> 31); | 86 return static_cast<int>((max * static_cast<int64_t>(Next(31))) >> 31); |
87 } | 87 } |
88 | 88 |
89 while (true) { | 89 while (true) { |
90 int rnd = Next(31); | 90 int rnd = Next(31); |
91 int val = rnd % max; | 91 int val = rnd % max; |
92 if (rnd - val + (max - 1) >= 0) { | 92 if (rnd - val + (max - 1) >= 0) { |
(...skipping 30 matching lines...) Expand all Loading... |
123 return static_cast<int>(seed >> (48 - bits)); | 123 return static_cast<int>(seed >> (48 - bits)); |
124 } | 124 } |
125 | 125 |
126 | 126 |
127 void RandomNumberGenerator::SetSeed(int64_t seed) { | 127 void RandomNumberGenerator::SetSeed(int64_t seed) { |
128 initial_seed_ = seed; | 128 initial_seed_ = seed; |
129 seed_ = (seed ^ kMultiplier) & kMask; | 129 seed_ = (seed ^ kMultiplier) & kMask; |
130 } | 130 } |
131 | 131 |
132 } } // namespace v8::base | 132 } } // namespace v8::base |
OLD | NEW |