rust 27 lines · 7 steps

Base64 encode and decode in Rust

A thin wrapper over the base64 crate that exposes standard and URL-safe encoding through explicit Engine values.

Explained by highlit
1use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};
2use base64::{DecodeError, Engine};
3 
4pub fn encode_standard(data: &[u8]) -> String {
5 STANDARD.encode(data)
6}
7 
8pub fn decode_standard(encoded: &str) -> Result<Vec<u8>, DecodeError> {
9 STANDARD.decode(encoded)
10}
11 
12pub fn encode_url_token(data: &[u8]) -> String {
13 URL_SAFE_NO_PAD.encode(data)
14}
15 
16pub fn decode_url_token(token: &str) -> Result<Vec<u8>, DecodeError> {
17 URL_SAFE_NO_PAD.decode(token)
18}
19 
20pub fn roundtrip(payload: &[u8]) -> Result<Vec<u8>, DecodeError> {
21 let encoded = STANDARD.encode(payload);
22 STANDARD.decode(&encoded)
23}
24 
25pub fn encode_into(data: &[u8], buf: &mut String) {
26 STANDARD.encode_string(data, buf);
27}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1The base64 crate makes the alphabet and padding an explicit Engine choice rather than a hidden default.
  2. 2Decoding returns a Result because arbitrary input can be malformed, so callers must handle DecodeError.
  3. 3URL-safe-no-pad output is what you want for tokens that ride inside URLs or headers.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Base64 encode and decode in Rust — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code