No Description

random_int.php 5.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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 - 2016 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. /**
  29. * Fetch a random integer between $min and $max inclusive
  30. *
  31. * @param int $min
  32. * @param int $max
  33. *
  34. * @throws Exception
  35. *
  36. * @return int
  37. */
  38. function random_int($min, $max)
  39. {
  40. /**
  41. * Type and input logic checks
  42. *
  43. * If you pass it a float in the range (~PHP_INT_MAX, PHP_INT_MAX)
  44. * (non-inclusive), it will sanely cast it to an int. If you it's equal to
  45. * ~PHP_INT_MAX or PHP_INT_MAX, we let it fail as not an integer. Floats
  46. * lose precision, so the <= and => operators might accidentally let a float
  47. * through.
  48. */
  49. try {
  50. $min = RandomCompat_intval($min);
  51. } catch (TypeError $ex) {
  52. throw new TypeError(
  53. 'random_int(): $min must be an integer'
  54. );
  55. }
  56. try {
  57. $max = RandomCompat_intval($max);
  58. } catch (TypeError $ex) {
  59. throw new TypeError(
  60. 'random_int(): $max must be an integer'
  61. );
  62. }
  63. /**
  64. * Now that we've verified our weak typing system has given us an integer,
  65. * let's validate the logic then we can move forward with generating random
  66. * integers along a given range.
  67. */
  68. if ($min > $max) {
  69. throw new Error(
  70. 'Minimum value must be less than or equal to the maximum value'
  71. );
  72. }
  73. if ($max === $min) {
  74. return $min;
  75. }
  76. /**
  77. * Initialize variables to 0
  78. *
  79. * We want to store:
  80. * $bytes => the number of random bytes we need
  81. * $mask => an integer bitmask (for use with the &) operator
  82. * so we can minimize the number of discards
  83. */
  84. $attempts = $bits = $bytes = $mask = $valueShift = 0;
  85. /**
  86. * At this point, $range is a positive number greater than 0. It might
  87. * overflow, however, if $max - $min > PHP_INT_MAX. PHP will cast it to
  88. * a float and we will lose some precision.
  89. */
  90. $range = $max - $min;
  91. /**
  92. * Test for integer overflow:
  93. */
  94. if (!is_int($range)) {
  95. /**
  96. * Still safely calculate wider ranges.
  97. * Provided by @CodesInChaos, @oittaa
  98. *
  99. * @ref https://gist.github.com/CodesInChaos/03f9ea0b58e8b2b8d435
  100. *
  101. * We use ~0 as a mask in this case because it generates all 1s
  102. *
  103. * @ref https://eval.in/400356 (32-bit)
  104. * @ref http://3v4l.org/XX9r5 (64-bit)
  105. */
  106. $bytes = PHP_INT_SIZE;
  107. $mask = ~0;
  108. } else {
  109. /**
  110. * $bits is effectively ceil(log($range, 2)) without dealing with
  111. * type juggling
  112. */
  113. while ($range > 0) {
  114. if ($bits % 8 === 0) {
  115. ++$bytes;
  116. }
  117. ++$bits;
  118. $range >>= 1;
  119. $mask = $mask << 1 | 1;
  120. }
  121. $valueShift = $min;
  122. }
  123. /**
  124. * Now that we have our parameters set up, let's begin generating
  125. * random integers until one falls between $min and $max
  126. */
  127. do {
  128. /**
  129. * The rejection probability is at most 0.5, so this corresponds
  130. * to a failure probability of 2^-128 for a working RNG
  131. */
  132. if ($attempts > 128) {
  133. throw new Exception(
  134. 'random_int: RNG is broken - too many rejections'
  135. );
  136. }
  137. /**
  138. * Let's grab the necessary number of random bytes
  139. */
  140. $randomByteString = random_bytes($bytes);
  141. if ($randomByteString === false) {
  142. throw new Exception(
  143. 'Random number generator failure'
  144. );
  145. }
  146. /**
  147. * Let's turn $randomByteString into an integer
  148. *
  149. * This uses bitwise operators (<< and |) to build an integer
  150. * out of the values extracted from ord()
  151. *
  152. * Example: [9F] | [6D] | [32] | [0C] =>
  153. * 159 + 27904 + 3276800 + 201326592 =>
  154. * 204631455
  155. */
  156. $val = 0;
  157. for ($i = 0; $i < $bytes; ++$i) {
  158. $val |= ord($randomByteString[$i]) << ($i * 8);
  159. }
  160. /**
  161. * Apply mask
  162. */
  163. $val &= $mask;
  164. $val += $valueShift;
  165. ++$attempts;
  166. /**
  167. * If $val overflows to a floating point number,
  168. * ... or is larger than $max,
  169. * ... or smaller than $min,
  170. * then try again.
  171. */
  172. } while (!is_int($val) || $val > $max || $val < $min);
  173. return (int) $val;
  174. }