const CHARSET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";

export function decodeBase32(str: string): Uint8Array {
    if(typeof str !== "string")
        throw new Error("decodeBase32 argument must be a string");

    //remove padding and convert to uppercase
    let endIndex = str.length - 1;

    while(str[endIndex] === "=")
        endIndex--;

    str = str.substring(0, endIndex + 1).toUpperCase();

    //base32 encodes 5 bits into each character
    const array = new Uint8Array(str.length * 5 / 8 | 0);

    let val = 0;
    let idx = 0;
    let bits = 0;

    for(let i = 0; i < str.length; i++){
        const x = CHARSET.indexOf(str[i]);
        if(x === -1)
            throw new Error("Could not decode malformed Base32");

        //shift previous bits and insert new value
        val = (val << 5) | x;
        bits += 5;

        if(bits >= 8){
            bits -= 8;
            array[idx++] = val >>> bits;
        }
    }

    return array;
};