Base64 Encoding

Base64 Encoding

Fast Base64 encoding and decoding powered by WebAssembly. This library is modeled after the WHATWG TextEncoder and TextDecoder API.

When I was experimenting with toolchainless WebAssembly I was looking for a simple, self-contained C library that I could ship as a useful WASM library. I’ve always found Base64 encoding confusing, particularly in the browser, so it became a natural target.

The result is Base64 Encoding, an isomorphic runs-everywhere WASM-with-JS-fallback Base64 implementation, with an API that is modeled after the WHATWG text encoding standard. It should therefore feel very familiar to people writing modern low(er)-level JavaScript code.

Because the C code is short, the compiled WASM is inlined into the the JS (Base64-encoded). Should instantiation fail, the pure-JS implementation that is needed to decode the inlined WASM is used as a fallback.

Example

Together with UUID Class this enables creating short, URL-friendly UUIDs:

For example the following strings represents the same 128 bit of data:

ed672cd6-696b-4d22-a977-f3442da10c1d <=> 7Wcs1mlrTSKpd_NELaEMHQ

Converting between the two works as follows:

const id = new UUID('ed672cd6-696b-4d22-a977-f3442da10c1d')
new Base64Encoder({ url: true }).encode(id)
// => 7Wcs1mlrTSKpd_NELaEMHQ

new UUID(new Base64Decoder().decode('7Wcs1mlrTSKpd_NELaEMHQ'))
// => UUID [ ed672cd6-696b-4d22-a977-f3442da10c1d ]

© 2021. All rights reserved.

Powered by Hydejack v9.1.2