UNPKG

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