uuid.js 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. // uuid.js
  2. //
  3. // Copyright (c) 2010-2012 Robert Kieffer
  4. // MIT License - http://opensource.org/licenses/mit-license.php
  5. // Unique ID creation requires a high quality random # generator. We feature
  6. // detect to determine the best RNG source, normalizing to a function that
  7. // returns 128-bits of randomness, since that's what's usually required
  8. var _rng = require('./rng');
  9. // Buffer class to use,
  10. // we can't use `Buffer || Array` otherwise Buffer would be
  11. // shimmed by browserify and added to the browser build
  12. var BufferClass = require('./buffer');
  13. // Maps for number <-> hex string conversion
  14. var _byteToHex = [];
  15. var _hexToByte = {};
  16. for (var i = 0; i < 256; i++) {
  17. _byteToHex[i] = (i + 0x100).toString(16).substr(1);
  18. _hexToByte[_byteToHex[i]] = i;
  19. }
  20. // **`parse()` - Parse a UUID into it's component bytes**
  21. function parse(s, buf, offset) {
  22. var i = (buf && offset) || 0, ii = 0;
  23. buf = buf || [];
  24. s.toLowerCase().replace(/[0-9a-f]{2}/g, function(oct) {
  25. if (ii < 16) { // Don't overflow!
  26. buf[i + ii++] = _hexToByte[oct];
  27. }
  28. });
  29. // Zero out remaining bytes if string was short
  30. while (ii < 16) {
  31. buf[i + ii++] = 0;
  32. }
  33. return buf;
  34. }
  35. // **`unparse()` - Convert UUID byte array (ala parse()) into a string**
  36. function unparse(buf, offset) {
  37. var i = offset || 0, bth = _byteToHex;
  38. return bth[buf[i++]] + bth[buf[i++]] +
  39. bth[buf[i++]] + bth[buf[i++]] + '-' +
  40. bth[buf[i++]] + bth[buf[i++]] + '-' +
  41. bth[buf[i++]] + bth[buf[i++]] + '-' +
  42. bth[buf[i++]] + bth[buf[i++]] + '-' +
  43. bth[buf[i++]] + bth[buf[i++]] +
  44. bth[buf[i++]] + bth[buf[i++]] +
  45. bth[buf[i++]] + bth[buf[i++]];
  46. }
  47. // **`v1()` - Generate time-based UUID**
  48. //
  49. // Inspired by https://github.com/LiosK/UUID.js
  50. // and http://docs.python.org/library/uuid.html
  51. // random #'s we need to init node and clockseq
  52. var _seedBytes = _rng();
  53. // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
  54. var _nodeId = [
  55. _seedBytes[0] | 0x01,
  56. _seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5]
  57. ];
  58. // Per 4.2.2, randomize (14 bit) clockseq
  59. var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 0x3fff;
  60. // Previous uuid creation time
  61. var _lastMSecs = 0, _lastNSecs = 0;
  62. // See https://github.com/broofa/node-uuid for API details
  63. function v1(options, buf, offset) {
  64. var i = buf && offset || 0;
  65. var b = buf || [];
  66. options = options || {};
  67. var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq;
  68. // UUID timestamps are 100 nano-second units since the Gregorian epoch,
  69. // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
  70. // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
  71. // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
  72. var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime();
  73. // Per 4.2.1.2, use count of uuid's generated during the current clock
  74. // cycle to simulate higher resolution clock
  75. var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1;
  76. // Time since last uuid creation (in msecs)
  77. var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;
  78. // Per 4.2.1.2, Bump clockseq on clock regression
  79. if (dt < 0 && options.clockseq === undefined) {
  80. clockseq = clockseq + 1 & 0x3fff;
  81. }
  82. // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
  83. // time interval
  84. if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
  85. nsecs = 0;
  86. }
  87. // Per 4.2.1.2 Throw error if too many uuids are requested
  88. if (nsecs >= 10000) {
  89. throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec');
  90. }
  91. _lastMSecs = msecs;
  92. _lastNSecs = nsecs;
  93. _clockseq = clockseq;
  94. // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
  95. msecs += 12219292800000;
  96. // `time_low`
  97. var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
  98. b[i++] = tl >>> 24 & 0xff;
  99. b[i++] = tl >>> 16 & 0xff;
  100. b[i++] = tl >>> 8 & 0xff;
  101. b[i++] = tl & 0xff;
  102. // `time_mid`
  103. var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;
  104. b[i++] = tmh >>> 8 & 0xff;
  105. b[i++] = tmh & 0xff;
  106. // `time_high_and_version`
  107. b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
  108. b[i++] = tmh >>> 16 & 0xff;
  109. // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
  110. b[i++] = clockseq >>> 8 | 0x80;
  111. // `clock_seq_low`
  112. b[i++] = clockseq & 0xff;
  113. // `node`
  114. var node = options.node || _nodeId;
  115. for (var n = 0; n < 6; n++) {
  116. b[i + n] = node[n];
  117. }
  118. return buf ? buf : unparse(b);
  119. }
  120. // **`v4()` - Generate random UUID**
  121. // See https://github.com/broofa/node-uuid for API details
  122. function v4(options, buf, offset) {
  123. // Deprecated - 'format' argument, as supported in v1.2
  124. var i = buf && offset || 0;
  125. if (typeof(options) == 'string') {
  126. buf = options == 'binary' ? new BufferClass(16) : null;
  127. options = null;
  128. }
  129. options = options || {};
  130. var rnds = options.random || (options.rng || _rng)();
  131. // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
  132. rnds[6] = (rnds[6] & 0x0f) | 0x40;
  133. rnds[8] = (rnds[8] & 0x3f) | 0x80;
  134. // Copy bytes to buffer, if provided
  135. if (buf) {
  136. for (var ii = 0; ii < 16; ii++) {
  137. buf[i + ii] = rnds[ii];
  138. }
  139. }
  140. return buf || unparse(rnds);
  141. }
  142. // Export public API
  143. var uuid = v4;
  144. uuid.v1 = v1;
  145. uuid.v4 = v4;
  146. uuid.parse = parse;
  147. uuid.unparse = unparse;
  148. uuid.BufferClass = BufferClass;
  149. module.exports = uuid;