summaryrefslogtreecommitdiff
path: root/src/library/scala/util/Marshal.scala
blob: c2269cde4580ddad1d25320e74efb7751eda5647 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/*                     __                                               *\
**     ________ ___   / /  ___     Scala API                            **
**    / __/ __// _ | / /  / _ |    (c) 2008-2011, LAMP/EPFL             **
**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
** /____/\___/_/ |_/____/_/ | |                                         **
**                          |/                                          **
\*                                                                      */



package scala.util

/**
 * Marshalling of Scala objects using Scala manifests.
 *
 * @author Stephane Micheloud
 * @version 1.0
 */
object Marshal {
  import java.io._
  import scala.reflect.ClassManifest

  def dump[A](o: A)(implicit m: ClassManifest[A]): Array[Byte] = {
    val ba = new ByteArrayOutputStream(512)
    val out = new ObjectOutputStream(ba)
    out.writeObject(m)
    out.writeObject(o)
    out.close()
    ba.toByteArray()
  }

  @throws(classOf[IOException])
  @throws(classOf[ClassCastException])
  @throws(classOf[ClassNotFoundException])
  def load[A](buffer: Array[Byte])(implicit expected: ClassManifest[A]): A = {
    val in = new ObjectInputStream(new ByteArrayInputStream(buffer))
    val found = in.readObject.asInstanceOf[ClassManifest[_]]
    // todo. [Eugene] needs review, since ClassManifests no longer capture typeArguments
    if (found.tpe <:< expected.tpe) {
      val o = in.readObject.asInstanceOf[A]
      in.close()
      o
    } else {
      in.close()
      throw new ClassCastException("type mismatch;"+
        "\n found   : "+found+
        "\n required: "+expected)
    }
  }

}