Modules

Base64

moduleSource
macOSLinuxWindowswasm

#import "Base64";

Base64 encoding and decoding, in the standard alphabet and the URL-safe one.

Results are allocated with the context allocator and the caller frees them. Decoding reports invalid input through a success result instead of failing; see base64_decode.

ExampleOpen in playground ↗
encoded := base64_encode("hello");
defer free(encoded);
assert(encoded == "aGVsbG8=");

Procedures#

(input: string, table: string = BASE64_ENCODER_TABLE, pad := true) -> string

The Base64 text of the bytes in input, using the 64 symbols in table.

encoded := base64_encode("Man");
defer free(encoded);
assert(encoded == "TWFu");

padded := base64_encode("Ma");
defer free(padded);
assert(padded == "TWE=");

bare := base64_encode("Ma", pad = false);
defer free(bare);
assert(bare == "TWE");
↗
(input: string, table: [256] u8 = BASE64_DECODER_TABLE) -> (string, success: bool)

The bytes that input encodes, and whether all of it was valid.

decoded, ok := base64_decode("TWFu\nTWE=");
defer free(decoded);
assert(ok && decoded == "ManMa");

failed, failed_ok := base64_decode("TW!u");
defer free(failed);
assert(!failed_ok && failed == "");

lone, lone_ok := base64_decode("T");
defer free(lone);
assert(!lone_ok);
↗
(input: string) -> string

The URL-safe Base64 text of input, with no = padding.

encoded := base64url_encode("\xfb\xff");
defer free(encoded);
assert(encoded == "-_8");
↗
(input: string) -> (string, success: bool)

The bytes that URL-safe Base64 text encodes, and whether all of it was valid. Padding is optional. Errors and ownership are as for base64_decode: the result is empty when success is false, and the caller frees it.

decoded, ok := base64url_decode("-_8");
defer free(decoded);
assert(ok && decoded == "\xfb\xff");
↗
()

Checks a standard Base64 round trip, with asserts. A smoke test for the module.

()

Checks a URL-safe Base64 round trip, with asserts. A smoke test for the module.

Constants#

:: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"

The 64 symbols of the standard alphabet in value order: A-Z, a-z, 0-9, +, /.

:: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"

The 64 symbols of the URL-safe alphabet: the standard one with - and _ in place of + and /.

:: #run decoder_table(BASE64_ENCODER_TABLE)

Maps each byte to what base64_decode does with it, for the standard alphabet.

table := BASE64_DECODER_TABLE;
table[#char " "] = 64;
decoded, ok := base64_decode("TW Fu", table);
defer free(decoded);
assert(ok && decoded == "Man");
↗
:: #run decoder_table(BASE64URL_ENCODER_TABLE)

The decoder table for the URL-safe alphabet. See BASE64_DECODER_TABLE for the values.