Skip to content

Instantly share code, notes, and snippets.

@pchiusano
Created April 2, 2017 14:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pchiusano/d3934a736b94bf281eb860d239d7f56c to your computer and use it in GitHub Desktop.
Save pchiusano/d3934a736b94bf281eb860d239d7f56c to your computer and use it in GitHub Desktop.
Fast binary encoding and decoding interfaces
package fastcodecs
import java.nio.{ByteBuffer, BufferUnderflowException}
abstract class Decoder[+A] {
/**
* Read a value from the `ByteBuffer`, advancing the offset if successful.
* Result is stored in `result`, unboxed if possible.
* On failure, a `DecodingFailure` is thrown.
*/
def apply(bytes: ByteBuffer, result: Result): Unboxed[A]
}
abstract class Encoder[-A] {
/**
* Write an `A` value to the `output` buffer, advancing the offset.
* If `output` is not large enough to contain the encoded value,
* an `EncodingBufferOverflow` is thrown and this function should be
* called again with a larger buffer.
*/
def apply(a: A, output: ByteBuffer): Unit
}
object decoders {
def double = new Decoder[Double] {
val err = DecodingFailure(List("double"))
def apply(bytes: ByteBuffer, result: Result) =
try { result.unboxed = bytes.getDouble }
catch { case e: BufferUnderflowException => throw err }
}
}
type Unboxed[+A] = Unit // would put this in package object
case class DecodingFailure(msgs: List[String]) extends Throwable {
override def fillInStackTrace = this
}
case object EncodingBufferOverflow extends Throwable {
override def fillInStackTrace = this
}
case class Result(var boxed: Any = null, var unboxed: Double = 0.0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment