Skip to content

Instantly share code, notes, and snippets.

@gszeliga
Created May 10, 2014 17:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gszeliga/fdea104aa87252ec8a11 to your computer and use it in GitHub Desktop.
Save gszeliga/fdea104aa87252ec8a11 to your computer and use it in GitHub Desktop.
import scala.util.parsing.input.Reader
import scala.util.parsing.input.CharArrayReader.EofCh
import scala.util.parsing.input.Position
case class ByteOffsetPosition(offset: Int) extends Position {
final val line = 1
def column = offset + 1
def lineContents: String = ""
}
class ByteReader (val bytes: Array[Byte], override val offset: Int = 0) extends Reader[Byte] {
def this(reader: Reader[_]) = this(reader.source.toString.getBytes, 0)
def this(bytes: Seq[Byte]) = this(bytes.toArray, 0)
def this(str: String) = this(str.getBytes, 0)
def first: Byte = if (offset < bytes.length) bytes(offset) else EofCh.toByte
def rest: ByteReader = if (offset < bytes.length) new ByteReader(bytes, offset + 1) else this
def pos: Position = ByteOffsetPosition(offset)
def atEnd = offset >= bytes.length
def byteAt(n: Int) = bytes(n)
def length = bytes.length - offset
override def drop(n: Int): ByteReader = new ByteReader(bytes, offset + n)
def take(n: Int): Seq[Byte] = bytes drop offset take n
override def toString = "ByteReader(%d / %d)".format(offset, bytes.length)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment