UNPKG

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