/ajax/libs/seedrandom/2.3.3/seedrandom.js

https://github.com/ninosys/cdnjs · JavaScript · 342 lines · 103 code · 19 blank · 220 comment · 26 complexity · a9757ab89a2f1399f79e040b3caa5cf6 MD5 · raw file

  1. // seedrandom.js version 2.3.3
  2. // Author: David Bau
  3. // Date: 2014 Feb 4
  4. //
  5. // Defines a method Math.seedrandom() that, when called, substitutes
  6. // an explicitly seeded RC4-based algorithm for Math.random(). Also
  7. // supports automatic seeding from local or network sources of entropy.
  8. // Can be used as a node.js or AMD module. Can be called with "new"
  9. // to create a local PRNG without changing Math.random.
  10. //
  11. // Basic usage:
  12. //
  13. // <script src=http://davidbau.com/encode/seedrandom.min.js></script>
  14. //
  15. // Math.seedrandom('yay.'); // Sets Math.random to a function that is
  16. // // initialized using the given explicit seed.
  17. //
  18. // Math.seedrandom(); // Sets Math.random to a function that is
  19. // // seeded using the current time, dom state,
  20. // // and other accumulated local entropy.
  21. // // The generated seed string is returned.
  22. //
  23. // Math.seedrandom('yowza.', true);
  24. // // Seeds using the given explicit seed mixed
  25. // // together with accumulated entropy.
  26. //
  27. // <script src="https://jsonlib.appspot.com/urandom?callback=Math.seedrandom">
  28. // </script> <!-- Seeds using urandom bits from a server. -->
  29. //
  30. // Math.seedrandom("hello."); // Behavior is the same everywhere:
  31. // document.write(Math.random()); // Always 0.9282578795792454
  32. // document.write(Math.random()); // Always 0.3752569768646784
  33. //
  34. // Math.seedrandom can be used as a constructor to return a seeded PRNG
  35. // that is independent of Math.random:
  36. //
  37. // var myrng = new Math.seedrandom('yay.');
  38. // var n = myrng(); // Using "new" creates a local prng without
  39. // // altering Math.random.
  40. //
  41. // When used as a module, seedrandom is a function that returns a seeded
  42. // PRNG instance without altering Math.random:
  43. //
  44. // // With node.js (after "npm install seedrandom"):
  45. // var seedrandom = require('seedrandom');
  46. // var rng = seedrandom('hello.');
  47. // console.log(rng()); // always 0.9282578795792454
  48. //
  49. // // With require.js or other AMD loader:
  50. // require(['seedrandom'], function(seedrandom) {
  51. // var rng = seedrandom('hello.');
  52. // console.log(rng()); // always 0.9282578795792454
  53. // });
  54. //
  55. // More examples:
  56. //
  57. // var seed = Math.seedrandom(); // Use prng with an automatic seed.
  58. // document.write(Math.random()); // Pretty much unpredictable x.
  59. //
  60. // var rng = new Math.seedrandom(seed); // A new prng with the same seed.
  61. // document.write(rng()); // Repeat the 'unpredictable' x.
  62. //
  63. // function reseed(event, count) { // Define a custom entropy collector.
  64. // var t = [];
  65. // function w(e) {
  66. // t.push([e.pageX, e.pageY, +new Date]);
  67. // if (t.length < count) { return; }
  68. // document.removeEventListener(event, w);
  69. // Math.seedrandom(t, true); // Mix in any previous entropy.
  70. // }
  71. // document.addEventListener(event, w);
  72. // }
  73. // reseed('mousemove', 100); // Reseed after 100 mouse moves.
  74. //
  75. // The callback third arg can be used to get both the prng and the seed.
  76. // The following returns both an autoseeded prng and the seed as an object,
  77. // without mutating Math.random:
  78. //
  79. // var obj = Math.seedrandom(null, false, function(prng, seed) {
  80. // return { random: prng, seed: seed };
  81. // });
  82. //
  83. // Version notes:
  84. //
  85. // The random number sequence is the same as version 1.0 for string seeds.
  86. // * Version 2.0 changed the sequence for non-string seeds.
  87. // * Version 2.1 speeds seeding and uses window.crypto to autoseed if present.
  88. // * Version 2.2 alters non-crypto autoseeding to sweep up entropy from plugins.
  89. // * Version 2.3 adds support for "new", module loading, and a null seed arg.
  90. // * Version 2.3.1 adds a build environment, module packaging, and tests.
  91. // * Version 2.3.3 fixes bugs on IE8, and switches to MIT license.
  92. //
  93. // The standard ARC4 key scheduler cycles short keys, which means that
  94. // seedrandom('ab') is equivalent to seedrandom('abab') and 'ababab'.
  95. // Therefore it is a good idea to add a terminator to avoid trivial
  96. // equivalences on short string seeds, e.g., Math.seedrandom(str + '\0').
  97. // Starting with version 2.0, a terminator is added automatically for
  98. // non-string seeds, so seeding with the number 111 is the same as seeding
  99. // with '111\0'.
  100. //
  101. // When seedrandom() is called with zero args or a null seed, it uses a
  102. // seed drawn from the browser crypto object if present. If there is no
  103. // crypto support, seedrandom() uses the current time, the native rng,
  104. // and a walk of several DOM objects to collect a few bits of entropy.
  105. //
  106. // Each time the one- or two-argument forms of seedrandom are called,
  107. // entropy from the passed seed is accumulated in a pool to help generate
  108. // future seeds for the zero- and two-argument forms of seedrandom.
  109. //
  110. // On speed - This javascript implementation of Math.random() is several
  111. // times slower than the built-in Math.random() because it is not native
  112. // code, but that is typically fast enough. Some details (timings on
  113. // Chrome 25 on a 2010 vintage macbook):
  114. //
  115. // seeded Math.random() - avg less than 0.0002 milliseconds per call
  116. // seedrandom('explicit.') - avg less than 0.2 milliseconds per call
  117. // seedrandom('explicit.', true) - avg less than 0.2 milliseconds per call
  118. // seedrandom() with crypto - avg less than 0.2 milliseconds per call
  119. //
  120. // Autoseeding without crypto is somewhat slower, about 20-30 milliseconds on
  121. // a 2012 windows 7 1.5ghz i5 laptop, as seen on Firefox 19, IE 10, and Opera.
  122. // Seeded rng calls themselves are fast across these browsers, with slowest
  123. // numbers on Opera at about 0.0005 ms per seeded Math.random().
  124. //
  125. // LICENSE (BSD):
  126. //
  127. // Copyright 2013 David Bau, all rights reserved.
  128. //
  129. // Redistribution and use in source and binary forms, with or without
  130. // modification, are permitted provided that the following conditions are met:
  131. //
  132. // 1. Redistributions of source code must retain the above copyright
  133. // notice, this list of conditions and the following disclaimer.
  134. //
  135. // 2. Redistributions in binary form must reproduce the above copyright
  136. // notice, this list of conditions and the following disclaimer in the
  137. // documentation and/or other materials provided with the distribution.
  138. //
  139. // 3. Neither the name of this module nor the names of its contributors may
  140. // be used to endorse or promote products derived from this software
  141. // without specific prior written permission.
  142. //
  143. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  144. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  145. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  146. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  147. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  148. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  149. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  150. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  151. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  152. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  153. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  154. //
  155. /**
  156. * All code is in an anonymous closure to keep the global namespace clean.
  157. */
  158. (function (
  159. global, pool, math, width, chunks, digits, module, define, rngname) {
  160. //
  161. // The following constants are related to IEEE 754 limits.
  162. //
  163. var startdenom = math.pow(width, chunks),
  164. significance = math.pow(2, digits),
  165. overflow = significance * 2,
  166. mask = width - 1,
  167. //
  168. // seedrandom()
  169. // This is the seedrandom function described above.
  170. //
  171. impl = math['seed' + rngname] = function(seed, use_entropy, callback) {
  172. var key = [];
  173. // Flatten the seed string or build one from local entropy if needed.
  174. var shortseed = mixkey(flatten(
  175. use_entropy ? [seed, tostring(pool)] :
  176. (seed == null) ? autoseed() : seed, 3), key);
  177. // Use the seed to initialize an ARC4 generator.
  178. var arc4 = new ARC4(key);
  179. // Mix the randomness into accumulated entropy.
  180. mixkey(tostring(arc4.S), pool);
  181. // Calling convention: what to return as a function of prng, seed, is_math.
  182. return (callback ||
  183. // If called as a method of Math (Math.seedrandom()), mutate Math.random
  184. // because that is how seedrandom.js has worked since v1.0. Otherwise,
  185. // it is a newer calling convention, so return the prng directly.
  186. function(prng, seed, is_math_call) {
  187. if (is_math_call) { math[rngname] = prng; return seed; }
  188. else return prng;
  189. })(
  190. // This function returns a random double in [0, 1) that contains
  191. // randomness in every bit of the mantissa of the IEEE 754 value.
  192. function() {
  193. var n = arc4.g(chunks), // Start with a numerator n < 2 ^ 48
  194. d = startdenom, // and denominator d = 2 ^ 48.
  195. x = 0; // and no 'extra last byte'.
  196. while (n < significance) { // Fill up all significant digits by
  197. n = (n + x) * width; // shifting numerator and
  198. d *= width; // denominator and generating a
  199. x = arc4.g(1); // new least-significant-byte.
  200. }
  201. while (n >= overflow) { // To avoid rounding up, before adding
  202. n /= 2; // last byte, shift everything
  203. d /= 2; // right using integer math until
  204. x >>>= 1; // we have exactly the desired bits.
  205. }
  206. return (n + x) / d; // Form the number within [0, 1).
  207. }, shortseed, this == math);
  208. };
  209. //
  210. // ARC4
  211. //
  212. // An ARC4 implementation. The constructor takes a key in the form of
  213. // an array of at most (width) integers that should be 0 <= x < (width).
  214. //
  215. // The g(count) method returns a pseudorandom integer that concatenates
  216. // the next (count) outputs from ARC4. Its return value is a number x
  217. // that is in the range 0 <= x < (width ^ count).
  218. //
  219. /** @constructor */
  220. function ARC4(key) {
  221. var t, keylen = key.length,
  222. me = this, i = 0, j = me.i = me.j = 0, s = me.S = [];
  223. // The empty key [] is treated as [0].
  224. if (!keylen) { key = [keylen++]; }
  225. // Set up S using the standard key scheduling algorithm.
  226. while (i < width) {
  227. s[i] = i++;
  228. }
  229. for (i = 0; i < width; i++) {
  230. s[i] = s[j = mask & (j + key[i % keylen] + (t = s[i]))];
  231. s[j] = t;
  232. }
  233. // The "g" method returns the next (count) outputs as one number.
  234. (me.g = function(count) {
  235. // Using instance members instead of closure state nearly doubles speed.
  236. var t, r = 0,
  237. i = me.i, j = me.j, s = me.S;
  238. while (count--) {
  239. t = s[i = mask & (i + 1)];
  240. r = r * width + s[mask & ((s[i] = s[j = mask & (j + t)]) + (s[j] = t))];
  241. }
  242. me.i = i; me.j = j;
  243. return r;
  244. // For robust unpredictability discard an initial batch of values.
  245. // See http://www.rsa.com/rsalabs/node.asp?id=2009
  246. })(width);
  247. }
  248. //
  249. // flatten()
  250. // Converts an object tree to nested arrays of strings.
  251. //
  252. function flatten(obj, depth) {
  253. var result = [], typ = (typeof obj), prop;
  254. if (depth && typ == 'object') {
  255. for (prop in obj) {
  256. try { result.push(flatten(obj[prop], depth - 1)); } catch (e) {}
  257. }
  258. }
  259. return (result.length ? result : typ == 'string' ? obj : obj + '\0');
  260. }
  261. //
  262. // mixkey()
  263. // Mixes a string seed into a key that is an array of integers, and
  264. // returns a shortened string seed that is equivalent to the result key.
  265. //
  266. function mixkey(seed, key) {
  267. var stringseed = seed + '', smear, j = 0;
  268. while (j < stringseed.length) {
  269. key[mask & j] =
  270. mask & ((smear ^= key[mask & j] * 19) + stringseed.charCodeAt(j++));
  271. }
  272. return tostring(key);
  273. }
  274. //
  275. // autoseed()
  276. // Returns an object for autoseeding, using window.crypto if available.
  277. //
  278. /** @param {Uint8Array|Navigator=} seed */
  279. function autoseed(seed) {
  280. try {
  281. global.crypto.getRandomValues(seed = new Uint8Array(width));
  282. return tostring(seed);
  283. } catch (e) {
  284. return [+new Date, global, (seed = global.navigator) && seed.plugins,
  285. global.screen, tostring(pool)];
  286. }
  287. }
  288. //
  289. // tostring()
  290. // Converts an array of charcodes to a string
  291. //
  292. function tostring(a) {
  293. return String.fromCharCode.apply(0, a);
  294. }
  295. //
  296. // When seedrandom.js is loaded, we immediately mix a few bits
  297. // from the built-in RNG into the entropy pool. Because we do
  298. // not want to intefere with determinstic PRNG state later,
  299. // seedrandom will not call math.random on its own again after
  300. // initialization.
  301. //
  302. mixkey(math[rngname](), pool);
  303. //
  304. // Nodejs and AMD support: export the implemenation as a module using
  305. // either convention.
  306. //
  307. if (module && module.exports) {
  308. module.exports = impl;
  309. } else if (define && define.amd) {
  310. define(function() { return impl; });
  311. }
  312. // End anonymous scope, and pass initial values.
  313. })(
  314. this, // global window object
  315. [], // pool: entropy pool starts empty
  316. Math, // math: package containing random, pow, and seedrandom
  317. 256, // width: each RC4 output is 0 <= x < 256
  318. 6, // chunks: at least six RC4 outputs for each double
  319. 52, // digits: there are 52 significant digits in a double
  320. (typeof module) == 'object' && module, // present in node.js
  321. (typeof define) == 'function' && define, // present with an AMD loader
  322. 'random'// rngname: name for Math.random and Math.seedrandom
  323. );