UNPKG

1.53 kBJavaScriptView Raw
1var bytesToUuid = require('./bytesToUuid');
2
3function uuidToBytes(uuid) {
4 // Note: We assume we're being passed a valid uuid string
5 var bytes = [];
6 uuid.replace(/[a-fA-F0-9]{2}/g, function(hex) {
7 bytes.push(parseInt(hex, 16));
8 });
9
10 return bytes;
11}
12
13function stringToBytes(str) {
14 str = unescape(encodeURIComponent(str)); // UTF8 escape
15 var bytes = new Array(str.length);
16 for (var i = 0; i < str.length; i++) {
17 bytes[i] = str.charCodeAt(i);
18 }
19 return bytes;
20}
21
22module.exports = function(name, version, hashfunc) {
23 var generateUUID = function(value, namespace, buf, offset) {
24 var off = buf && offset || 0;
25
26 if (typeof(value) == 'string') value = stringToBytes(value);
27 if (typeof(namespace) == 'string') namespace = uuidToBytes(namespace);
28
29 if (!Array.isArray(value)) throw TypeError('value must be an array of bytes');
30 if (!Array.isArray(namespace) || namespace.length !== 16) throw TypeError('namespace must be uuid string or an Array of 16 byte values');
31
32 // Per 4.3
33 var bytes = hashfunc(namespace.concat(value));
34 bytes[6] = (bytes[6] & 0x0f) | version;
35 bytes[8] = (bytes[8] & 0x3f) | 0x80;
36
37 if (buf) {
38 for (var idx = 0; idx < 16; ++idx) {
39 buf[off+idx] = bytes[idx];
40 }
41 }
42
43 return buf || bytesToUuid(bytes);
44 };
45
46 generateUUID.name = name;
47
48 // Pre-defined namespaces, per Appendix C
49 generateUUID.DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
50 generateUUID.URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
51
52 return generateUUID;
53};