gpt4 book ai didi

scala - 编解码器组合器 : Header contains magic number that is used to discriminate types

转载 作者:行者123 更新时间:2023-12-04 19:02:22 25 4
gpt4 key购买 nike

我正在寻找一种方法来处理类似于以下示例的协议(protocol):

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

在这里, bodyType == 0将代表 Read , 和 bodyType != 0将编码 Write .
请注意,有几个字段将鉴别器与鉴别值分开。

我看过 an example with byte-ordering .
但据我了解,这种“鱿鱼”编码的鉴别器不会往返。
解决此类问题的正确方法是什么?

最佳答案

有几种方法可以做到这一点,但这是我用过的一种:

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]
}

关于scala - 编解码器组合器 : Header contains magic number that is used to discriminate types,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34701756/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com