-
-
Notifications
You must be signed in to change notification settings - Fork 468
Expand file tree
/
Copy pathRandom.java
More file actions
345 lines (301 loc) · 12.4 KB
/
Random.java
File metadata and controls
345 lines (301 loc) · 12.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
/*
* Adapted from: https://github.com/KilianB/pcg-java/blob/master/src/main/java/com/github/kilianB/pcg/fast/PcgRSFast.java
*
* MIT License
*
* Copyright (c) 2018
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.sentry.util;
import java.util.concurrent.atomic.AtomicLong;
import org.jetbrains.annotations.ApiStatus;
/**
* A simplified replacement for {@link java.util.Random}, based on pcg-java that we use for
* sampling, which is much faster than {@link java.security.SecureRandom}. This is necessary so that
* some security tools do not flag our Random usage as potentially insecure.
*/
@ApiStatus.Internal
@SuppressWarnings({"unused", "UnnecessaryParentheses", "OperatorPrecedence"})
public final class Random implements java.io.Serializable {
private static final long serialVersionUID = -4257915988930727506L;
static final AtomicLong UNIQUE_SEED = new AtomicLong(System.nanoTime());
/** Linear congruential constant. Same as MMIX by Donald Knuth and Newlib, Musl */
private static final long MULT_64 = 6364136223846793005L;
// static final variables are inlined by default
private static final double DOUBLE_MASK = 1L << 53;
private static final float FLOAT_UNIT = (float) (1 << 24);
private static final long INTEGER_MASK = 0xFFFFFFFFL;
// 64 version
/** 64 bit internal state */
private long state;
/** Stream number of the rng. */
private long inc;
private boolean gausAvailable;
private double nextGaus;
// private static final int INTEGER_MASK_SIGNED = 0xFFFFFFFF;
/**
* Create a PcgRSFast instance seeded with with 2 longs generated by xorshift*. The values chosen
* are very likely not used as seeds in any other non argument constructor of any of the classes
* provided in this library.
*/
public Random() {
this(getRandomSeed(), getRandomSeed());
}
/**
* Create a random number generator with the given seed and stream number. The seed defines the
* current state in which the rng is in and corresponds to seeds usually found in other RNG
* instances. RNGs with different seeds are able to catch up after they exhaust their period and
* produce the same numbers. (2^63).
*
* <p>Different stream numbers alter the increment of the rng and ensure distinct state sequences
*
* <p>Only generators with the same seed AND stream numbers will produce identical values
*
* <p>
*
* @param seed used to compute the starting state of the RNG
* @param streamNumber used to compute the increment for the lcg.
*/
public Random(long seed, long streamNumber) {
setSeed(seed, streamNumber);
}
private Random(long initialState, long increment, boolean dummy) {
setState(initialState);
setInc(increment);
}
/**
* Sets the seed of this random number generator using . The general contract of setSeed is that
* it alters the state of this random number generator object so as to be in exactly the same
* state as if it had just been created with the argument seed as a seed.
*
* <p>Only generators with the same seed AND stream numbers will produce identical values
*
* <p>
*
* @param seed used to compute the starting state of the RNG
* @param streamNumber used to compute the increment for the lcg.
*/
public void setSeed(long seed, long streamNumber) {
// TODO synchronize?
state = 0;
inc = (streamNumber << 1) | 1; // 2* + 1
state = (state * MULT_64) + inc;
state += seed;
// Due to access to inlined vars the fast implementation is one step ahead of
// the ordinary rngs. To get same results we can skip the state update
// state = (state * MULT_64) + inc;
}
public byte nextByte() {
state = (state * MULT_64) + inc;
return (byte) ((((state >>> 22) ^ state) >>> ((state >>> 61) + 22)) >>> 24);
}
public void nextBytes(byte[] b) {
for (int i = 0; i < b.length; i++) {
state = (state * MULT_64) + inc;
b[i] = (byte) ((((state >>> 22) ^ state) >>> ((state >>> 61) + 22)) >>> 24);
}
}
public char nextChar() {
state = (state * MULT_64) + inc;
// Why should we cast it to an int first can't we mask it to a char directly?
return (char) ((((state >>> 22) ^ state) >>> ((state >>> 61) + 22)) >>> 16);
}
public short nextShort() {
state = (state * MULT_64) + inc;
return (short) ((((state >>> 22) ^ state) >>> ((state >>> 61) + 22)) >>> 16);
}
/**
* Returns the next pseudorandom, uniformly distributed {@code int} value from this random number
* generator's sequence. The general contract of {@code nextInt} is that one {@code int} value is
* pseudorandomly generated and returned. All 2<sup>32</sup> possible {@code int} values are
* produced with (approximately) equal probability.
*
* @return the next pseudorandom, uniformly distributed {@code int} value from this random number
* generator's sequence
*/
public int nextInt() {
// we miss a single state and keep an old value around. but this does not alter
// The produced number but shifts them 1 back.
state = (state * MULT_64) + inc;
// long oldState = state;
return (int) (((state >>> 22) ^ state) >>> ((state >>> 61) + 22));
}
/**
* Returns a pseudorandom, uniformly distributed {@code int} value between 0 (inclusive) and the
* specified value (exclusive), drawn from this random number generator's sequence.
*
* @param n the upper bound (exclusive). Must be positive.
* @return the next pseudorandom, uniformly distributed {@code int} value between zero (inclusive)
* and {@code bound} (exclusive) from this random number generator's sequence
*/
public int nextInt(int n) {
state = (state * MULT_64) + inc;
int r = (int) (((state >>> 22) ^ state) >>> ((state >>> 61) + 22)) >>> 1; // Unsigned!
int m = n - 1;
if ((n & m) == 0) // i.e., bound is a power of 2
r = (int) ((n * (long) r) >> 31);
else {
for (int u = r; u - (r = u % n) + m < 0; ) {
state = (state * MULT_64) + inc;
u = (int) (((state >>> 22) ^ state) >>> ((state >>> 61) + 22)) >>> 1;
}
}
return r;
}
;
/**
* Returns the next pseudorandom, uniformly distributed {@code boolean} value from this random
* number generator's sequence. The general contract of {@code nextBoolean} is that one {@code
* boolean} value is pseudorandomly generated and returned. The values {@code true} and {@code
* false} are produced with (approximately) equal probability.
*
* @return the next pseudorandom, uniformly distributed {@code boolean} value from this random
* number generator's sequence
*/
@SuppressWarnings("OperatorPrecedence")
public boolean nextBoolean() {
// Two choices either take the low bit or get a range 2 int and make an if
state = (state * MULT_64) + inc;
return (((((state >>> 22) ^ state) >>> (state >>> 61) + 22) & INTEGER_MASK) >>> 31) != 0;
}
@SuppressWarnings("UnnecessaryParentheses")
public boolean nextBoolean(double probability) {
if (probability < 0.0 || probability > 1.0)
throw new IllegalArgumentException("probability must be between 0.0 and 1.0 inclusive.");
// Borrowed from https://cs.gmu.edu/~sean/research/mersenne/MersenneTwister.java
if (probability == 0.0) return false;
if (probability == 1.0) return true;
state = (state * MULT_64) + inc;
long l = ((((state >>> 22) ^ state) >>> ((state >>> 61) + 22))) & INTEGER_MASK;
state = (state * MULT_64) + inc;
return (((l >>> 6) << 27)
+ (((((state >>> 22) ^ state) >>> ((state >>> 61) + 22)) & INTEGER_MASK) >>> 5))
/ DOUBLE_MASK
< probability;
}
public long nextLong() {
state = (state * MULT_64) + inc;
// No need to mask if we shift by 32 bits
long l = (((state >>> 22) ^ state) >>> ((state >>> 61) + 22));
state = (state * MULT_64) + inc;
long j = (((state >>> 22) ^ state) >>> ((state >>> 61) + 22));
// Long keep consistent with the random definition of keeping the lower word
// signed,
// But should this really be the case? Why don't we mask the sign bit?
return (l << 32) + (int) j;
}
public long nextLong(long n) {
if (n == 0) throw new IllegalArgumentException("n has to be greater than 0");
long bits;
long val;
do {
state = (state * MULT_64) + inc;
// No need to mask if we shift by 32 bits
long l = (((state >>> 22) ^ state) >>> ((state >>> 61) + 22));
state = (state * MULT_64) + inc;
long j = (((state >>> 22) ^ state) >>> ((state >>> 61) + 22));
bits = ((l << 32) + (int) j >>> 1);
val = bits % n;
} while (bits - val + (n - 1) < 0);
return val;
}
public double nextDouble() {
state = (state * MULT_64) + inc;
long l = ((((state >>> 22) ^ state) >>> ((state >>> 61) + 22))) & INTEGER_MASK;
state = (state * MULT_64) + inc;
return (((l >>> 6) << 27)
+ (((((state >>> 22) ^ state) >>> ((state >>> 61) + 22)) & INTEGER_MASK) >>> 5))
/ DOUBLE_MASK;
}
public double nextDouble(boolean includeZero, boolean includeOne) {
double d = 0.0;
do {
state = (state * MULT_64) + inc;
long l = ((((state >>> 22) ^ state) >>> ((state >>> 61) + 22))) & INTEGER_MASK;
state = (state * MULT_64) + inc;
d =
(((l >>> 6) << 27)
+ (((((state >>> 22) ^ state) >>> ((state >>> 61) + 22)) & INTEGER_MASK) >>> 5))
/ DOUBLE_MASK;
// grab a value, initially from half-open [0.0, 1.0)
if (includeOne) {
// Only generate the boolean if it really is the case or we scramble the state
state = (state * MULT_64) + inc;
if ((((((state >>> 22) ^ state) >>> (state >>> 61) + 22) & INTEGER_MASK) >>> 31) != 0) {
d += 1.0;
}
}
} while ((d > 1.0)
|| // everything above 1.0 is always invalid
(!includeZero && d == 0.0)); // if we're not including zero, 0.0 is invalid
return d;
}
public float nextFloat() {
state = (state * MULT_64) + inc;
return (((((state >>> 22) ^ state) >>> ((state >>> 61) + 22)) & INTEGER_MASK) >>> 8)
/ FLOAT_UNIT;
}
public float nextFloat(boolean includeZero, boolean includeOne) {
float d = 0.0f;
do {
state = (state * MULT_64) + inc;
d =
(((((state >>> 22) ^ state) >>> ((state >>> 61) + 22)) & INTEGER_MASK) >>> 8)
/ FLOAT_UNIT; // grab a
// value,
// initially
// from
// half-open
// [0.0f,
// 1.0f)
if (includeOne) {
// Only generate the boolean if it really is the case or we scramble the state
state = (state * MULT_64) + inc;
if ((((((state >>> 22) ^ state) >>> (state >>> 61) + 22) & INTEGER_MASK) >>> 31) != 0) {
d += 1.0f;
}
}
} while ((d > 1.0f)
|| // everything above 1.0f is always invalid
(!includeZero && d == 0.0f)); // if we're not including zero, 0.0f is invalid
return d;
}
private void setInc(long increment) {
if (increment == 0 || increment % 2 == 0) {
throw new IllegalArgumentException("Increment may not be 0 or even. Value: " + increment);
}
this.inc = increment;
}
private void setState(long state) {
this.state = state;
}
private static long getRandomSeed() {
// xorshift64*
for (; ; ) {
long current = UNIQUE_SEED.get();
long next = current;
next ^= next >> 12;
next ^= next << 25; // b
next ^= next >> 27; // c
next *= 0x2545F4914F6CDD1DL;
if (UNIQUE_SEED.compareAndSet(current, next)) return next;
}
}
}