import { toUint8Array, fromUint8Array } from "../../../deno.land/x/base64@v0.2.1/base64url.js";
const decoder = new TextDecoder();
const encoder = new TextEncoder();
/** Serializes a Uint8Array to a hexadecimal string. */
function toHexString(buf) {
    return buf.reduce((hex, byte) => `${hex}${byte < 16 ? "0" : ""}${byte.toString(16)}`, "");
}
/** Deserializes a Uint8Array from a hexadecimal string. */
function fromHexString(hex) {
    const len = hex.length;
    if (len % 2 || !/^[0-9a-fA-F]+$/.test(hex)) {
        throw new TypeError("Invalid hex string.");
    }
    hex = hex.toLowerCase();
    const buf = new Uint8Array(Math.floor(len / 2));
    const end = len / 2;
    for (let i = 0; i < end; ++i) {
        buf[i] = parseInt(hex.substr(i * 2, 2), 16);
    }
    return buf;
}
/** Decodes a Uint8Array to utf8-, base64-, or hex-encoded string. */
export function decode(buf, encoding = "utf8") {
    if (/^utf-?8$/i.test(encoding)) {
        return decoder.decode(buf);
    }
    else if (/^base64$/i.test(encoding)) {
        return fromUint8Array(buf);
    }
    else if (/^hex(?:adecimal)?$/i.test(encoding)) {
        return toHexString(buf);
    }
    else {
        throw new TypeError("Unsupported string encoding.");
    }
}
export function encode(str, encoding = "utf8") {
    if (/^utf-?8$/i.test(encoding)) {
        return encoder.encode(str);
    }
    else if (/^base64$/i.test(encoding)) {
        return toUint8Array(str);
    }
    else if (/^hex(?:adecimal)?$/i.test(encoding)) {
        return fromHexString(str);
    }
    else {
        throw new TypeError("Unsupported string encoding.");
    }
}
