OCaml library for Crockford's Base32
1# Crockford Base32 Encoding for OCaml
2
3An OCaml implementation of [Douglas Crockford's
4Base32](https://www.crockford.com/base32.html) encoding with ISO 7064 checksum
5support. Provides encoding and decoding of int64 values to URI-friendly base32
6strings, with optional checksum validation, padding, splitting, and random ID
7generation. Ported from <https://github.com/front-matter/commonmeta>.
8
9## Installation
10
11```bash
12opam install crockford
13```
14
15Or add to your `dune-project`:
16
17```scheme
18(package
19 (depends
20 (crockford)))
21```
22
23## Usage
24
25### Basic Encoding and Decoding
26
27```ocaml
28(* Encode a number *)
29let encoded = Crockford.encode 1234567890L in
30(* "16jkpa2" *)
31
32(* Decode back to number *)
33let decoded = Crockford.decode "16jkpa2" in
34(* 1234567890L *)
35```
36
37### With Checksum
38
39```ocaml
40(* Encode with checksum *)
41let encoded = Crockford.encode ~checksum:true 1234567890L in
42(* "16jkpa2d" *)
43
44(* Decode and validate checksum *)
45let decoded = Crockford.decode ~checksum:true "16jkpa2d" in
46(* 1234567890L - or raises Checksum_mismatch if invalid *)
47```
48
49### Formatted Output
50
51```ocaml
52(* Split with dashes for readability *)
53let encoded = Crockford.encode ~split_every:4 1234567890L in
54(* "16jk-pa2" *)
55
56(* With minimum length (zero-padded) *)
57let encoded = Crockford.encode ~min_length:10 1234L in
58(* "000000016j" *)
59```
60
61### Random ID Generation
62
63```ocaml
64Random.self_init ();
65
66(* Generate random IDs *)
67let id = Crockford.generate ~length:8 ~checksum:true () in
68(* e.g., "a3x7m9q5" *)
69
70(* Generate formatted IDs *)
71let id = Crockford.generate ~length:16 ~split_every:4 ~checksum:true () in
72(* e.g., "7n2q-8xkm-5pwt-3hr9" *)
73```
74
75### Normalization
76
77```ocaml
78(* Handles common character confusions *)
79let decoded = Crockford.decode "ILO" in (* Treated as "110" *)
80let decoded = Crockford.decode "16-JK-PA" in (* Dashes ignored *)
81```
82
83## License
84
85MIT License
86
87## Author
88
89Anil Madhavapeddy <anil@recoil.org>
90(based on code from https://github.com/front-matter/commonmeta)
91
92## Links
93
94- [Homepage](https://tangled.org/@anil.recoil.org/ocaml-crockford)
95- [Crockford Base32 Specification](https://www.crockford.com/base32.html)