predictable_random.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. module.exports = function nailfactory(boot) {
  2. var BOOT = boot || 0xbadebabe;
  3. function stringify(obj, replacer, spaces, cycleReplacer) {
  4. return JSON.stringify(obj, serializer(replacer, cycleReplacer), spaces)
  5. }
  6. function serializer(replacer, cycleReplacer) {
  7. var stack = [],
  8. keys = []
  9. if (cycleReplacer == null) cycleReplacer = function(key, value) {
  10. if (stack[0] === value) return "[Circular ~]"
  11. return "[Circular ~." + keys.slice(0, stack.indexOf(value)).join(".") + "]"
  12. }
  13. return function(key, value) {
  14. if (stack.length > 0) {
  15. var thisPos = stack.indexOf(this)~ thisPos ? stack.splice(thisPos + 1) : stack.push(this)~ thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key)
  16. if (~stack.indexOf(value)) value = cycleReplacer.call(this, key, value)
  17. } else stack.push(value)
  18. return replacer == null ? value : replacer.call(this, key, value)
  19. }
  20. }
  21. var Mash = function() {
  22. var n = BOOT;
  23. var mash = function(data) {
  24. if (data) {
  25. data = data.toString();
  26. for (var i = 0; i < data.length; i++) {
  27. n += data.charCodeAt(i);
  28. var h = 0.02519603282416938 * n;
  29. n = h >>> 0;
  30. h -= n;
  31. h *= n;
  32. n = h >>> 0;
  33. h -= n;
  34. n += h * 0x100000000; // 2^32
  35. }
  36. return (n >>> 0) * 2.3283064365386963e-10; // 2^-32
  37. } else {
  38. n = BOOT;
  39. }
  40. };
  41. return mash;
  42. };
  43. var uheprng = function(seed) {
  44. return (function() {
  45. var o = 48; // set the 'order' number of ENTROPY-holding 32-bit values
  46. var c = 1; // init the 'carry' used by the multiply-with-carry (MWC) algorithm
  47. var p = o; // init the 'phase' (max-1) of the intermediate variable pointer
  48. var s = new Array(o); // declare our intermediate variables array
  49. var i; // general purpose local
  50. var j; // general purpose local
  51. var k = 0; // general purpose local
  52. // when our "uheprng" is initially invoked our PRNG state is initialized from the
  53. // browser's own local PRNG. This is okay since although its generator might not
  54. // be wonderful, it's useful for establishing large startup entropy for our usage.
  55. var mash = new Mash(); // get a pointer to our high-performance "Mash" hash
  56. // fill the array with initial mash hash values
  57. for (i = 0; i < o; i++) {
  58. s[i] = mash(Math.random());
  59. }
  60. // this PRIVATE (internal access only) function is the heart of the multiply-with-carry
  61. // (MWC) PRNG algorithm. When called it returns a pseudo-random number in the form of a
  62. // 32-bit JavaScript fraction (0.0 to <1.0) it is a PRIVATE function used by the default
  63. // [0-1] return function, and by the random 'string(n)' function which returns 'n'
  64. // characters from 33 to 126.
  65. var rawprng = function() {
  66. if (++p >= o) {
  67. p = 0;
  68. }
  69. var t = 1768863 * s[p] + c * 2.3283064365386963e-10; // 2^-32
  70. return s[p] = t - (c = t | 0);
  71. };
  72. // this EXPORTED function is the default function returned by this library.
  73. // The values returned are integers in the range from 0 to range-1. We first
  74. // obtain two 32-bit fractions (from rawprng) to synthesize a single high
  75. // resolution 53-bit prng (0 to <1), then we multiply this by the caller's
  76. // "range" param and take the "floor" to return a equally probable integer.
  77. var random = function(range) {
  78. return Math.floor(range * (rawprng() + (rawprng() * 0x200000 | 0) * 1.1102230246251565e-16)); // 2^-53
  79. };
  80. // this EXPORTED function 'string(n)' returns a pseudo-random string of
  81. // 'n' printable characters ranging from chr(33) to chr(126) inclusive.
  82. random.string = function(count) {
  83. var i;
  84. var s = '';
  85. for (i = 0; i < count; i++) {
  86. s += String.fromCharCode(33 + random(94));
  87. }
  88. return s;
  89. };
  90. // this PRIVATE "hash" function is used to evolve the generator's internal
  91. // entropy state. It is also called by the EXPORTED addEntropy() function
  92. // which is used to pour entropy into the PRNG.
  93. var hash = function() {
  94. var args = Array.prototype.slice.call(arguments);
  95. for (i = 0; i < args.length; i++) {
  96. for (j = 0; j < o; j++) {
  97. s[j] -= mash(args[i]);
  98. if (s[j] < 0) {
  99. s[j] += 1;
  100. }
  101. }
  102. }
  103. };
  104. // this EXPORTED "clean string" function removes leading and trailing spaces and non-printing
  105. // control characters, including any embedded carriage-return (CR) and line-feed (LF) characters,
  106. // from any string it is handed. this is also used by the 'hashstring' function (below) to help
  107. // users always obtain the same EFFECTIVE uheprng seeding key.
  108. random.cleanString = function(inStr) {
  109. inStr = inStr.replace(/(^\s*)|(\s*$)/gi, ''); // remove any/all leading spaces
  110. inStr = inStr.replace(/[\x00-\x1F]/gi, ''); // remove any/all control characters
  111. inStr = inStr.replace(/\n /, '\n'); // remove any/all trailing spaces
  112. return inStr; // return the cleaned up result
  113. };
  114. // this EXPORTED "hash string" function hashes the provided character string after first removing
  115. // any leading or trailing spaces and ignoring any embedded carriage returns (CR) or Line Feeds (LF)
  116. random.hashString = function(inStr) {
  117. inStr = random.cleanString(inStr);
  118. mash(inStr); // use the string to evolve the 'mash' state
  119. for (i = 0; i < inStr.length; i++) { // scan through the characters in our string
  120. k = inStr.charCodeAt(i); // get the character code at the location
  121. for (j = 0; j < o; j++) { // "mash" it into the UHEPRNG state
  122. s[j] -= mash(k);
  123. if (s[j] < 0) {
  124. s[j] += 1;
  125. }
  126. }
  127. }
  128. };
  129. // this EXPORTED function allows you to seed the random generator.
  130. random.seed = function(seed) {
  131. if (typeof seed === 'undefined' || seed === null) {
  132. seed = Math.random();
  133. }
  134. if (typeof seed !== 'string') {
  135. seed = stringify(seed, function(key, value) {
  136. if (typeof value === 'function') {
  137. return (value).toString();
  138. }
  139. return value;
  140. });
  141. }
  142. random.initState();
  143. random.hashString(seed);
  144. };
  145. // this handy exported function is used to add entropy to our uheprng at any time
  146. random.addEntropy = function( /* accept zero or more arguments */ ) {
  147. var args = [];
  148. for (i = 0; i < arguments.length; i++) {
  149. args.push(arguments[i]);
  150. }
  151. hash(args.join(''));
  152. };
  153. // if we want to provide a deterministic startup context for our PRNG,
  154. // but without directly setting the internal state variables, this allows
  155. // us to initialize the mash hash and PRNG's internal state before providing
  156. // some hashing input
  157. random.initState = function() {
  158. mash(); // pass a null arg to force mash hash to init
  159. for (i = 0; i < o; i++) {
  160. s[i] = mash(' '); // fill the array with initial mash hash values
  161. }
  162. c = 1; // init our multiply-with-carry carry
  163. p = o; // init our phase
  164. };
  165. // we use this (optional) exported function to signal the JavaScript interpreter
  166. // that we're finished using the "Mash" hash function so that it can free up the
  167. // local "instance variables" is will have been maintaining. It's not strictly
  168. // necessary, of course, but it's good JavaScript citizenship.
  169. random.done = function() {
  170. mash = null;
  171. };
  172. // if we called "uheprng" with a seed value, then execute random.seed() before returning
  173. if (typeof seed !== 'undefined') {
  174. random.seed(seed);
  175. }
  176. // Returns a random integer between 0 (inclusive) and range (exclusive)
  177. random.range = function(range) {
  178. return random(range);
  179. };
  180. // Returns a random float between 0 (inclusive) and 1 (exclusive)
  181. random.random = function() {
  182. return random(Number.MAX_VALUE - 1) / Number.MAX_VALUE;
  183. };
  184. // Returns a random float between min (inclusive) and max (exclusive)
  185. random.floatBetween = function(min, max) {
  186. return random.random() * (max - min) + min;
  187. };
  188. // Returns a random integer between min (inclusive) and max (inclusive)
  189. random.intBetween = function(min, max) {
  190. return Math.floor(random.random() * (max - min + 1)) + min;
  191. };
  192. // when our main outer "uheprng" function is called, after setting up our
  193. // initial variables and entropic state, we return an "instance pointer"
  194. // to the internal anonymous function which can then be used to access
  195. // the uheprng's various exported functions. As with the ".done" function
  196. // above, we should set the returned value to 'null' once we're finished
  197. // using any of these functions.
  198. return random;
  199. }());
  200. };
  201. // Modification for use in node:
  202. uheprng.create = function(seed) {
  203. return new uheprng(seed);
  204. };
  205. return uheprng;
  206. }