Created
April 2, 2017 14:27
-
-
Save pchiusano/d3934a736b94bf281eb860d239d7f56c to your computer and use it in GitHub Desktop.
Fast binary encoding and decoding interfaces
This file contains 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
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