base64

    Portable RFC 4648 Base64 and WHATWG forgiving decoding ported from base64-simd

    base64
    simd
    encoding
    rfc4648
    Download zip
    Author
    Version
    0.1.0
    License
    MIT
    Last updated
    58 minutes ago
    Downloads
    2

    No dependencies

    #Checked Base64 examples

    ///|
    test "standard padded Base64" {
    assert_eq(
    @base64.standard.encode_to_string(b"hello world"),
    "aGVsbG8gd29ybGQ=",
    )
    assert_eq(@base64.standard.decode_string("aGVsbG8gd29ybGQ="), b"hello world")
    }

    ///|
    test "URL-safe and WHATWG forgiving decoding" {
    assert_eq(@base64.url_safe_no_pad.encode_to_string(b"\xfb\xff"), "-_8")
    assert_eq(@base64.url_safe_no_pad.decode_string("-_8"), b"\xfb\xff")
    assert_eq(@base64.forgiving_decode_string(" Z h = = \n"), b"f")
    }

    Base64Error

    pub suberror Base64Error {
    InvalidInput
    OutputTooSmall
    } derive(Eq,
    Debug
    )

    Invalid Base64 or insufficient caller-provided output storage.

    InvalidInput covers length, alphabet, padding, and nonzero unused bits. OutputTooSmall also covers an output offset outside the destination. Allocating operations expose no partial output. Buffer operations can change an output prefix before a later InvalidInput; see their docs.

    Base64

    An immutable RFC 4648 alphabet and padding policy.

    Use standard, standard_no_pad, url_safe, or url_safe_no_pad, or construct the same policies with Base64::new. Assignments safely share the configuration; operations retain no input and have no mutable state. The measured default requests vectors on Wasm and scalar processing on native, Wasm GC, and JS. An explicit simd argument overrides that choice.

    Base64::charset

    fn Base64::charset(self : Base64) -> BytesView

    Returns the configuration's immutable 64-byte alphabet.

    The result can be retained independently of inputs and outputs.

    Base64::check

    fn Base64::check(self : Base64, input : BytesView, simd? : Bool) -> Unit raise Base64Error

    Fully validates byte input without allocating decoded output or mutating input.

    Raises InvalidInput for the wrong alphabet, any whitespace, malformed padding, impossible length, or nonzero unused bits. Padded policies require exact RFC 4648 padding; no-pad policies reject =. Empty input is valid. Uses V128 with simd=true on native/Wasm and scalar fallback elsewhere.

    Base64::decode

    fn Base64::decode(self : Base64, input : BytesView, simd? : Bool) -> Bytes raise Base64Error

    Decodes strictly validated Base64 bytes into an independent byte sequence.

    The alphabet, padding, and error rules match check. No whitespace is accepted. Raises InvalidInput without exposing partial output; input is unchanged. SIMD processes full 16-character blocks on native/Wasm, with scalar tails and fallback on Wasm GC/JS. Empty input returns empty bytes.

    Base64::decode_append

    fn Base64::decode_append(self : Base64, input : BytesView, output :
    Buffer
    , simd? : Bool) -> Unit raise Base64Error

    Appends decoded bytes to output after validating all input.

    Raises InvalidInput with the buffer unchanged. A temporary independent byte sequence is allocated by decode; its strict and SIMD policies apply. Buffer aliases observe a successful append; input remains unchanged.

    Base64::decode_inplace

    fn Base64::decode_inplace(self : Base64, data : FixedArray[Byte], length? : Int, simd? : Bool) -> Int raise Base64Error

    Decodes the first length bytes of data into its prefix, returning its size.

    length defaults to the full array and must lie within its capacity. The configuration's strict rules apply. Reads precede their overlapping writes; no input copy is made. Only the returned prefix represents decoded data; the unused suffix is unchanged on success. An InvalidInput can leave a partially overwritten prefix. Array aliases observe writes. Uses the same vector/tail/fallback policy as decode.

    Base64::decode_into

    fn Base64::decode_into(self : Base64, input : BytesView, output : FixedArray[Byte], offset? : Int, simd? : Bool) -> Int raise Base64Error

    Decodes bytes into output at offset, returning the number written.

    The alphabet and strict validation match decode. An invalid structural length or insufficient capacity raises before writing. A later alphabet or tail-bit error can leave an already decoded prefix; its contents are unspecified on error. On success, bytes outside the output range stay unchanged. The input is immutable. Uses the same SIMD policy as decode.

    Base64::decode_string

    fn Base64::decode_string(self : Base64, input : StringView, simd? : Bool) -> Bytes raise Base64Error

    Decodes an ASCII StringView using the same strict rules as decode.

    Reads UTF-16 code units directly, including a view's starting offset; no UTF-8 materialization is needed. Every non-ASCII code unit is rejected. Inputs and retained views remain unchanged. Raises InvalidInput without exposing partial output; vector requests fall back on Wasm GC/JS.

    test {
    assert_eq(@base64.url_safe_no_pad.decode_string("-_8"), b"\xfb\xff")
    }

    Base64::decoded_length

    fn Base64::decoded_length(self : Base64, input : BytesView) -> Int raise Base64Error

    Calculates the decoded size after checking length and terminal padding.

    As in upstream decoded_length, this is a partial validation: invalid alphabet bytes, interior =, and unused tail bits can still pass. Use check for full validation. Raises InvalidInput for impossible lengths. Neither the configuration nor input is changed.

    Base64::encode

    fn Base64::encode(self : Base64, input : BytesView, simd? : Bool) -> Bytes

    Encodes input into a newly allocated ASCII byte sequence.

    Empty input returns empty bytes. Input views are read within their bounds. simd=true requests V128 on native/Wasm, with a scalar short-input path and scalar fallback on Wasm GC/JS. Panics if the encoded length overflows. The input and configuration are unchanged; the returned bytes are independent.

    Base64::encode_append

    fn Base64::encode_append(self : Base64, input : BytesView, output : StringBuilder, simd? : Bool) -> Unit

    Appends an encoded ASCII String to output, preserving its existing prefix.

    Input is unchanged. The temporary encoded allocation and padding/overflow and SIMD behavior are the same as encode_to_string. Builder aliases observe the append; the configuration retains no builder reference.

    Base64::encode_into

    fn Base64::encode_into(self : Base64, input : BytesView, output : FixedArray[Byte], offset? : Int, simd? : Bool) -> Int raise Base64Error

    Writes encoded bytes at offset and returns the number of bytes written.

    The default offset is zero. Raises OutputTooSmall for an invalid offset or insufficient capacity, before changing the destination. Panics on size overflow as encoded_length does. Bytes outside the written range remain unchanged. Immutable BytesView input is independent of the mutable array. Uses the same SIMD and fallback policy as encode.

    Base64::encode_to_string

    fn Base64::encode_to_string(self : Base64, input : BytesView, simd? : Bool) -> String

    Encodes arbitrary bytes into a newly allocated ASCII String.

    Uses the same padding, bounds, overflow, and SIMD policy as encode. Binary input is never interpreted as text. The output is safe to retain.

    test {
    assert_eq(
    @base64.standard.encode_to_string(b"hello world"),
    "aGVsbG8gd29ybGQ=",
    )
    }

    Base64::encoded_length

    fn Base64::encoded_length(self : Base64, length : Int) -> Int

    Calculates the exact encoded byte length, including configured padding.

    Panics for negative length or an output exceeding Int::max_value. This checks multiplication before allocation; empty input needs zero bytes.

    Base64::estimated_decoded_length

    fn Base64::estimated_decoded_length(_self : Base64, length : Int) -> Int

    Returns an allocation upper bound for decoding length encoded bytes.

    The estimate rounds up to a quartet and does not validate any input. Panics for negative lengths; all nonnegative Int lengths are safe.

    Base64::new

    fn Base64::new(url_safe? : Bool, padding? : Bool) -> Base64

    Selects the RFC 4648 alphabet and padding policy.

    url_safe=true uses - and _; padding=false omits = on encoding and forbids it on decoding. Defaults select the standard padded policy.

    forgiving_decode

    fn forgiving_decode(input : BytesView, simd? : Bool) -> Bytes raise Base64Error

    Decodes standard Base64 using WHATWG Infra's forgiving-base64 algorithm.

    Removes ASCII TAB, LF, FF, CR, and SPACE, accepts correctly placed optional padding, and ignores unused tail bits. Vertical tab, non-ASCII, URL-safe characters, interior padding, and impossible lengths raise InvalidInput. Input is unchanged; the result is independent. Whitespace needs a temporary normalized allocation. SIMD and fallback behavior match strict decode.

    forgiving_decode_inplace

    fn forgiving_decode_inplace(data : FixedArray[Byte], length? : Int, simd? : Bool) -> Int raise Base64Error

    Compacts whitespace then forgiving-decodes a mutable array prefix in place.

    length defaults to the array capacity and must be within it. No input copy is allocated. Returns decoded prefix size; the unused suffix is unspecified because whitespace compaction can change it. Array aliases observe writes. As upstream does, whitespace compaction and partial decoding can occur before InvalidInput. Uses the same SIMD policy as forgiving_decode; only standard Base64 is accepted.

    forgiving_decode_into

    fn forgiving_decode_into(input : BytesView, output : FixedArray[Byte], offset? : Int, simd? : Bool) -> Int raise Base64Error

    Writes forgiving-decoded bytes at offset and returns the number written.

    Normalizes whitespace into temporary storage when present. Capacity is checked against the exact decoded size, relaxing upstream's requirement that the destination hold the entire encoded input. OutputTooSmall occurs before writes. Later InvalidInput can leave a partially written prefix; on success, bytes outside the written range are unchanged. Input is immutable.

    forgiving_decode_string

    fn forgiving_decode_string(input : StringView, simd? : Bool) -> Bytes raise Base64Error

    Applies forgiving-base64 to an ASCII StringView without UTF-8 conversion.

    Whitespace, tail-bit, padding, failure, and SIMD rules match forgiving_decode. Every non-ASCII UTF-16 code unit is rejected, and the input and retained views are unchanged. Empty or all-whitespace input returns empty bytes.

    standard

    let standard : Base64

    The standard A-Z a-z 0-9 + / alphabet with required = padding.

    standard_no_pad

    let standard_no_pad : Base64

    The standard alphabet with no padding; decoding rejects every =.

    url_safe

    let url_safe : Base64

    The URL-safe A-Z a-z 0-9 - _ alphabet with required = padding.

    url_safe_no_pad

    let url_safe_no_pad : Base64

    The URL-safe alphabet with no padding; decoding rejects every =.