Created
June 23, 2016 10:52
-
-
Save mnn/2805fbcac14a6b55bd956c83a080e45e to your computer and use it in GitHub Desktop.
Scala serialization issue, pickling library.
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
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