Base32 encodings: RFC 4648 base32 and base32hex, Crockford, sortable

README.md

nox-base32 #

Base32 encodings for OCaml: the base32 and base32hex alphabets of RFC 4648, Crockford's alphabet, and the sortable alphabet of AT Protocol identifiers.

A byte string is cut into groups of five bits, each written as one of 32 symbols, so five bytes take eight symbols. The RFC 4648 alphabets pad the last group with = unless asked not to, and every alphabet writes either case. The decoder accepts exactly what the encoder writes with the same arguments and refuses anything else with the offset of the refused byte: a symbol outside the alphabet, padding where none fits, a length no encoding has, or a last symbol that sets bits past the last byte. Crockford's alphabet is decoded as its specification asks, ignoring case and hyphens and reading I and L as 1 and O as 0.

Unsigned 64-bit integers are written in base 32 too, most significant symbol first, which is what Crockford identifiers and AT Protocol timestamp identifiers (TIDs) are.

Installation #

$ opam install nox-base32

Usage #

# Base32.encode "foobar";;
- : string = "MZXW6YTBOI======"
# Base32.encode ~pad:false ~lower:true "foobar";;
- : string = "mzxw6ytboi"
# Base32.decode "MZXW6YTBOI======";;
- : (string, Base32.error) result = Ok "foobar"
# Base32.decode "MZXW6YT!";;
- : (string, Base32.error) result = Error (Base32.Character (7, '!'))

An AT Protocol TID is a 64-bit integer in thirteen sortable symbols:

# Base32.decode_int64 ~alphabet:`Sortable "3jzfcijpj2z2a";;
- : (int64, Base32.error) result = Ok 1728652679052295174L
# Base32.encode_int64 ~alphabet:`Crockford 1234L;;
- : string = "16J"
  • base32 on opam takes the name; nox-base32 adds base32hex, Crockford and the sortable alphabet, integers, and a decoder whose error names the offset it refuses.
  • multibase carries the RFC 4648 base32 variants behind multibase prefixes.
  • crockford encodes 64-bit identifiers in Crockford's alphabet with an ISO 7064 checksum, and no byte strings.

References #

Licence #

ISC. See LICENSE.md.