seedrandom.js 8.4 KB

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