Skip to content

Instantly share code, notes, and snippets.

@gszeliga
Created May 12, 2014 22:36
Show Gist options
  • Save gszeliga/ac880789ddd1eff7b473 to your computer and use it in GitHub Desktop.
Save gszeliga/ac880789ddd1eff7b473 to your computer and use it in GitHub Desktop.
Single digit parser
trait BencodeParser extends Parsers with BencodeConstants {
type Elem = Byte
implicit def charToParser(ch: Char) = elem(ch.toByte)
def delimitedBy[A](left: Parser[Byte], right: Parser[Byte])(p: Parser[A]): Parser[A] = left ~> p <~ right
def single_digit = new Parser[String] {
val re = """\d""".r
def apply(in: Input) = {
if (in.atEnd) Failure("End of input reached", in)
else {
//Specification says numbers are coded in ASCII
val n = new String(Array(in.first.asInstanceOf[Byte]), DEFAULT_NUMBER_ENCODING)
re.findFirstIn(n) map (Success(_, in.rest)) getOrElse (Failure(s"'$n' is not a number", in))
}
}
} named ("digit")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment