Skip to content

Instantly share code, notes, and snippets.

@ndchandar ndchandar/scodec-test2.scala Secret
Last active Oct 25, 2019

Embed
What would you like to do?
import scodec.Codec
import scodec.bits._
import scodec.codecs._
import shapeless._
object Test1 {
sealed trait PacketType extends Product with Serializable
case class Connect(i: Int) extends PacketType
case class Subscribe(s: String) extends PacketType
case object Disconnect extends PacketType
case class Payload1(i: Int)
case class Payload2(s: String)
sealed trait MyPacketType
case class MyPacket1(packetType: Connect, payload: Payload1) extends MyPacketType
case class MyPacket2(packetType: Subscribe, payload: Payload2) extends MyPacketType
case class MyPacket3(packetType: Disconnect.type) extends MyPacketType
val packetTypeCodec: Codec[PacketType] =
discriminated[PacketType]
.by(uint4)
.typecase(1, (uint16 <~ constant(bin"0000")).as[Connect])
.typecase(2, variableSizeBytes(uint16, utf8.as[Subscribe]))
.typecase(3, provide(Disconnect) <~ constant(bin"0001"))
val payload1Codec: Codec[Payload1] = uint16.as[Payload1]
val payload2Codec: Codec[Payload2] = utf8.as[Payload2]
// 1. Co-product case
type MyPacket = MyPacket1 :+: MyPacket2 :+: MyPacket3 :+: CNil
// TODO: How to fill `typecase` for the co-product cases when there are nested case classes
// i.e discriminated[MyPacket].by(packetTypeCodec) ?
val myPacketCodec1: Codec[MyPacket] = ???
// 2. Product case
// TODO: Or How to fill in `typecase` for product case
// i.e discriminated[PacketType].by(packetTypeCodec) ?
val myPacketCodec2: Codec[PacketType] = ???
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.