Skip to content

Instantly share code, notes, and snippets.

@skvithalani
Last active February 19, 2020 10:21
Show Gist options
  • Save skvithalani/c2654a7bac3d20706de09a192d1a28d6 to your computer and use it in GitHub Desktop.
Save skvithalani/c2654a7bac3d20706de09a192d1a28d6 to your computer and use it in GitHub Desktop.
trait CborAkkaSerializer[Ser] extends Serializer {
private var registrations: List[(Class[_], Codec[_])] = Nil
protected def register[T <: Ser: Encoder: Decoder: ClassTag]: Unit = {
registrations ::= scala.reflect.classTag[T].runtimeClass -> Codec.of[T]
}
override def includeManifest: Boolean = true
override def toBinary(o: AnyRef): Array[Byte] = {
val codec = getCodec(o.getClass, "encoding")
val encoder = codec.encoder.asInstanceOf[Encoder[AnyRef]]
Cbor.encode(o)(encoder).toByteArray
}
override def fromBinary(bytes: Array[Byte], manifest: Option[Class[_]]): AnyRef = {
val codec = getCodec(manifest.get, "decoding")
val decoder = codec.decoder.asInstanceOf[Decoder[AnyRef]]
Cbor.decode(bytes).to[AnyRef](decoder).value
}
private def getCodec(classValue: Class[_], action: String): Codec[_] = {
registrations
.collectFirst {
case (clazz, codec) if clazz.isAssignableFrom(classValue) => codec
}
.getOrElse {
throw new RuntimeException(s"$action of $classValue is not configured")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment