zena:encoding
import {…} from 'zena:encoding';
Binary-to-text encodings, and a check for UTF-8.
BaseEncoding implements the encodings of RFC 4648: an alphabet of 16,
32 or 64 characters, each standing for 4, 5 or 6 bits of the input. The
common ones are ready to use:
hex: base16 in lowercase. Decoding accepts either case.base32: the RFC 4648 alphabet,A-Zand2-7.base32Lower: the same alphabet in lowercase, as multibase and CIDs use.base64:A-Z,a-z,0-9,+and/.base64Url: the URL- and filename-safe alphabet, with-and_for+and/, as JWTs use.
import {base64, base64Url, hex} from 'zena:encoding';
let text = base64.encode(bytes); // padded with '='
let token = base64Url.encode(bytes, false); // unpadded
let digest = hex.decode('e3b0c442');
encode pads with = unless pad is false. decode accepts text with
or without padding. It throws EncodingError for a character outside
the alphabet, for a length that no byte string encodes to, for padding
of the wrong length, and for a last character with bits set beyond the
last whole byte. So a byte string has exactly one unpadded encoding and
one padded one, and decoding never accepts two different texts as the
same bytes in the same form.
Classes
EncodingError
class EncodingError extends Error
Text that is not a valid encoding.
new(message: String)
BaseEncoding
final class BaseEncoding
An RFC 4648 encoding with a given alphabet.
new(alphabet: String, caseInsensitive: boolean = false)
An encoding with alphabet, which must have 16, 32 or 64 distinct
ASCII characters. With caseInsensitive, decoding also accepts each
letter of the alphabet in the other case; the alphabet must then not
hold both cases of a letter.
Functions
isValidUtf8
function isValidUtf8(bytes: FixedArray<u8>, start: i32 = 0, end: i32 = -1): boolean
Whether bytes[start..end] is UTF-8 as RFC 3629 defines it: no
overlong forms, no surrogates (U+D800 to U+DFFF), and nothing above
U+10FFFF. end defaults to the length of bytes.
Zena strings hold WTF-8, which allows surrogates, so a String is not
always valid UTF-8; check bytes with this before handing them to a
format that requires it.
Variables
hex
let hex: BaseEncoding
Base16 in lowercase; decoding accepts either case.
base32
let base32: BaseEncoding
RFC 4648 base32.
base32Lower
let base32Lower: BaseEncoding
RFC 4648 base32 in lowercase, as multibase (b...) and CIDs write it.
base64
let base64: BaseEncoding
RFC 4648 base64.
base64Url
let base64Url: BaseEncoding
RFC 4648 base64 with the URL- and filename-safe alphabet.