Created
March 21, 2015 19:39
-
-
Save searler/7000c8956b8b49a456b5 to your computer and use it in GitHub Desktop.
Scodec Discrimination by tag value range
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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