2024-01-01 21:11:32 +00:00
|
|
|
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
2022-03-01 04:25:50 +00:00
|
|
|
// This module is browser compatible.
|
|
|
|
|
2024-08-08 09:45:56 +00:00
|
|
|
const hexTable: string[] = [];
|
|
|
|
|
|
|
|
for (let i = 0; i < 256; ++i) {
|
|
|
|
hexTable.push(i < 0x10 ? "0" + i.toString(16) : i.toString(16));
|
|
|
|
}
|
|
|
|
|
2020-10-01 09:40:40 +00:00
|
|
|
/**
|
|
|
|
* Converts the byte array to a UUID string
|
|
|
|
* @param bytes Used to convert Byte to Hex
|
|
|
|
*/
|
2020-04-15 14:38:05 +00:00
|
|
|
export function bytesToUuid(bytes: number[] | Uint8Array): string {
|
2024-08-08 09:45:56 +00:00
|
|
|
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();
|
2020-04-15 14:38:05 +00:00
|
|
|
}
|
2020-04-27 12:49:34 +00:00
|
|
|
|
2020-10-01 09:40:40 +00:00
|
|
|
/**
|
2021-02-02 03:16:27 +00:00
|
|
|
* Converts a string to a byte array by converting the hex value to a number.
|
|
|
|
* @param uuid Value that gets converted.
|
2020-10-01 09:40:40 +00:00
|
|
|
*/
|
2024-05-31 11:10:04 +00:00
|
|
|
export function uuidToBytes(uuid: string): Uint8Array {
|
2024-08-10 06:48:05 +00:00
|
|
|
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;
|
2020-04-27 12:49:34 +00:00
|
|
|
}
|