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))aGVsbG8sIHdvcmxkhello, worldHex, one pair of digits per byte:
import encoding
print(encoding.hex(&"Hi\n"))print(try encoding.from_hex(&"4869"))48690aHiHandle 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 00Reference
Section titled “Reference”import encodingFunctions
Section titled “Functions”base64
Section titled “base64”pub fn base64(data: &Str) -> StrStandard 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.
from_base64
Section titled “from_base64”pub fn from_base64(text: &Str) -> Str ! DecodeErrorReads 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"))hellobase64_url
Section titled “base64_url”pub fn base64_url(data: &Str) -> StrBase64url (RFC 4648): - and _ instead of + and /, no padding; safe in URLs and file names.
pub fn hex(data: &Str) -> StrLowercase hexadecimal, two digits per byte.
from_hex
Section titled “from_hex”pub fn from_hex(text: &Str) -> Str ! DecodeErrorUndoes 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.
DecodeError
Section titled “DecodeError”pub struct DecodeError { pub message: Str}