My aggregated monorepo of OCaml code, automaintained
1open Tomlt
2
3(* Helper to encode TOML to string via writer *)
4let toml_to_string value =
5 let buf = Buffer.create 256 in
6 Tomlt_bytesrw.to_writer (Bytesrw.Bytes.Writer.of_buffer buf) value;
7 Buffer.contents buf
8
9type config = { name : string; timeout : int option }
10
11let config_codec =
12 Table.(
13 obj (fun name timeout -> { name; timeout })
14 |> mem "name" string ~enc:(fun c -> c.name)
15 |> opt_mem "timeout" int ~enc:(fun c -> c.timeout)
16 |> finish
17 )
18
19let () =
20 (* Test encoding *)
21 let c = { name = "app"; timeout = None } in
22 let toml = encode config_codec c in
23 Printf.printf "Encoded TOML:\n%s\n" (toml_to_string toml);
24
25 (* Show raw structure *)
26 Printf.printf "\nRaw structure: %s\n" (match toml with
27 | Toml.Table pairs ->
28 String.concat ", " (List.map (fun (k, v) ->
29 Printf.sprintf "%s=%s" k (match v with
30 | Toml.String s -> Printf.sprintf "\"%s\"" s
31 | Toml.Bool b -> string_of_bool b
32 | Toml.Int i -> Int64.to_string i
33 | _ -> "?"
34 )
35 ) pairs)
36 | _ -> "not a table");
37
38 (* Test decoding the encoded value *)
39 Printf.printf "\nDecoding...\n";
40 match decode config_codec toml with
41 | Ok { name; timeout } ->
42 Printf.printf "Decoded: name=%s, timeout=%s\n" name
43 (match timeout with Some t -> string_of_int t | None -> "None")
44 | Error e ->
45 Printf.printf "Decode error: %s\n" (Toml.Error.to_string e)