1
+ import validate from './validate.mjs' ;
2
+
3
+ /**
4
+ * Convert array of 16 byte values to UUID string format of the form:
5
+ * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
6
+ */
7
+ const byteToHex = [ ] ;
8
+
9
+ for ( let i = 0 ; i < 256 ; ++ i ) {
10
+ byteToHex . push ( ( i + 0x100 ) . toString ( 16 ) . slice ( 1 ) ) ;
11
+ }
12
+
13
+ export function unsafeStringify ( arr , offset = 0 ) {
14
+ // Note: Be careful editing this code! It's been tuned for performance
15
+ // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
16
+ return (
17
+ byteToHex [ arr [ offset + 0 ] ] +
18
+ byteToHex [ arr [ offset + 1 ] ] +
19
+ byteToHex [ arr [ offset + 2 ] ] +
20
+ byteToHex [ arr [ offset + 3 ] ] +
21
+ '-' +
22
+ byteToHex [ arr [ offset + 4 ] ] +
23
+ byteToHex [ arr [ offset + 5 ] ] +
24
+ '-' +
25
+ byteToHex [ arr [ offset + 6 ] ] +
26
+ byteToHex [ arr [ offset + 7 ] ] +
27
+ '-' +
28
+ byteToHex [ arr [ offset + 8 ] ] +
29
+ byteToHex [ arr [ offset + 9 ] ] +
30
+ '-' +
31
+ byteToHex [ arr [ offset + 10 ] ] +
32
+ byteToHex [ arr [ offset + 11 ] ] +
33
+ byteToHex [ arr [ offset + 12 ] ] +
34
+ byteToHex [ arr [ offset + 13 ] ] +
35
+ byteToHex [ arr [ offset + 14 ] ] +
36
+ byteToHex [ arr [ offset + 15 ] ]
37
+ ) . toLowerCase ( ) ;
38
+ }
39
+
40
+ function stringify ( arr , offset = 0 ) {
41
+ const uuid = unsafeStringify ( arr , offset ) ;
42
+ // Consistency check for valid UUID. If this throws, it's likely due to one
43
+ // of the following:
44
+ // - One or more input array values don't map to a hex octet (leading to
45
+ // "undefined" in the uuid)
46
+ // - Invalid input values for the RFC `version` or `variant` fields
47
+ if ( ! validate ( uuid ) ) {
48
+ throw TypeError ( 'Stringified UUID is invalid' ) ;
49
+ }
50
+
51
+ return uuid ;
52
+ }
53
+
54
+ export default stringify ;
0 commit comments