nox-hex #
Hexadecimal string codec (RFC 4648 base16) for OCaml.
nox-hex encodes and decodes between octet strings and their hex
rendering, with bytesrw stream filters and hexdump pretty-printers. The
_into variants read from and write into a window of an existing buffer,
so key material kept in a buffer that can be erased never has to be copied
into an immutable string. decode_int parses fixed-width hex fields, such
as those of a cpio header, without allocating. The library is adapted from
ohex by Hannes Mehnert and keeps its
API.
Installation #
Install with opam:
$ opam install nox-hex
If opam cannot find the package, it may not yet be released in the public
opam-repository. Add the overlay repository, then install it:
$ opam repo add samoht https://tangled.org/gazagnaire.org/opam-overlay.git
$ opam update
$ opam install nox-hex
The package installs the library nox-hex, whose module is Hex. It needs
OCaml 4.14 or later.
Usage #
Encoding is lowercase. Decoding accepts both digit cases and, by default,
skips whitespace:
# Hex.encode "AB";;
- : string = "4142"
# Hex.decode "41 42";;
- : string = "AB"
# Hex.decode "4a4B";;
- : string = "JK"
# Hex.required_length "4142";;
- : int = 2
An invalid character or an odd number of digits raises Invalid_argument:
# Hex.decode "414";;
Exception: Invalid_argument "leftover byte in hex string".
decode_int reads a fixed-width field in place and returns None rather
than raising, so a parser can reject a malformed header field without a
handler:
# Hex.decode_int ~off:2 ~len:4 "0x00ff";;
- : int option = Some 255
# Hex.decode_int ~len:2 "zz";;
- : int option = None
decode_into writes into a window of a caller's buffer:
# let buf = Bytes.make 4 '.';;
val buf : bytes = Bytes.of_string "...."
# Hex.decode_into "4142" buf ~dst_off:1 ();;
- : unit = ()
# buf;;
- : bytes = Bytes.of_string ".AB."
pp_hexdump prints one row per 16 octets. A row starts with the offset,
then the octets in pairs, then their printable characters.
# Fmt.pr "%a%!" (Hex.pp_hexdump ()) "Hello, hex!";;
000000 4865 6c6c 6f2c 2068 6578 21 Hello, hex!
- : unit = ()
API #
lib/hex.mli is the reference, which dune build @doc
renders with odoc:
Hex.encodeandHex.encode_intoturn octets into lowercase hex.Hex.decodeandHex.decode_intoturn hex into octets, validating
first.Hex.required_lengthis the decoded size of a hex string.Hex.decode_intreads a fixed-width hex field as an integer.Hex.encode_readsandHex.decode_readsare bytesrw reader filters, and
Hex.encode_writesandHex.decode_writesare writer filters.Hex.ppprints spaced hex andHex.pp_hexdumpprints a hexdump.
License #
ISC. See LICENSE.md.