- OCaml 100%
Toml #
Reading a TOML configuration file into an OCaml record usually means walking a
generic tree by hand, and writing it back means a second function that has to
agree with the first. Toml is a TOML 1.1 codec in
which one description of a type gives both directions. Each codec 'a Toml.codec decodes a TOML value into an 'a and encodes an 'a back, and
codecs compose from primitives through combinators.
The design follows Daniel Buenzli's Jsont
and its paper, An alphabet for your data soups (2024,
https://github.com/dbuenzli/jsont/tree/main/paper). Decoding errors carry the
location in the source text, and Toml.to_string ~preserve:true writes a parsed
document back byte for byte except for the values that changed.
Installation #
Install with opam:
opam install nox-toml
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-toml
Quick Start #
Define a codec for your OCaml types:
type config = { host : string; port : int; debug : bool }
let config_codec =
Toml.Codec.(Table.(
obj (fun host port debug -> { host; port; debug })
|> mem "host" string ~enc:(fun c -> c.host)
|> mem "port" int ~enc:(fun c -> c.port)
|> mem "debug" bool ~enc:(fun c -> c.debug) ~dec_absent:false
|> finish
))
Decode a TOML string directly with the core library:
let () =
match Toml.of_string config_codec {|
host = "localhost"
port = 8080
|} with
| Ok config -> Printf.printf "Host: %s\n" config.host
| Error e -> prerr_endline (Toml.Error.to_string e)
For streaming decode from a bytesrw reader, use Toml.of_reader.
Packages #
The opam package nox-toml provides the library Toml: the value type
(Toml.Value), the codec combinators (Toml.Codec), a cursor for editing a
document in place (Toml.Cursor), and a streaming parser and encoder over
Bytesrw. The sub-library nox-toml.json (Toml_json) converts between TOML and
JSON values.
Licence #
ISC