random_int.php 6.6 KB

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