Scodec StreamDecoder example

I’ve been spending the last few days getting my head around StreamDecoders from the scodec library. Here’s a simple example showing it’s usage:

package scodec.helloworld


import scodec._
import scodec.codecs.implicits._
import{decode, encode}

import scala.concurrent.{Await, Promise}
import scala.concurrent.duration.Duration

case class Foo(value: Int)

object Foo {

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

    val codec = Codec[Foo]

    val aFoo = Foo(42)
    val encodedFoo = codec.encode(aFoo).require

    val stream = new ByteArrayInputStream(encodedFoo.toByteArray)

    val p = Promise[Foo]()
    val streamDecoder = decode.once(codec).decodeInputStream(stream) Foo) => p.success(f)).run.unsafeRun()
    val decodedFoo = Await.result(p.future, Duration.Inf)

    assert(decodedFoo == aFoo)