random_int.php 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. <?php
  2. /**
  3. * Random_* Compatibility Library
  4. * for using the new PHP 7 random_* API in PHP 5 projects
  5. *
  6. * The MIT License (MIT)
  7. *
  8. * Copyright (c) 2015 Paragon Initiative Enterprises
  9. *
  10. * Permission is hereby granted, free of charge, to any person obtaining a copy
  11. * of this software and associated documentation files (the "Software"), to deal
  12. * in the Software without restriction, including without limitation the rights
  13. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  14. * copies of the Software, and to permit persons to whom the Software is
  15. * furnished to do so, subject to the following conditions:
  16. *
  17. * The above copyright notice and this permission notice shall be included in
  18. * all copies or substantial portions of the Software.
  19. *
  20. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  21. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  22. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  23. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  24. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  25. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  26. * SOFTWARE.
  27. */
  28. if ( ! is_callable( 'random_int' ) ):
  29. /**
  30. * Fetch a random integer between $min and $max inclusive
  31. *
  32. * @param int $min
  33. * @param int $max
  34. *
  35. * @throws Exception
  36. *
  37. * @return int
  38. */
  39. function random_int($min, $max)
  40. {
  41. /**
  42. * Type and input logic checks
  43. *
  44. * If you pass it a float in the range (~PHP_INT_MAX, PHP_INT_MAX)
  45. * (non-inclusive), it will sanely cast it to an int. If you it's equal to
  46. * ~PHP_INT_MAX or PHP_INT_MAX, we let it fail as not an integer. Floats
  47. * lose precision, so the <= and => operators might accidentally let a float
  48. * through.
  49. */
  50. try {
  51. $min = RandomCompat_intval($min);
  52. } catch (TypeError $ex) {
  53. throw new TypeError(
  54. 'random_int(): $min must be an integer'
  55. );
  56. }
  57. try {
  58. $max = RandomCompat_intval($max);
  59. } catch (TypeError $ex) {
  60. throw new TypeError(
  61. 'random_int(): $max must be an integer'
  62. );
  63. }
  64. /**
  65. * Now that we've verified our weak typing system has given us an integer,
  66. * let's validate the logic then we can move forward with generating random
  67. * integers along a given range.
  68. */
  69. if ($min > $max) {
  70. throw new Error(
  71. 'Minimum value must be less than or equal to the maximum value'
  72. );
  73. }
  74. if ($max === $min) {
  75. return $min;
  76. }
  77. /**
  78. * Initialize variables to 0
  79. *
  80. * We want to store:
  81. * $bytes => the number of random bytes we need
  82. * $mask => an integer bitmask (for use with the &) operator
  83. * so we can minimize the number of discards
  84. */
  85. $attempts = $bits = $bytes = $mask = $valueShift = 0;
  86. /**
  87. * At this point, $range is a positive number greater than 0. It might
  88. * overflow, however, if $max - $min > PHP_INT_MAX. PHP will cast it to
  89. * a float and we will lose some precision.
  90. */
  91. $range = $max - $min;
  92. /**
  93. * Test for integer overflow:
  94. */
  95. if (!is_int($range)) {
  96. /**
  97. * Still safely calculate wider ranges.
  98. * Provided by @CodesInChaos, @oittaa
  99. *
  100. * @ref https://gist.github.com/CodesInChaos/03f9ea0b58e8b2b8d435
  101. *
  102. * We use ~0 as a mask in this case because it generates all 1s
  103. *
  104. * @ref https://eval.in/400356 (32-bit)
  105. * @ref http://3v4l.org/XX9r5 (64-bit)
  106. */
  107. $bytes = PHP_INT_SIZE;
  108. $mask = ~0;
  109. } else {
  110. /**
  111. * $bits is effectively ceil(log($range, 2)) without dealing with
  112. * type juggling
  113. */
  114. while ($range > 0) {
  115. if ($bits % 8 === 0) {
  116. ++$bytes;
  117. }
  118. ++$bits;
  119. $range >>= 1;
  120. $mask = $mask << 1 | 1;
  121. }
  122. $valueShift = $min;
  123. }
  124. /**
  125. * Now that we have our parameters set up, let's begin generating
  126. * random integers until one falls between $min and $max
  127. */
  128. do {
  129. /**
  130. * The rejection probability is at most 0.5, so this corresponds
  131. * to a failure probability of 2^-128 for a working RNG
  132. */
  133. if ($attempts > 128) {
  134. throw new Exception(
  135. 'random_int: RNG is broken - too many rejections'
  136. );
  137. }
  138. /**
  139. * Let's grab the necessary number of random bytes
  140. */
  141. $randomByteString = random_bytes($bytes);
  142. if ($randomByteString === false) {
  143. throw new Exception(
  144. 'Random number generator failure'
  145. );
  146. }
  147. /**
  148. * Let's turn $randomByteString into an integer
  149. *
  150. * This uses bitwise operators (<< and |) to build an integer
  151. * out of the values extracted from ord()
  152. *
  153. * Example: [9F] | [6D] | [32] | [0C] =>
  154. * 159 + 27904 + 3276800 + 201326592 =>
  155. * 204631455
  156. */
  157. $val = 0;
  158. for ($i = 0; $i < $bytes; ++$i) {
  159. $val |= ord($randomByteString[$i]) << ($i * 8);
  160. }
  161. /**
  162. * Apply mask
  163. */
  164. $val &= $mask;
  165. $val += $valueShift;
  166. ++$attempts;
  167. /**
  168. * If $val overflows to a floating point number,
  169. * ... or is larger than $max,
  170. * ... or smaller than $min,
  171. * then try again.
  172. */
  173. } while (!is_int($val) || $val > $max || $val < $min);
  174. return (int) $val;
  175. }
  176. endif;