forked from uuidjs/uuid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuuid.js
80 lines (70 loc) · 2.1 KB
/
uuid.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
(function() {
/*
* Generate a RFC4122(v4) UUID
*
* Documentation at https://github.com/broofa/node-uuid
*/
// Use node.js Buffer class if available, otherwise use the Array class
var BufferClass = typeof(Buffer) == 'function' ? Buffer : Array;
// Buffer used for generating string uuids
var _buf = new BufferClass(16);
// Cache number <-> hex string for octet values
var toString = [];
var toNumber = {};
for (var i = 0; i < 256; i++) {
toString[i] = (i + 0x100).toString(16).substr(1);
toNumber[toString[i]] = i;
}
function parse(s) {
var buf = new BufferClass(16);
var i = 0;
s.toLowerCase().replace(/[0-9a-f][0-9a-f]/g, function(octet) {
buf[i++] = toNumber[octet];
});
return buf;
}
function unparse(buf) {
var tos = toString, b = buf;
return tos[b[0]] + tos[b[1]] + tos[b[2]] + tos[b[3]] + '-' +
tos[b[4]] + tos[b[5]] + '-' +
tos[b[6]] + tos[b[7]] + '-' +
tos[b[8]] + tos[b[9]] + '-' +
tos[b[10]] + tos[b[11]] + tos[b[12]] +
tos[b[13]] + tos[b[14]] + tos[b[15]];
}
var b32 = 0x100000000, ff = 0xff;
function uuid(fmt, buf, offset) {
var b = fmt != 'binary' ? _buf : (buf ? buf : new BufferClass(16));
var i = buf && offset || 0;
var r = Math.random()*b32;
b[i++] = r & ff;
b[i++] = r>>>8 & ff;
b[i++] = r>>>16 & ff;
b[i++] = r>>>24 & ff;
r = Math.random()*b32;
b[i++] = r & ff;
b[i++] = r>>>8 & ff;
b[i++] = r>>>16 & 0x0f | 0x40; // See RFC4122 sect. 4.1.3
b[i++] = r>>>24 & ff;
r = Math.random()*b32;
b[i++] = r & 0x3f | 0x80; // See RFC4122 sect. 4.4
b[i++] = r>>>8 & ff;
b[i++] = r>>>16 & ff;
b[i++] = r>>>24 & ff;
r = Math.random()*b32;
b[i++] = r & ff;
b[i++] = r>>>8 & ff;
b[i++] = r>>>16 & ff;
b[i++] = r>>>24 & ff;
return fmt === undefined ? unparse(b) : b;
};
uuid.parse = parse;
uuid.unparse = unparse;
uuid.BufferClass = BufferClass;
if (typeof(module) != 'undefined') {
module.exports = uuid;
} else {
// In browser? Set as top-level function
this.uuid = uuid;
}
})();