Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scodec combinators: Header contains magic number that is used to discriminate types

Tags:

scala

scodec

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?

like image 529
om-nom-nom Avatar asked Jan 10 '16 03:01

om-nom-nom


1 Answers

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]
} 
like image 88
Steve Buzzard Avatar answered Oct 22 '22 23:10

Steve Buzzard