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 = [];
|
16 |
|
17 | for (var i = 0; i < str.length; ++i) {
|
18 | bytes.push(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 | function generateUUID(value, namespace, buf, offset) {
|
28 | if (typeof value === 'string') {
|
29 | value = stringToBytes(value);
|
30 | }
|
31 |
|
32 | if (typeof namespace === 'string') {
|
33 | namespace = uuidToBytes(namespace);
|
34 | }
|
35 |
|
36 | if (!Array.isArray(value)) {
|
37 | throw TypeError('value must be an array of bytes');
|
38 | }
|
39 |
|
40 | if (!Array.isArray(namespace) || namespace.length !== 16) {
|
41 | throw TypeError('namespace must be uuid string or an Array of 16 byte values');
|
42 | }
|
43 |
|
44 |
|
45 | var bytes = hashfunc(namespace.concat(value));
|
46 | bytes[6] = bytes[6] & 0x0f | version;
|
47 | bytes[8] = bytes[8] & 0x3f | 0x80;
|
48 |
|
49 | if (buf) {
|
50 | offset = offset || 0;
|
51 |
|
52 | for (var i = 0; i < 16; ++i) {
|
53 | buf[offset + i] = bytes[i];
|
54 | }
|
55 |
|
56 | return buf;
|
57 | }
|
58 |
|
59 | return bytesToUuid(bytes);
|
60 | }
|
61 |
|
62 |
|
63 | try {
|
64 | generateUUID.name = name;
|
65 | } catch (err) {}
|
66 |
|
67 |
|
68 | generateUUID.DNS = DNS;
|
69 | generateUUID.URL = URL;
|
70 | return generateUUID;
|
71 | } |
\ | No newline at end of file |