Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Scala serialization issue, pickling library.
import java.io.{ByteArrayInputStream, ByteArrayOutputStream, ObjectInputStream, ObjectOutputStream}
import scala.pickling.Defaults._, scala.pickling.binary._
object Main extends App {
SerializationTest.run()
}
case class IntSeqHolder(seq: Seq[Int])
case class Pupper(name: String)
case class Doggies(oldPuppers: Seq[Pupper])
object SerializationTest {
def run() {
val data = Seq(
Seq(1),
IntSeqHolder(Seq(1)),
Seq(Some(1)),
Seq(Pupper("Collin")),
Doggies(Seq(Pupper("Adolf"), Pupper("Ben")))
)
val runners = Seq(
("classic", testClassic _),
("pickling", testPickling _)
)
for {x <- data} {
println(s"-- Running tests with data $x.")
println()
for {(runnerName, fn) <- runners} {
println(s"Using $runnerName on $x")
try {
val (res, serialized) = fn(x)
println(s"$x ==> ${serialized.length} B ==> $res")
assert(x == res)
println(s"Test succeeded.")
} catch {
case e: Throwable =>
println(s"Test failed: ${e.getClass.getSimpleName} - ${e.getMessage}")
e.printStackTrace()
}
println()
}
println()
}
}
def testClassic(input: AnyRef): (AnyRef, Array[Byte]) = {
val serialized = {
val bos = new ByteArrayOutputStream()
val out = new ObjectOutputStream(bos)
out.writeObject(input)
val r = bos.toByteArray
out.close()
bos.close()
r
}
val unserialized = {
val bis = new ByteArrayInputStream(serialized)
val in = new ObjectInputStream(bis)
val r = in.readObject()
in.close()
bis.close()
r
}
(unserialized, serialized)
}
def testPickling(input: AnyRef): (AnyRef, Array[Byte]) = {
val pickled: Array[Byte] = input.pickle.value
(pickled.unpickle[AnyRef], pickled)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.