seedrandom.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. /* eslint-disable */
  2. /*
  3. Copyright 2014 David Bau.
  4. Permission is hereby granted, free of charge, to any person obtaining
  5. a copy of this software and associated documentation files (the
  6. "Software"), to deal in the Software without restriction, including
  7. without limitation the rights to use, copy, modify, merge, publish,
  8. distribute, sublicense, and/or sell copies of the Software, and to
  9. permit persons to whom the Software is furnished to do so, subject to
  10. the following conditions:
  11. The above copyright notice and this permission notice shall be
  12. included in all copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  14. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  15. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  16. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  17. CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  18. TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  19. SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  20. */
  21. function seedRandom(pool, math) {
  22. //
  23. // The following constants are related to IEEE 754 limits.
  24. //
  25. var global = this,
  26. width = 256, // each RC4 output is 0 <= x < 256
  27. chunks = 6, // at least six RC4 outputs for each double
  28. digits = 52, // there are 52 significant digits in a double
  29. rngname = 'random', // rngname: name for Math.random and Math.seedrandom
  30. startdenom = math.pow(width, chunks),
  31. significance = math.pow(2, digits),
  32. overflow = significance * 2,
  33. mask = width - 1,
  34. nodecrypto; // node.js crypto module, initialized at the bottom.
  35. //
  36. // seedrandom()
  37. // This is the seedrandom function described above.
  38. //
  39. function seedrandom(seed, options, callback) {
  40. var key = [];
  41. options = (options === true) ? { entropy: true } : (options || {});
  42. // Flatten the seed string or build one from local entropy if needed.
  43. var shortseed = mixkey(flatten(
  44. options.entropy ? [seed, tostring(pool)] :
  45. (seed === null) ? autoseed() : seed, 3), key);
  46. // Use the seed to initialize an ARC4 generator.
  47. var arc4 = new ARC4(key);
  48. // This function returns a random double in [0, 1) that contains
  49. // randomness in every bit of the mantissa of the IEEE 754 value.
  50. var prng = function() {
  51. var n = arc4.g(chunks), // Start with a numerator n < 2 ^ 48
  52. d = startdenom, // and denominator d = 2 ^ 48.
  53. x = 0; // and no 'extra last byte'.
  54. while (n < significance) { // Fill up all significant digits by
  55. n = (n + x) * width; // shifting numerator and
  56. d *= width; // denominator and generating a
  57. x = arc4.g(1); // new least-significant-byte.
  58. }
  59. while (n >= overflow) { // To avoid rounding up, before adding
  60. n /= 2; // last byte, shift everything
  61. d /= 2; // right using integer math until
  62. x >>>= 1; // we have exactly the desired bits.
  63. }
  64. return (n + x) / d; // Form the number within [0, 1).
  65. };
  66. prng.int32 = function() { return arc4.g(4) | 0; };
  67. prng.quick = function() { return arc4.g(4) / 0x100000000; };
  68. prng.double = prng;
  69. // Mix the randomness into accumulated entropy.
  70. mixkey(tostring(arc4.S), pool);
  71. // Calling convention: what to return as a function of prng, seed, is_math.
  72. return (options.pass || callback ||
  73. function(prng, seed, is_math_call, state) {
  74. if (state) {
  75. // Load the arc4 state from the given state if it has an S array.
  76. if (state.S) { copy(state, arc4); }
  77. // Only provide the .state method if requested via options.state.
  78. prng.state = function() { return copy(arc4, {}); };
  79. }
  80. // If called as a method of Math (Math.seedrandom()), mutate
  81. // Math.random because that is how seedrandom.js has worked since v1.0.
  82. if (is_math_call) { math[rngname] = prng; return seed; }
  83. // Otherwise, it is a newer calling convention, so return the
  84. // prng directly.
  85. else return prng;
  86. })(
  87. prng,
  88. shortseed,
  89. 'global' in options ? options.global : (this == math),
  90. options.state);
  91. }
  92. math['seed' + rngname] = seedrandom;
  93. //
  94. // ARC4
  95. //
  96. // An ARC4 implementation. The constructor takes a key in the form of
  97. // an array of at most (width) integers that should be 0 <= x < (width).
  98. //
  99. // The g(count) method returns a pseudorandom integer that concatenates
  100. // the next (count) outputs from ARC4. Its return value is a number x
  101. // that is in the range 0 <= x < (width ^ count).
  102. //
  103. function ARC4(key) {
  104. var t, keylen = key.length,
  105. me = this, i = 0, j = me.i = me.j = 0, s = me.S = [];
  106. // The empty key [] is treated as [0].
  107. if (!keylen) { key = [keylen++]; }
  108. // Set up S using the standard key scheduling algorithm.
  109. while (i < width) {
  110. s[i] = i++;
  111. }
  112. for (i = 0; i < width; i++) {
  113. s[i] = s[j = mask & (j + key[i % keylen] + (t = s[i]))];
  114. s[j] = t;
  115. }
  116. // The "g" method returns the next (count) outputs as one number.
  117. me.g = function(count) {
  118. // Using instance members instead of closure state nearly doubles speed.
  119. var t, r = 0,
  120. i = me.i, j = me.j, s = me.S;
  121. while (count--) {
  122. t = s[i = mask & (i + 1)];
  123. r = r * width + s[mask & ((s[i] = s[j = mask & (j + t)]) + (s[j] = t))];
  124. }
  125. me.i = i; me.j = j;
  126. return r;
  127. // For robust unpredictability, the function call below automatically
  128. // discards an initial batch of values. This is called RC4-drop[256].
  129. // See http://google.com/search?q=rsa+fluhrer+response&btnI
  130. };
  131. }
  132. //
  133. // copy()
  134. // Copies internal state of ARC4 to or from a plain object.
  135. //
  136. function copy(f, t) {
  137. t.i = f.i;
  138. t.j = f.j;
  139. t.S = f.S.slice();
  140. return t;
  141. }
  142. //
  143. // flatten()
  144. // Converts an object tree to nested arrays of strings.
  145. //
  146. function flatten(obj, depth) {
  147. var result = [], typ = (typeof obj), prop;
  148. if (depth && typ == 'object') {
  149. for (prop in obj) {
  150. try { result.push(flatten(obj[prop], depth - 1)); } catch (e) {}
  151. }
  152. }
  153. return (result.length ? result : typ == 'string' ? obj : obj + '\0');
  154. }
  155. //
  156. // mixkey()
  157. // Mixes a string seed into a key that is an array of integers, and
  158. // returns a shortened string seed that is equivalent to the result key.
  159. //
  160. function mixkey(seed, key) {
  161. var stringseed = seed + '', smear, j = 0;
  162. while (j < stringseed.length) {
  163. key[mask & j] =
  164. mask & ((smear ^= key[mask & j] * 19) + stringseed.charCodeAt(j++));
  165. }
  166. return tostring(key);
  167. }
  168. //
  169. // autoseed()
  170. // Returns an object for autoseeding, using window.crypto and Node crypto
  171. // module if available.
  172. //
  173. function autoseed() {
  174. try {
  175. if (nodecrypto) { return tostring(nodecrypto.randomBytes(width)); }
  176. var out = new Uint8Array(width);
  177. (global.crypto || global.msCrypto).getRandomValues(out);
  178. return tostring(out);
  179. } catch (e) {
  180. var browser = global.navigator,
  181. plugins = browser && browser.plugins;
  182. return [+new Date(), global, plugins, global.screen, tostring(pool)];
  183. }
  184. }
  185. //
  186. // tostring()
  187. // Converts an array of charcodes to a string
  188. //
  189. function tostring(a) {
  190. return String.fromCharCode.apply(0, a);
  191. }
  192. //
  193. // When seedrandom.js is loaded, we immediately mix a few bits
  194. // from the built-in RNG into the entropy pool. Because we do
  195. // not want to interfere with deterministic PRNG state later,
  196. // seedrandom will not call math.random on its own again after
  197. // initialization.
  198. //
  199. mixkey(math.random(), pool);
  200. //
  201. // Nodejs and AMD support: export the implementation as a module using
  202. // either convention.
  203. //
  204. // End anonymous scope, and pass initial values.
  205. };
  206. function initialize(BMMath) {
  207. seedRandom([], BMMath);
  208. }
  209. export default initialize;