const hexTable = new TextEncoder().encode("0123456789abcdef");const textEncoder = new TextEncoder();const textDecoder = new TextDecoder();
function errInvalidByte(byte: number) { return new TypeError(`Invalid byte '${String.fromCharCode(byte)}'`);}
function errLength() { return new RangeError("Odd length hex string");}
function fromHexChar(byte: number): number { if (48 <= byte && byte <= 57) return byte - 48; if (97 <= byte && byte <= 102) return byte - 97 + 10; if (65 <= byte && byte <= 70) return byte - 65 + 10;
throw errInvalidByte(byte);}
export function encode(src: Uint8Array): Uint8Array { const dst = new Uint8Array(src.length * 2); for (let i = 0; i < dst.length; i++) { const v = src[i]; dst[i * 2] = hexTable[v >> 4]; dst[i * 2 + 1] = hexTable[v & 0x0f]; } return dst;}
export function encodeHex(src: string | Uint8Array | ArrayBuffer): string { let u8: Uint8Array;
if (src instanceof Uint8Array) { u8 = src; } else if (src instanceof ArrayBuffer) { u8 = new Uint8Array(src); } else if (typeof src === "string") { u8 = textEncoder.encode(src); } else { throw new TypeError(`Invalid input type: ${typeof src}`); }
const dst = new Uint8Array(u8.length * 2); for (let i = 0; i < dst.length; i++) { const v = u8[i]; dst[i * 2] = hexTable[v >> 4]; dst[i * 2 + 1] = hexTable[v & 0x0f]; } return textDecoder.decode(dst);}
export function decode(src: Uint8Array): Uint8Array { const dst = new Uint8Array(src.length / 2); for (let i = 0; i < dst.length; i++) { const a = fromHexChar(src[i * 2]); const b = fromHexChar(src[i * 2 + 1]); dst[i] = (a << 4) | b; }
if (src.length % 2 === 1) { fromHexChar(src[dst.length * 2]); throw errLength(); }
return dst;}
export function decodeHex(src: string): Uint8Array { const u8 = textEncoder.encode(src); const dst = new Uint8Array(u8.length / 2); for (let i = 0; i < dst.length; i++) { const a = fromHexChar(u8[i * 2]); const b = fromHexChar(u8[i * 2 + 1]); dst[i] = (a << 4) | b; }
if (u8.length % 2 === 1) { fromHexChar(u8[dst.length * 2]); throw errLength(); }
return dst;}