uuid.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. // uuid.js
  2. //
  3. // (c) 2010-2012 Robert Kieffer
  4. // MIT License
  5. // https://github.com/broofa/node-uuid
  6. (function() {
  7. var _global = this;
  8. // Unique ID creation requires a high quality random # generator. We feature
  9. // detect to determine the best RNG source, normalizing to a function that
  10. // returns 128-bits of randomness, since that's what's usually required
  11. var _rng;
  12. // Node.js crypto-based RNG - http://nodejs.org/docs/v0.6.2/api/crypto.html
  13. //
  14. // Moderately fast, high quality
  15. if (typeof(require) == 'function') {
  16. try {
  17. var _rb = require('crypto').randomBytes;
  18. _rng = _rb && function() {return _rb(16);};
  19. } catch(e) {}
  20. }
  21. if (!_rng && _global.crypto && crypto.getRandomValues) {
  22. // WHATWG crypto-based RNG - http://wiki.whatwg.org/wiki/Crypto
  23. //
  24. // Moderately fast, high quality
  25. var _rnds8 = new Uint8Array(16);
  26. _rng = function whatwgRNG() {
  27. crypto.getRandomValues(_rnds8);
  28. return _rnds8;
  29. };
  30. }
  31. if (!_rng) {
  32. // Math.random()-based (RNG)
  33. //
  34. // If all else fails, use Math.random(). It's fast, but is of unspecified
  35. // quality.
  36. var _rnds = new Array(16);
  37. _rng = function() {
  38. for (var i = 0, r; i < 16; i++) {
  39. if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
  40. _rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
  41. }
  42. return _rnds;
  43. };
  44. }
  45. // Buffer class to use
  46. var BufferClass = typeof(Buffer) == 'function' ? Buffer : Array;
  47. // Maps for number <-> hex string conversion
  48. var _byteToHex = [];
  49. var _hexToByte = {};
  50. for (var i = 0; i < 256; i++) {
  51. _byteToHex[i] = (i + 0x100).toString(16).substr(1);
  52. _hexToByte[_byteToHex[i]] = i;
  53. }
  54. // **`parse()` - Parse a UUID into it's component bytes**
  55. function parse(s, buf, offset) {
  56. var i = (buf && offset) || 0, ii = 0;
  57. buf = buf || [];
  58. s.toLowerCase().replace(/[0-9a-f]{2}/g, function(oct) {
  59. if (ii < 16) { // Don't overflow!
  60. buf[i + ii++] = _hexToByte[oct];
  61. }
  62. });
  63. // Zero out remaining bytes if string was short
  64. while (ii < 16) {
  65. buf[i + ii++] = 0;
  66. }
  67. return buf;
  68. }
  69. // **`unparse()` - Convert UUID byte array (ala parse()) into a string**
  70. function unparse(buf, offset) {
  71. var i = offset || 0, bth = _byteToHex;
  72. return bth[buf[i++]] + bth[buf[i++]] +
  73. bth[buf[i++]] + bth[buf[i++]] + '-' +
  74. bth[buf[i++]] + bth[buf[i++]] + '-' +
  75. bth[buf[i++]] + bth[buf[i++]] + '-' +
  76. bth[buf[i++]] + bth[buf[i++]] + '-' +
  77. bth[buf[i++]] + bth[buf[i++]] +
  78. bth[buf[i++]] + bth[buf[i++]] +
  79. bth[buf[i++]] + bth[buf[i++]];
  80. }
  81. // **`v1()` - Generate time-based UUID**
  82. //
  83. // Inspired by https://github.com/LiosK/UUID.js
  84. // and http://docs.python.org/library/uuid.html
  85. // random #'s we need to init node and clockseq
  86. var _seedBytes = _rng();
  87. // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
  88. var _nodeId = [
  89. _seedBytes[0] | 0x01,
  90. _seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5]
  91. ];
  92. // Per 4.2.2, randomize (14 bit) clockseq
  93. var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 0x3fff;
  94. // Previous uuid creation time
  95. var _lastMSecs = 0, _lastNSecs = 0;
  96. // See https://github.com/broofa/node-uuid for API details
  97. function v1(options, buf, offset) {
  98. var i = buf && offset || 0;
  99. var b = buf || [];
  100. options = options || {};
  101. var clockseq = options.clockseq != null ? options.clockseq : _clockseq;
  102. // UUID timestamps are 100 nano-second units since the Gregorian epoch,
  103. // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
  104. // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
  105. // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
  106. var msecs = options.msecs != null ? options.msecs : new Date().getTime();
  107. // Per 4.2.1.2, use count of uuid's generated during the current clock
  108. // cycle to simulate higher resolution clock
  109. var nsecs = options.nsecs != null ? options.nsecs : _lastNSecs + 1;
  110. // Time since last uuid creation (in msecs)
  111. var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;
  112. // Per 4.2.1.2, Bump clockseq on clock regression
  113. if (dt < 0 && options.clockseq == null) {
  114. clockseq = clockseq + 1 & 0x3fff;
  115. }
  116. // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
  117. // time interval
  118. if ((dt < 0 || msecs > _lastMSecs) && options.nsecs == null) {
  119. nsecs = 0;
  120. }
  121. // Per 4.2.1.2 Throw error if too many uuids are requested
  122. if (nsecs >= 10000) {
  123. throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec');
  124. }
  125. _lastMSecs = msecs;
  126. _lastNSecs = nsecs;
  127. _clockseq = clockseq;
  128. // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
  129. msecs += 12219292800000;
  130. // `time_low`
  131. var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
  132. b[i++] = tl >>> 24 & 0xff;
  133. b[i++] = tl >>> 16 & 0xff;
  134. b[i++] = tl >>> 8 & 0xff;
  135. b[i++] = tl & 0xff;
  136. // `time_mid`
  137. var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;
  138. b[i++] = tmh >>> 8 & 0xff;
  139. b[i++] = tmh & 0xff;
  140. // `time_high_and_version`
  141. b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
  142. b[i++] = tmh >>> 16 & 0xff;
  143. // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
  144. b[i++] = clockseq >>> 8 | 0x80;
  145. // `clock_seq_low`
  146. b[i++] = clockseq & 0xff;
  147. // `node`
  148. var node = options.node || _nodeId;
  149. for (var n = 0; n < 6; n++) {
  150. b[i + n] = node[n];
  151. }
  152. return buf ? buf : unparse(b);
  153. }
  154. // **`v4()` - Generate random UUID**
  155. // See https://github.com/broofa/node-uuid for API details
  156. function v4(options, buf, offset) {
  157. // Deprecated - 'format' argument, as supported in v1.2
  158. var i = buf && offset || 0;
  159. if (typeof(options) == 'string') {
  160. buf = options == 'binary' ? new BufferClass(16) : null;
  161. options = null;
  162. }
  163. options = options || {};
  164. var rnds = options.random || (options.rng || _rng)();
  165. // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
  166. rnds[6] = (rnds[6] & 0x0f) | 0x40;
  167. rnds[8] = (rnds[8] & 0x3f) | 0x80;
  168. // Copy bytes to buffer, if provided
  169. if (buf) {
  170. for (var ii = 0; ii < 16; ii++) {
  171. buf[i + ii] = rnds[ii];
  172. }
  173. }
  174. return buf || unparse(rnds);
  175. }
  176. // Export public API
  177. var uuid = v4;
  178. uuid.v1 = v1;
  179. uuid.v4 = v4;
  180. uuid.parse = parse;
  181. uuid.unparse = unparse;
  182. uuid.BufferClass = BufferClass;
  183. if (_global.define && define.amd) {
  184. // Publish as AMD module
  185. define(function() {return uuid;});
  186. } else if (typeof(module) != 'undefined' && module.exports) {
  187. // Publish as node.js module
  188. module.exports = uuid;
  189. } else {
  190. // Publish as global (in browsers)
  191. var _previousRoot = _global.uuid;
  192. // **`noConflict()` - (browser only) to reset global 'uuid' var**
  193. uuid.noConflict = function() {
  194. _global.uuid = _previousRoot;
  195. return uuid;
  196. };
  197. _global.uuid = uuid;
  198. }
  199. }());