std::base64
std/src/base64.mo
Base64 (RFC 4648 §4) and base64url (§5) codecs, pure Monad.
B64 is the standard alphabet (+//, =-padded); B64Url is the
URL alphabet (-/_) and emits no padding. Both decoders accept
their own alphabet with or without padding and reject non-canonical
trailing bits, so a re-encode of what they return is byte-identical.
Lives in std: the codecs are pure and portable, and they are the
single home for base64. motes/http's request-cookie/basic-auth decoder
and motes/tui's OSC 52 encoder delegate here, as does std::random's
Random.token.
U8 has no shift or bitwise operations, so encoding works in U32
(U8.to_u32/U32.to_u8) and decoding uses multiplication/division,
the shape std's SHA-256 and http's decoder already use.
pub type B64Error {
/// A byte outside the alphabet (including `=` where it cannot appear).
invalid_char,
/// `=` in a position the group rule forbids.
invalid_padding,
/// A non-`=` character after the padding.
data_after_padding,
/// The final group's unused low bits are not zero, so a re-encode would
/// not reproduce the input.
non_canonical_bits,
/// A final group of one character, which carries no whole byte.
bad_length
}Why a base64 string was rejected. One variant per rejection rule, so a
caller can branch on the reason; to_string is the only render point.
pub def B64Error.to_string (e : B64Error) : Stringpub def B64.encode_std (bs : List U8) : StringStandard alphabet, =-padded (RFC 4648 §4).
pub def B64.decode_std (s : String) : Result B64Error (List U8)Standard alphabet; accepts padded or unpadded input.
pub def B64Url.encode (bs : List U8) : StringURL alphabet, unpadded (RFC 4648 §5).
pub def B64Url.decode (s : String) : Result B64Error (List U8)URL alphabet; accepts padded or unpadded input.