UNPKG

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