const BASE64_DEC: {[key: string]: number} = {};
[... 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'].forEach(
    (c, i) => BASE64_DEC[c] = i);
BASE64_DEC['+'] = BASE64_DEC['-'] = 62;
BASE64_DEC['/'] = BASE64_DEC['_'] = 63;

export function decodeBase64(s: string): Uint8Array {
    const bs = new Uint8Array(Math.floor(s.length * 3/4));
    let i = 0;
    let j = 0;
    while (i < s.length) {
        const v1 = BASE64_DEC[s[i++]];
        const v2 = BASE64_DEC[s[i++]];
        const v3 = BASE64_DEC[s[i++]];
        const v4 = BASE64_DEC[s[i++]];
        const v = (v1 << 18) | (v2 << 12) | (v3 << 6) | v4;
        bs[j++] = (v >> 16) & 255;
        if (v3 === void 0) break;
        bs[j++] = (v >> 8) & 255;
        if (v4 === void 0) break;
        bs[j++] = v & 255;
    }
    return bs.subarray(0, j);
}

const BASE64_ENC = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'

export function encodeBase64(bs: Uint8Array): string {
    let s = '';
    let buffer = 0;
    let bitcount = 0;
    for (let b of bs) {
        buffer = ((buffer & 0x3f) << 8) | b;
        bitcount += 8;
        while (bitcount >= 6) {
            bitcount -= 6;
            const v = (buffer >> bitcount) & 0x3f;
            s = s + BASE64_ENC[v];
        }
    }
    if (bitcount > 0) {
        const v = (buffer << (6 - bitcount)) & 0x3f;
        s = s + BASE64_ENC[v];
    }
    return s;
}
