DEV Community

Implementing Base64 from scratch in Rust

Tiemen on August 02, 2021

In this article we're taking a closer look at the Base64 algorithm and implement an encoder and decoder from scratch using the Rust programming lan...
Collapse
 
minigamedev profile image
Mossa •

You're missing encode and decode. You have a description of them, maybe it is enough to write it myself.

Collapse
 
minigamedev profile image
Mossa •

Oh, I'm a bit wrong here: The included encode and decode calls themselves, which is not entirely correct. The version that works is here:

fn encode(input: &String) -> String {
    encoder::encode_using_alphabet(&Classic, input.as_bytes())
}

fn decode(input: &String) -> Result<String, CLIError> {
    let decoded =
        decoder::decode_using_alphabet(Classic, input).map_err(|_| CLIError::DecodingError)?;

    let decoded_as_string = std::str::from_utf8(&decoded).map_err(|_| CLIError::DecodingError)?;

    Ok(decoded_as_string.to_owned())
}
Enter fullscreen mode Exit fullscreen mode

I love how this example is self-contained enough that I can actually guess the intent.

Collapse
 
tiemen profile image
Tiemen • • Edited

The implementation of these functions was described in the chapter "Piecing it together" (third code block). It's pretty much what you wrote here, instead I used the convenience function that assumes you want to encode and decode against the classic alphabet :)

But maybe I'm misinterpreting your comment. In any case, thank you for feedback so far!

Thread Thread
 
minigamedev profile image
Mossa •

Thanks for the reply. I went through it the first time, and could interpret it as a first time reader. This is no longer the case, so I don't know why I wrote that. Sorry.

But I think it is okay as is now.

Do you want me to delete these corrections now that they have been remedied?

Thread Thread
 
tiemen profile image
Tiemen •

No worries! I appreciate the feedback regardless ☺️ Don't worry about the comments, I think that's part of the post and perhaps it encourages folks to point out mistakes I might have made. Thanks👌

Collapse
 
minigamedev profile image
Mossa •

The decode_using_alphabet needs a ; after the .collect.

Collapse
 
tiemen profile image
Tiemen •

Sharp! You are correct! Thank you so much :)

Collapse
 
minigamedev profile image
Mossa •

I've also seen that get_padding_char is missing.

Collapse
 
minigamedev profile image
Mossa •

I'm guessing it should be this

    fn get_padding_char(&self) -> char {
        '='
    }
Enter fullscreen mode Exit fullscreen mode
Collapse
 
tiemen profile image
Tiemen •

Yep, that was the idea! Somehow I missed copying this one too. Thanks again 👌

Collapse
 
minigamedev profile image
Mossa •

This repo is probably private. Atleast the link doesn't work.

Collapse
 
tiemen profile image
Tiemen •

🙈 You are correct! Totally missed that one. Changed the visibility of the repository, thanks!