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
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) |