UNPKG

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