All files / uuid / _common.ts

100.00% Branches 10/10
100.00% Functions 2/2
100.00% Lines 59/59
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
 
 
 
x33
 
x33
x8448
x8448
 
 
 
 
 
x33
x51036
x51036
x51036
x51036
x51036
x51036
x51036
x51036
x51036
x51036
x51036
x51036
x51036
x51036
x51036
x51036
x51036
x51036
x51036
x51036
x51036
 
 
 
 
x51036
x51036
 
 
 
 
 
x33
x20015
x20015
 
x20015
x100075
x100075
x100075
x60045
x60045
x60045
x60045
x100075
x20015
x20015
x20015
x20015
x20015
x20015
x100075
x20015
x20015
x20015
x20015
x20015
x20015
x20015
x20015
x100075
x100075
 
x20015
x20015













































































// Copyright 2018-2026 the Deno authors. MIT license.
// This module is browser compatible.

const hexTable: string[] = [];

for (let i = 0; i < 256; ++i) {
  hexTable.push(i < 0x10 ? "0" + i.toString(16) : i.toString(16));
}

/**
 * Converts the byte array to a UUID string
 * @param bytes Used to convert Byte to Hex
 */
export function bytesToUuid(bytes: number[] | Uint8Array): string {
  return (
    hexTable[bytes[0]!]! +
    hexTable[bytes[1]!]! +
    hexTable[bytes[2]!]! +
    hexTable[bytes[3]!]! +
    "-" +
    hexTable[bytes[4]!]! +
    hexTable[bytes[5]!]! +
    "-" +
    hexTable[bytes[6]!]! +
    hexTable[bytes[7]!]! +
    "-" +
    hexTable[bytes[8]!]! +
    hexTable[bytes[9]!]! +
    "-" +
    hexTable[bytes[10]!]! +
    hexTable[bytes[11]!]! +
    hexTable[bytes[12]!]! +
    hexTable[bytes[13]!]! +
    hexTable[bytes[14]!]! +
    hexTable[bytes[15]!]!
    // Use .toLowerCase() to avoid the v8 engine memory issue
    // when concatenating strings with "+" operator. See:
    // - https://issues.chromium.org/issues/42206473
    // - https://github.com/uuidjs/uuid/pull/434
  ).toLowerCase();
}

/**
 * Converts a string to a byte array by converting the hex value to a number.
 * @param uuid Value that gets converted.
 */
export function uuidToBytes(uuid: string): Uint8Array {
  const bytes = new Uint8Array(16);
  let i = 0;

  for (const str of uuid.split("-")) {
    const hex = parseInt(str, 16);
    switch (str.length) {
      case 4: {
        bytes[i++] = (hex >>> 8) & 0xff;
        bytes[i++] = hex & 0xff;
        break;
      }
      case 8: {
        bytes[i++] = (hex >>> 24) & 0xff;
        bytes[i++] = (hex >>> 16) & 0xff;
        bytes[i++] = (hex >>> 8) & 0xff;
        bytes[i++] = hex & 0xff;
        break;
      }
      case 12: {
        bytes[i++] = (hex / 0x10000000000) & 0xff;
        bytes[i++] = (hex / 0x100000000) & 0xff;
        bytes[i++] = (hex >>> 24) & 0xff;
        bytes[i++] = (hex >>> 16) & 0xff;
        bytes[i++] = (hex >>> 8) & 0xff;
        bytes[i++] = hex & 0xff;
        break;
      }
    }
  }

  return bytes;
}