magiclen / base64-url

Base64 encode, decode, escape and unescape for URL applications.
MIT License
11 stars 0 forks source link

Set decode length in bits #3

Open kaimast opened 1 year ago

kaimast commented 1 year ago

The following code to decode a u64 from base64 works fine but is quite ugly:

        let mut array = [0u8; 9];
        base64_url::decode_to_slice(str_rep, &mut array).expect("Not a valid base64 encoding");
        u64::from_le_bytes(array[..8].try_into().unwrap())

The problem here is that the encoded u64 is 11 characters which amounts to 66 bits, not 64. Ideally, I would like to have a decode function that can set the length explicitly or detects it based on the size of the slice.

For example, this would look much nicer:

        let mut array = [0u8; std::mem::size_of::<u64>()];
        base64_url::decode_to_slice_with_length(str_rep, &mut array, u64::BITS).expect("Not a valid base64 encoding");
        u64::from_le_bytes(array)
magiclen commented 1 year ago

I believe it is an upstream issue.

use base64::Engine;

fn main() {
    let u = 1u64;
    let u_bytes = u.to_le_bytes();

    let base64_str = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(u_bytes);

    println!("{u:?} -> {base64_str}");

    let mut buffer = [0u8; std::mem::size_of::<u64>()];

    let length = base64::engine::general_purpose::URL_SAFE_NO_PAD.decode_slice(base64_str.as_str(), &mut buffer).unwrap(); // OutputSliceTooSmall error occurs

    println!("{base64_str} -> {:?}", &buffer[..length])
}