diff --git a/lib/cast_to_int.php b/lib/cast_to_int.php index f7f1960..474ce64 100644 --- a/lib/cast_to_int.php +++ b/lib/cast_to_int.php @@ -44,10 +44,7 @@ */ function RandomCompat_intval($number, $fail_open = false) { - if ( - is_string($number) && - preg_match('#^\-?[0-9]+\.?[0-9]*$#', $number) - ) { + if (is_numeric($number)) { $number += 0; } if ( @@ -55,11 +52,7 @@ function RandomCompat_intval($number, $fail_open = false) $number > ~PHP_INT_MAX && $number < PHP_INT_MAX ) { - $number = (int) ( - $number < 0 - ? ceil($number) - : floor($number) - ); + $number = (int) $number; } if (is_int($number) || $fail_open) { return $number; diff --git a/lib/random_bytes_libsodium.php b/lib/random_bytes_libsodium.php index 43317d2..796ba6a 100644 --- a/lib/random_bytes_libsodium.php +++ b/lib/random_bytes_libsodium.php @@ -58,6 +58,7 @@ function random_bytes($bytes) * generated in one invocation. */ if ($bytes > 2147483647) { + $buf = ''; for ($i = 0; $i < $bytes; $i += 1073741824) { $n = ($bytes - $i) > 1073741824 ? 1073741824 diff --git a/tests/unit/RandomIntTest.php b/tests/unit/RandomIntTest.php index c61f698..f9fc3c3 100644 --- a/tests/unit/RandomIntTest.php +++ b/tests/unit/RandomIntTest.php @@ -19,7 +19,8 @@ public function testOutput() random_int(0.11111, 0.99999), random_int($half_neg_max, PHP_INT_MAX), random_int(0.0, 255.0), - random_int(-4.5, -4.5) + random_int(-4.5, -4.5), + random_int("1337e3","1337e3") ); $this->assertFalse($integers[0] === $integers[1]); @@ -33,6 +34,7 @@ public function testOutput() $this->assertTrue($integers[7] >= $half_neg_max && $integers[7] <= PHP_INT_MAX); $this->assertTrue($integers[8] >= 0 && $integers[8] <= 255); $this->assertTrue($integers[9] === -4); + $this->assertTrue($integers[10] === 1337000); try { $h = random_int("2147483648", "2147483647"); diff --git a/tests/unit/UtilityTest.php b/tests/unit/UtilityTest.php index 54da8c3..294a801 100644 --- a/tests/unit/UtilityTest.php +++ b/tests/unit/UtilityTest.php @@ -34,6 +34,12 @@ public function testIntval() $this->assertTrue( is_int(RandomCompat_intval(~PHP_INT_MAX + 1, true)) ); + $this->assertTrue( + is_int(RandomCompat_intval("1337e3", true)) + ); + $this->assertTrue( + is_int(RandomCompat_intval("1.", true)) + ); // False $this->assertFalse( @@ -54,13 +60,22 @@ public function testIntval() $this->assertFalse( is_int(RandomCompat_intval(PHP_INT_MAX + 0.1, true)) ); + $this->assertFalse( + is_int(RandomCompat_intval("hello", true)) + ); if (PHP_INT_SIZE === 8) { + $this->assertFalse( + is_int(RandomCompat_intval("-9223372036854775809", true)) + ); $this->assertTrue( - is_int(RandomCompat_intval("-9223372036854775807", true)) + is_int(RandomCompat_intval("-9223372036854775808", true)) + ); + $this->assertFalse( + is_int(RandomCompat_intval("9223372036854775808", true)) ); $this->assertTrue( - is_int(RandomCompat_intval("9223372036854775806", true)) + is_int(RandomCompat_intval("9223372036854775807", true)) ); } else { $this->assertFalse(