Skip to content

Instantly share code, notes, and snippets.

@searler
Created March 21, 2015 19:30
Show Gist options
  • Save searler/cb4d9483375422d6d253 to your computer and use it in GitHub Desktop.
Save searler/cb4d9483375422d6d253 to your computer and use it in GitHub Desktop.
Codec to extract value w/o consuming source BitVector

The scodec discriminated.by(tag).typecase(n,message) does not suffice to match all message structures:

  1. tag is at start of structure
  2. value of tag is not required by the message codec.

The PeekCodec uses the target codec to extract a value, but returns the original BitVector so the tag value can be re-decoded by a subsequent codec.

private class PeekCodec[T](target: Codec[T]) extends Codec[T] {
def sizeBound = target.sizeBound
def encode(value: T) = target.encode(value)
def decode(buffer: BitVector) =
target.decode(buffer) match {
case Attempt.Successful(DecodeResult(value, rest)) => Attempt.successful(DecodeResult(value, buffer))
case f: Attempt.Failure => f
}
}
def peek[T](target: Codec[T]) = new PeekCodec(target)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment