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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1The base64 crate makes the alphabet and padding an explicit Engine choice rather than a hidden default.
- 2Decoding returns a Result because arbitrary input can be malformed, so callers must handle DecodeError.
- 3URL-safe-no-pad output is what you want for tokens that ride inside URLs or headers.
Related explainers
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
rust
use std::cmp::{Ordering, Reverse}; use std::collections::BinaryHeap; use std::fs::File; use std::io::{self, BufRead, BufReader, BufWriter, Lines, Write};
K-way merge of sorted logs in Rust
binary-heap
k-way-merge
streaming-io
Intermediate
8 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
rust
use std::f64::consts::PI; #[derive(Debug, Clone, Copy)] pub struct LatLng {
Building geographic bounding boxes in Rust
geospatial
value-types
option
Intermediate
7 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/base64-encode-and-decode-in-rust-explained-rust-af61/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.