Skip to content
This repository has been archived by the owner on May 8, 2024. It is now read-only.

Commit

Permalink
Merge branch 'denixport-hotfix/rand-int'
Browse files Browse the repository at this point in the history
  • Loading branch information
ezimuel committed Mar 5, 2014
2 parents 4c617fd + 4a5a7df commit 43f2f86
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 6 deletions.
20 changes: 14 additions & 6 deletions library/Zend/Math/Rand.php
Original file line number Diff line number Diff line change
Expand Up @@ -130,13 +130,21 @@ public static function getInteger($min, $max, $strong = false)
'The supplied range is too great to generate'
);
}
$log = log($range, 2);
$bytes = (int) ($log / 8) + 1;
$bits = (int) $log + 1;
$filter = (int) (1 << $bits) - 1;

// calculate number of bits required to store range on this machine
$r = $range;
$bits = 0;
while ($r >>= 1) {
$bits++;
}

$bits = (int) max($bits, 1);
$bytes = (int) max(ceil($bits / 8), 1);
$filter = (int) ((1 << $bits) - 1);

do {
$rnd = hexdec(bin2hex(self::getBytes($bytes, $strong)));
$rnd = $rnd & $filter;
$rnd = hexdec(bin2hex(static::getBytes($bytes, $strong)));
$rnd &= $filter;
} while ($rnd > $range);

return ($min + $rnd);
Expand Down
11 changes: 11 additions & 0 deletions tests/ZendTest/Math/RandTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,17 @@ public function testIntegerRangeFail()
$rand = Rand::getInteger(100, 0);
}

public function testIntegerRangeOverflow()
{
$values = 0;
$cycles = 100;
for ($i = 0; $i < $cycles; $i++) {
$values += Rand::getInteger(0, PHP_INT_MAX);
}

$this->assertFalse($values === 0);
}

public function testRandFloat()
{
for ($length = 1; $length < 512; $length++) {
Expand Down

0 comments on commit 43f2f86

Please sign in to comment.