Encoding
Base64, Base64URL, and hex encoders and decoders for byte views and strings.
std.encoding provides binary-to-text encoders and decoders. The current
public modules are encoding.base64, encoding.base64url, and encoding.hex.
String-returning encoders return owned String throws(AllocError), so callers
use try or catch.
import std.encoding;
fn main() {
let padded = try encoding.base64.encode("fo");
let compact = try encoding.base64.encode_no_pad("fo");
let direct = try encoding.base64.encode("Hello");
assert padded.str() == "Zm8=";
assert compact.str() == "Zm8";
assert direct.str() == "SGVsbG8=";
}
encoding.base64 uses the standard alphabet with + and /.
| Method | Purpose |
|---|---|
base64.encode(data) | Encode with = padding. |
base64.encode_no_pad(data) | Encode without padding. |
Both methods use canonical bytes.Bytes inputs. Callers can pass string
literals, String, existing byte views, or [u8] slices directly as call
arguments.
encoding.base64url uses the URL-safe alphabet with - and _.
import std.encoding;
fn main() {
let url = try encoding.base64url.encode_no_pad("hello?");
assert url.str() == "aGVsbG8_";
}
| Method | Purpose |
|---|---|
base64url.encode(data) | Encode with URL-safe alphabet and = padding. |
base64url.encode_no_pad(data) | Encode with URL-safe alphabet and no padding. |
For local namespace imports, import the submodule directly:
import std.encoding.base64;
fn main() {
let text = try base64.encode("Hello");
assert text.str() == "SGVsbG8=";
}
encoding.hex provides lowercase and uppercase hex encoding plus strict
decoding.
import std.encoding;
import std.encoding.hex;
fn main() {
let lower = try encoding.hex.encode("Az");
let upper = try hex.encode_upper("Az");
let decoded = try hex.decode("486900");
let bytes = decoded.slice();
assert lower.str() == "417a";
assert upper.str() == "417A";
assert bytes.length == 3;
assert bytes[2] == 0 as u8;
}
| Method | Purpose |
|---|---|
hex.valid(text) | Return whether a string is valid even-length hex. |
hex.encoded_length(len) | Return the byte length of encoded hex output. |
hex.decoded_length(text) | Return decoded byte length or HexError.Invalid. |
hex.encode(data) | Encode lowercase hex into String throws(AllocError). |
hex.encode_upper(data) | Encode uppercase hex into String throws(AllocError). |
hex.encode_into(data, out) | Encode lowercase hex into caller-owned bytes. |
hex.encode_upper_into(data, out) | Encode uppercase hex into caller-owned bytes. |
hex.decode(text) | Decode strict hex into Array<u8> throws(HexError | AllocError). |
hex.decode_into(text, out) | Decode strict hex into caller-owned bytes. |
Malformed hex raises HexError.Invalid. _into calls raise
HexError.Buffer when the output slice is too small.