Skip to content

Instantly share code, notes, and snippets.

@searler
Created March 21, 2015 19:39
Show Gist options
  • Save searler/7000c8956b8b49a456b5 to your computer and use it in GitHub Desktop.
Save searler/7000c8956b8b49a456b5 to your computer and use it in GitHub Desktop.
Scodec Discrimination by tag value range
class RangeDiscriminatorCodec[T](start: Int, end: Int, tag: Codec[Int], child: Codec[Int ~ T]) extends Codec[Int ~ T] {
override def sizeBound = tag.sizeBound | child.sizeBound
override def encode(value: Int ~ T) = value match {
case t ~ _ if t >= start && t <= end => child.encode(value)
case _ => Attempt.failure(Err("out of range"))
}
override def decode(bits: BitVector) = tag.decode(bits) match {
case Attempt.Successful(DecodeResult(value, remainder)) =>
if (value >= start && value <= end)
child.decode(remainder)
else
Attempt.failure(Err("out of range"))
case Attempt.Failure(err) => Attempt.failure(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment