Skip to content

Instantly share code, notes, and snippets.

@abhandaru
Last active November 21, 2019 19:26
Show Gist options
  • Select an option

  • Save abhandaru/f544d005ff05bcbb1eb09c7baa61cdeb to your computer and use it in GitHub Desktop.

Select an option

Save abhandaru/f544d005ff05bcbb1eb09c7baa61cdeb to your computer and use it in GitHub Desktop.
dependencies:
com.thesamet.scalapb:
scalapb-runtime:
lang: scala
version: '0.10.0-M1'
// Consider pulling in Algebird. See full implementation:
// https://github.com/twitter/bijection/blob/0.8.0/bijection-core/src/main/scala/com/twitter/bijection/Bijection.scala
@implicitNotFound(msg = "Could not find a BytesBijection for ${T}")
trait Bijection[A, B] extends (A => B) {
def invert(b: B): A
def andThen[C](g: Bijection[B, C]): Bijection[A, C] = {
val self = this
new Bijection[A, C] {
override def apply(a: A) = g(self.apply(a))
override def invert(c: C) = self.invert(g.invert(c))
}
}
}
object ProtobufBytesBijection {
import scalapb._
type MessageDef[T] = GeneratedMessage with Message[T]
type CompanionDef[T <: MessageDef[T]] = GeneratedMessageCompanion[T]
implicit def apply[T <: MessageDef[T]: CompanionDef]: Bijection[T, Array[Byte]] = {
new Bijection[T, Array[Byte]] {
override def apply(t: T) = t.toByteArray
override def invert(buf: Array[Byte]) = implicitly[CompanionDef[T]].parseFrom(buf)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment