-
Notifications
You must be signed in to change notification settings - Fork 15
Home
Ppx protocol conv (de)serialisers using ppxlib, which allows for plugable (de)serialisers.
For the impatient, see Tl;DR
The ppx supports the following features:
- records
- recursive and non-recursive types
- variants
- polymophic variants
- All primitive types
- High level of control of output
The following drivers for serialisation and deserialisation are provided:
-
Json which serialises to
Yojson.Safe.t
-
Jsonm which serialises to
Ezjsonm.value
-
Msgpack which serialises to
Msgpck.t
-
Yaml which serialises to
Yaml.t
-
Xml_light which serialises to
Xml.xml list
open Protocol_conv_json
type a = {
x: int;
y: string [@key "Y"]
z: int list [@default [2;3]]
} [@@deriving protocol ~driver:(module Json)]
type b = A of int
| B of int [@key "b"]
| C
[@@deriving protocol ~driver:(module Json)]
will generate the functions:
val a_to_json: a -> Json.t
val a_of_json_exn: Json.t -> a
val a_of_json: Json.t -> (a, exn) Result.t
val b_to_json: a -> Json.t
val b_of_json_exn: Json.t -> b
val b_of_json: Json.t -> (b, exn) Result.t
a_to_json { x=42; y:"really"; z:[6;7] }
Evaluates to
[ "x", `Int 42; "Y", `String "really"; "z", `List [ `Int 6; `Int 7 ] ] (* Yojson.Safe.json *)
to_protocol
generates only serialisation functions.
of_protocol
generates only de-serialisation functions.
protocol
generates both serialisation and de-serialisation functions.
Record label names can be changed using [@key <string>]
Variant and polymorphic variant constructors names can be changed using the [@name <string>]
attribute.
If a record field is not present in the input when deserialising, as default value can be
assigned using [@default <expr>]
. If the value to be serialized
matches the default value, the field will be omitted (Some drivers
allow disabling this functionality. Comparison uses polymorphic compare, so be careful.
The ppx also handles signature, but disallows
[@key ...]
, [@default ...]
and [@name] ....
as these does not impact signatures.
Drivers specify concrete serialization and deserialization. Users of the library can elect to implement their own driver see custom drivers, or use predefined drivers:
-
Json which serialises to
Yojson.Safe.t
-
Jsonm which serialises to
Ezjsonm.value
-
Msgpack which serialises to
Msgpck.t
-
Yaml which serialises to
Yaml.t
-
Xml_light which serialises to
Xml.xml list
It is easy to provide custom drivers by implementing the signature:
include Protocol_conv.Runtime.Driver with
type t = ...
See the drivers
directory for examples on how to implemented new drivers.
Submissions of new drivers are more than welcome.
- Generalised algebraic datatypes (GADT's)
- Extensible types
- Extensible polymorphic variants