Sign in

    #Base64

    Base64 encoding and decoding following RFC 4648.

    #Encoding

    Use encode to convert bytes to a Base64 string. Padding with = is enabled by default.

    ///|
    test "encode" {
    let bytes : Bytes = b"Hello"
    inspect(@base64.encode(bytes), content="SGVsbG8=")
    }

    Disable padding by setting padding=false:

    ///|
    test "encode_no_padding" {
    let bytes : Bytes = b"Hello"
    inspect(@base64.encode(bytes, padding=false), content="SGVsbG8")
    }

    #Decoding

    Use decode to convert a Base64 string back to bytes. Both padded and unpadded input are accepted. Raises Malformed on invalid input.

    ///|
    test "decode" {
    let bytes = @base64.decode("SGVsbG8=")
    inspect(bytes, content="b\"Hello\"")
    }

    Set ignore_whitespace=true to skip spaces, tabs, CR, and LF in the input:

    ///|
    test "decode_ignore_whitespace" {
    let bytes = @base64.decode("SGVs bG8=", ignore_whitespace=true)
    inspect(bytes, content="b\"Hello\"")
    }

    #Lossy Decoding

    Use decode_lossy to decode Base64 while skipping invalid characters instead of raising an error. Padding ends decoding. Spaces, tabs, CR, and LF also end decoding by default; set ignore_whitespace=true to skip them.

    ///|
    test "decode_lossy" {
    let bytes = @base64.decode_lossy("SGVsbG8=")
    inspect(bytes, content="b\"Hello\"")
    }

    Malformed

    pub suberror Malformed {
    Malformed(StringView)
    } derive(
    Debug
    )

    Error type Malformed.

    decode

    fn decode(text : StringView, ignore_whitespace? : Bool) -> Bytes raise Malformed

    Decodes a Base64 string into a byte array.

    When ignore_whitespace is true, spaces, tabs, CR, and LF are ignored. Padding may only appear at the end. Both padded and unpadded input are accepted, but malformed padding raises Malformed.

    decode_lossy

    fn decode_lossy(text : StringView, ignore_whitespace? : Bool) -> Bytes

    Decodes a Base64 string into a byte array, skipping invalid characters.

    Other invalid characters are skipped. Spaces, tabs, CR, and LF stop decoding unless ignore_whitespace is true, in which case they are skipped. Decoding always stops once padding is encountered.

    encode

    fn encode(bytes : BytesView, padding? : Bool) -> String

    Encodes a byte array into a Base64 string (RFC 4648).

    When padding is true, the output is padded with = to a multiple of 4.