Template for a codec for a sum type A
.
Template for a codec for a sum type A
.
Each constructor of A
should get assigned a unique index when
implementing this class. It is used to tag
XML trees, so that the correct
decoding function can be chosen.
In addition to the contract of Codec
, instances of this class must
also preserve the index, that is, any index returned by enc
must
produce a valid decoding function in dec
.
Using this is simple: Instead of creating a new Codec
object, create
an object extending from this class and implement enc
and dec
accordingly. It is automatically a Codec
.
Example usage
new Variant[Option[A]]("option") { def enc(a: Option[A]) = a match { case Some(a) => (0, Codec[A].encode(a)) case None => (1, Codec[Unit].encode(())) } def dec(idx: Int) = idx match { case 0 => Some(Codec[A].decode(_).right.map(Some.apply)) case 1 => Some(Codec[Unit].decode(_).right.map(_ => None)) case _ => None } }
Obtain an instance of a codec from the implicit scope.
Obtain an instance of a codec from the implicit scope.
Example usage
Codec[Int].encode(env)(3)
Combinators for codecs.