uuid.js 7.1 KB

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