predictable_random.js 11 KB

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