Skip to content

Instantly share code, notes, and snippets.

@searler
Last active August 29, 2015 14:17
Show Gist options
  • Save searler/bf2c2573946dcf896c1f to your computer and use it in GitHub Desktop.
Save searler/bf2c2573946dcf896c1f to your computer and use it in GitHub Desktop.
This code supports on over-the-wire serialization where the payload is normally very small (10s of bytes) but the maximum is 2^32 bytes.

A length < 255 is encoded using only uint(8), and thus requires only one byte of overhead.

A length > 254 is encoded using a marker byte (255) followed by the length using uint(32), requiring 5 bytes of overhead

val size: Codec[Int] = new Codec[Int] {
private val marker = 255
override def sizeBound = uint(8).sizeBound | uint(32).sizeBound
override def encode(value: Int) = if (value < marker)
uint(8).encode(value)
else
(uint(8) ~ uint(32)).encode(marker ~ value)
override def decode(bits: BitVector) = {
uint(8).decode(bits) match {
case Attempt.Successful(DecodeResult(value, remainder)) if value == marker => int(32).decode(remainder)
case _@ x => x
}
}
}
def body[T](contents: Codec[T]) = variableSizeBytes(size, contents)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment