Skip to content

encoding

Base64 and hexadecimal: turning bytes into printable text and back.

A Str can hold any bytes. The encoders take a &Str and always succeed. The decoders return Str ! DecodeError, because the input may not be valid.

Encode and decode base64:

import encoding
let text = encoding.base64(&"hello, world")
print(text)
print(try encoding.from_base64(&text))
aGVsbG8sIHdvcmxk
hello, world

Hex, one pair of digits per byte:

import encoding
print(encoding.hex(&"Hi\n"))
print(try encoding.from_hex(&"4869"))
48690a
Hi

Handle bad input with catch:

import encoding
let data = encoding.from_hex(&"zz") catch {
encoding.DecodeError(e) => {
print(e.message)
""
}
}
print(data.len())
not hex at byte 0
0
import encoding
pub fn base64(data: &Str) -> Str

Standard base64 (RFC 4648) with = padding.

The output uses the standard alphabet (+ and /) with = padding. For URLs and file names, base64_url uses - and _ instead and leaves out the padding.

pub fn from_base64(text: &Str) -> Str ! DecodeError

Reads base64 (standard or URL-safe; padding optional; spaces and line breaks skipped).

Lenient on purpose: it reads both the standard and the URL-safe alphabet, padding may be missing, and spaces, tabs and line breaks are skipped, so wrapped base64 (as in PEM files or email) decodes as is. Any other character, data after a =, or text that ends in the middle of a byte (a lone last character, or unused bits that are not zero) is a DecodeError, so cut or altered text is noticed.

import encoding
print(try encoding.from_base64(&"aGVs\nbG8"))
hello
pub fn base64_url(data: &Str) -> Str

Base64url (RFC 4648): - and _ instead of + and /, no padding; safe in URLs and file names.

pub fn hex(data: &Str) -> Str

Lowercase hexadecimal, two digits per byte.

pub fn from_hex(text: &Str) -> Str ! DecodeError

Undoes hex; either case is accepted, and an odd number of digits is an error.

Accepts upper and lower case digits. The input must have an even number of digits and nothing else: no spaces and no 0x prefix.

pub struct DecodeError {
pub message: Str
}