I am looking for a way to approach a protocol like the following example:
case class Request(bodyType: Int, foo: Int, bar: Int, body: RequestBody)
sealed trait RequestBody
case class Read(key: String) extends RequestBody
case class Write(key: String, value: Array[Byte]) extends RequestBody
Here, bodyType == 0
will stand for Read
, and bodyType != 0
will encode Write
.
Note that there are a few fields separating discriminator from discriminated value.
I've seen an example with byte-ordering. But as far as I understand this "squid" encoded discriminator would not round trip. What's the correct way to solve such a problem?
There are a few ways to do it, but this is one I've used:
import scodec._
import scodec.codecs._
import scodec.bits._
case class Request(bodyType: Int, foo: Int, bar: Int, body: RequestBody)
sealed trait RequestBody
case class Read(key: String) extends RequestBody
object Read {
implicit val codec: Codec[Read] = ("key" | utf8).as[Read]
implicit val discriminator: Discriminator[RequestBody, Read, Int] = Discriminator(0)
}
case class Write(key: String, value: ByteVector) extends RequestBody
object Write {
implicit val codec: Codec[Write] = {
("key" | utf8 ) ::
("value" | bytes )
}.as[Write]
implicit val discriminator: Discriminator[RequestBody, Write, Int] = Discriminator(1)
}
object Request {
implicit val codec: Codec[Request] = {
("bodyType" | uint16 ).flatPrepend { bodyType =>
("foo" | uint16 ) ::
("bar" | uint16 ) ::
("body" | Codec.coproduct[RequestBody].discriminatedBy(provide(bodyType)).auto)
}}.as[Request]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With