uuid.js 5.2 KB

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