1 | import bytesToUuid from './bytesToUuid.js';
|
2 |
|
3 | function uuidToBytes(uuid) {
|
4 |
|
5 | var bytes = [];
|
6 | uuid.replace(/[a-fA-F0-9]{2}/g, function (hex) {
|
7 | bytes.push(parseInt(hex, 16));
|
8 | });
|
9 | return bytes;
|
10 | }
|
11 |
|
12 | function stringToBytes(str) {
|
13 | str = unescape(encodeURIComponent(str));
|
14 |
|
15 | var bytes = new Array(str.length);
|
16 |
|
17 | for (var i = 0; i < str.length; i++) {
|
18 | bytes[i] = str.charCodeAt(i);
|
19 | }
|
20 |
|
21 | return bytes;
|
22 | }
|
23 |
|
24 | export var DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
|
25 | export var URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
|
26 | export default function (name, version, hashfunc) {
|
27 | var generateUUID = function generateUUID(value, namespace, buf, offset) {
|
28 | var off = buf && offset || 0;
|
29 | if (typeof value == 'string') value = stringToBytes(value);
|
30 | if (typeof namespace == 'string') namespace = uuidToBytes(namespace);
|
31 | if (!Array.isArray(value)) throw TypeError('value must be an array of bytes');
|
32 | if (!Array.isArray(namespace) || namespace.length !== 16) throw TypeError('namespace must be uuid string or an Array of 16 byte values');
|
33 |
|
34 | var bytes = hashfunc(namespace.concat(value));
|
35 | bytes[6] = bytes[6] & 0x0f | version;
|
36 | bytes[8] = bytes[8] & 0x3f | 0x80;
|
37 |
|
38 | if (buf) {
|
39 | for (var idx = 0; idx < 16; ++idx) {
|
40 | buf[off + idx] = bytes[idx];
|
41 | }
|
42 | }
|
43 |
|
44 | return buf || bytesToUuid(bytes);
|
45 | };
|
46 |
|
47 |
|
48 | try {
|
49 | generateUUID.name = name;
|
50 | } catch (err) {}
|
51 |
|
52 |
|
53 | generateUUID.DNS = DNS;
|
54 | generateUUID.URL = URL;
|
55 | return generateUUID;
|
56 | } |
\ | No newline at end of file |