1 | import stringify from './stringify.js';
|
2 | import parse from './parse.js';
|
3 |
|
4 | function stringToBytes(str) {
|
5 | str = unescape(encodeURIComponent(str));
|
6 |
|
7 | const bytes = [];
|
8 |
|
9 | for (let i = 0; i < str.length; ++i) {
|
10 | bytes.push(str.charCodeAt(i));
|
11 | }
|
12 |
|
13 | return bytes;
|
14 | }
|
15 |
|
16 | export const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
|
17 | export const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
|
18 | export default function (name, version, hashfunc) {
|
19 | function generateUUID(value, namespace, buf, offset) {
|
20 | if (typeof value === 'string') {
|
21 | value = stringToBytes(value);
|
22 | }
|
23 |
|
24 | if (typeof namespace === 'string') {
|
25 | namespace = parse(namespace);
|
26 | }
|
27 |
|
28 | if (namespace.length !== 16) {
|
29 | throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');
|
30 | }
|
31 |
|
32 |
|
33 |
|
34 |
|
35 | let bytes = new Uint8Array(16 + value.length);
|
36 | bytes.set(namespace);
|
37 | bytes.set(value, namespace.length);
|
38 | bytes = hashfunc(bytes);
|
39 | bytes[6] = bytes[6] & 0x0f | version;
|
40 | bytes[8] = bytes[8] & 0x3f | 0x80;
|
41 |
|
42 | if (buf) {
|
43 | offset = offset || 0;
|
44 |
|
45 | for (let i = 0; i < 16; ++i) {
|
46 | buf[offset + i] = bytes[i];
|
47 | }
|
48 |
|
49 | return buf;
|
50 | }
|
51 |
|
52 | return stringify(bytes);
|
53 | }
|
54 |
|
55 |
|
56 | try {
|
57 | generateUUID.name = name;
|
58 | } catch (err) {}
|
59 |
|
60 |
|
61 | generateUUID.DNS = DNS;
|
62 | generateUUID.URL = URL;
|
63 | return generateUUID;
|
64 | } |
\ | No newline at end of file |