1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Savvot\Random; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* Fast and good quality random generator, based on XorShift+ algorithm with 128bit state |
7
|
|
|
* Based on C code from http://xorshift.di.unimi.it/xorshift128plus.c |
8
|
|
|
* More info: https://en.wikipedia.org/wiki/Xorshift |
9
|
|
|
* Comparison of different xorshifts: http://xorshift.di.unimi.it/ |
10
|
|
|
* |
11
|
|
|
* @package Savvot\Random |
12
|
|
|
* @author SavvoT <[email protected]> |
13
|
|
|
*/ |
14
|
|
|
class XorShiftRand extends AbstractRand |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* This is 63bit generator because PHP does not support unsigned 64bit int |
18
|
|
|
*/ |
19
|
|
|
const INT_MAX = 0x7FFFFFFFFFFFFFFF; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @inheritdoc |
23
|
|
|
*/ |
24
|
|
|
public function randomInt() |
25
|
|
|
{ |
26
|
|
|
$s1 = $this->state[0]; |
27
|
|
|
$s0 = $this->state[1]; |
28
|
|
|
$this->state[0] = $s0; |
29
|
|
|
$s1 ^= ($s1 << 23) & self::INT_MAX; |
30
|
|
|
|
31
|
|
|
// s1 ^ s0 ^ (s1 >> 17) ^ (s0 >> 26) |
|
|
|
|
32
|
|
|
// Original C algorithm operates uint64, but in PHP 64bit int is signed only. |
33
|
|
|
// Also right shift in PHP is arithmetic, so we need to unset filled sign bits |
34
|
|
|
$this->state[1] = $s1 ^ $s0 ^ (($s1 >> 17) & (self::INT_MAX >> 16)) ^ (($s0 >> 26) & (self::INT_MAX >> 25)); |
35
|
|
|
|
36
|
|
|
return ($this->state[1] + $s0) & self::INT_MAX; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* @inheritdoc |
41
|
|
|
*/ |
42
|
|
|
protected function init() |
43
|
|
|
{ |
44
|
|
|
// Unfortunately P flag for 64bit is 5.6+ |
45
|
|
|
$state = unpack('V*', $this->hashedSeed); |
46
|
|
|
$this->state = [ |
47
|
|
|
($state[2] << 32 | $state[1]) & self::INT_MAX, |
48
|
|
|
($state[4] << 32 | $state[3]) & self::INT_MAX, |
49
|
|
|
]; |
50
|
|
|
|
51
|
|
|
// Values must not be 0 |
52
|
|
|
while ($this->state[0] === 0 || $this->state[1] === 0) { |
53
|
|
|
$this->hashedSeed = md5($this->hashedSeed, true); |
54
|
|
|
$state = unpack('V*', $this->hashedSeed); |
55
|
|
|
$this->state = [ |
56
|
|
|
($state[2] << 32 | $state[1]) & self::INT_MAX, |
57
|
|
|
($state[4] << 32 | $state[3]) & self::INT_MAX, |
58
|
|
|
]; |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|
Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.
The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.
This check looks for comments that seem to be mostly valid code and reports them.