Module Type.Coded

Coded types.

Coded types store arbitrary OCaml values by encoding them to a base type. To let other, non OCaml-based, systems access the database, be conservative in your encodings.

See an example.

type 'a repr := 'a t
type ('a, 'b) t

The type for type 'a encoded by type 'b.

val make : ?doc:string -> ?pp:'a fmt -> ?equal:'a eq -> name:string -> 'b repr -> enc:('a -> 'b) -> dec:('b -> 'a) -> ('a, 'b) t

make ~name repr ~enc ~dec is a coded type with:

  • name, the name of the coded type.
  • repr, the base type used to encode values.
  • enc, the function for encoding values. The function must raise Failure for partial encodings.
  • dec, the function for decoding values. The function must raise Failure for partial decodings.
  • equal, an equality function on the values of the type. Defaults to Stdlib.(=)
  • pp, a formatter for the type values. Defaults uses enc and repr's formatter
  • doc, a doc string for the coded type.
val name : ('a, 'b) t -> string

name c is the name of c.

val doc : ('a, 'b) t -> string

doc c is the documentation string of c.

val repr : ('a, 'b) t -> 'b repr

repr c is the type of the encoding of c

val enc : ('a, 'b) t -> 'a -> 'b

enc c is the encoder of c.

val dec : ('a, 'b) t -> 'b -> 'a

dec c is the decoder of c.

val equal : ('a, 'b) t -> 'a eq

equal c tests values of c for equality.

val pp : ('a, 'b) t -> 'a fmt

pp c formats values of c.

Example

This encodes a binary enum to a boolean:

open Rel

type status = [ `Ok | `Failed ]

let pp_status ppf v =
  Format.pp_print_string ppf (match v with `Ok -> "ok" | `Failed -> "failed")

let status : status Type.t =
  let enc = function `Ok -> true | `Failed -> false in
  let dec = function true -> `Ok | false -> `Failed in
  Type.coded (Type.Coded.make ~name:"status" Type.bool ~enc ~dec ~pp:pp_status)