简体   繁体   English

Vector [N]的编解码器,其中N确定向量的结尾

[英]codec for a Vector[N] where N determines the end of the vector

I am using Scodec to decode Flac metadata. 我正在使用Scodec解码Flac元数据。 One of the specifications is that there is a Header and a Block that can be repeated a number of times together. 规范之一是存在一个标头和一个块,它们可以一起重复多次。 Header has a flag which indicates if the current Header/Block combo is the last. 标头有一个标志,指示当前的标头/块组合是否为最后一个。

I have been able to decode Header and Block, but how can we create a Vector base on this specification. 我已经能够解码Header和Block,但是我们如何才能基于此规范创建一个Vector。

Here is the code broken down 这是分解的代码

  //isLastBlock determines if this is the last Header/Block combo to decode.
  case class Header(isLastBlock: Boolean)
  //Some example data.
  case class Block(someData: Int)

  object Codec {
    //Codec for Header
    val headerCodec : Codec[Header] = bool.as[Header]
    //Coded for Block
    val blockCodec: Codec[Block] = int32.as[Block]

    //We are guaranteed at least one Header/Block Combo, but how can we do this?
    val headerBlock: Codec[(Header, Block, Vector[(Header, Block)])] = ???
  }

Not sure if scodec provides this functionality. 不确定scodec是否提供此功能。 The 2 methods vectorOfN and sizedVector do not work because they require knowing the number of items prior to decoding. vectorOfN和sizeVector这2种方法不起作用,因为它们需要在解码之前知道项数。

I found a solution using flatMap and recursion. 我找到了使用flatMap和递归的解决方案。

  //create a single Codec
  val headerBlockCode: Codec[(Header,Block)] = headerCodec ~ blockCodec

  //Takes the last decode and continues to decode until Header.isLastBlock 
  def repeat(priorDecode: DecodeResult[(Header,Block)]) : Attempt[DecodeResult[List[(Header, Block)]]] = {
    if (priorDecode.value._1.isLastBlock) Successful(priorDecode.map(List(_)))
    else {
      headerBlockCode.decode(priorDecode.remainder) match {
        case f: Failure => f
        case s: Successful[DecodeResult[(Header, Block)]] => {
          repeat(s.value) match {
            case f: Failure => f
            case Successful(list) => {
              Successful(list.map(decList => s.value.value :: decList))
            }
          }
        }
      }
    }
  }

  //Initial the decode
  val bv = BitVector(data)
  for {
    first <- headerBlockCode.decode(bv)
    list <- repeat(first)
  } yield {
    list.map(l => (list.value, l))
  }

I'm currently doing exactly the same exercise - so interested to know how you've progressed. 我目前正在做完全相同的练习-非常想知道您的进步情况。

I've also been experimenting with the VectorTerminatedByIsLastIndicator issue, although the approach taken is different. 我也一直在尝试使用VectorTerminatedByIsLastIndicator问题,尽管采用的方法不同。

This is some test code that I created (for Bar read MetadataBlockHeader). 这是我创建的一些测试代码(供Bar阅读MetadataBlockHeader)。 Note that the case class for MetadataBlockHeader does not include the isLast indicator - it is just added during encode, and removed during decode. 请注意,MetadataBlockHeader的案例类不包含isLast指示符-它仅在编码期间添加,而在解码期间删除。

case class Bar(value: Int)

case class Foo(list1: List[Bar], list2: List[Bar])

object Foo {

  def main(args: Array[String]) : Unit = {

    implicit val barCodec : Codec[Bar] = {
      ("value" | int32).hlist
    }.as[Bar]

    implicit val barListCodec : Codec[List[Bar]] = new Codec[List[Bar]] {

      case class IsLast[A](isLast: Boolean, thing: A)

      implicit val lastBarCodec : Codec[IsLast[Bar]] = {
        ("isLast" | bool) :: ("bar" | Codec[Bar])
      }.as[IsLast[Bar]]

      override def sizeBound: SizeBound = SizeBound.unknown

      override def encode(bars: List[Bar]): Attempt[BitVector] = {
        if (bars.size == 0) {
          Failure(Err("Cannot encode zero length list"))
        } else {
          val zippedBars = bars.zipWithIndex
          val lastBars = zippedBars.map(bi => IsLast(bi._2 + 1 == bars.size, bi._1))
          Codec.encodeSeq(lastBarCodec)(lastBars)
        }
      }

      override def decode(b: BitVector): Attempt[DecodeResult[List[Bar]]] = {
        val lastBars = decode(b, List.empty)
        val bars = lastBars.map(dr => dr.value.thing)
        Successful(DecodeResult(bars, lastBars.last.remainder))
      }

      @tailrec
      private def decode(b: BitVector, lastBars: List[DecodeResult[IsLast[Bar]]]) : List[DecodeResult[IsLast[Bar]]] = {
        val lastBar = lastBarCodec.decode(b).require
        val lastBarsInterim = lastBars :+ lastBar
        if (lastBar.value.isLast) lastBarsInterim
        else decode(lastBar.remainder, lastBarsInterim)
      }
    }

    implicit val fooCodec : Codec[Foo] = {
      (("list1" | Codec[List[Bar]])
      :: ("list2" | Codec[List[Bar]]))
    }.as[Foo]

    val bar1 = Bar(1)
    val bar2 = Bar(2)
    val bar3 = Bar(3)
    val bar4 = Bar(4)

    val aFoo = Foo(Seq(bar1, bar2).toList, Seq(bar3, bar4).toList)
    println("aFoo:       " + aFoo)

    val encodedFoo = fooCodec.encode(aFoo).require
    println("encodedFoo: " + encodedFoo)

    val decodedFoo = fooCodec.decode(encodedFoo).require.value
    println("decodedFoo: " + decodedFoo)

    assert(decodedFoo == aFoo)
  }

}

A fraction more background to this example can be found here . 这里可以找到该示例的更多背景信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM