File: BT.scala

package info (click to toggle)
scala-tools-sbinary 0.4.2-on-scala-2.11.0~M5-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 248 kB
  • sloc: xml: 23; makefile: 6
file content (61 lines) | stat: -rw-r--r-- 1,685 bytes parent folder | download | duplicates (2)
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
52
53
54
55
56
57
58
59
60
61
package sbintest

import sbinary._
import DefaultProtocol._
import Operations._

	// Binary tree data types that will be
	//   created and converted to/from byte arrays

sealed abstract class BT;
case class Bin(left : BT, right : BT) extends BT;
case class Leaf(label : String) extends BT;

	// Custom protocol for (de)serializing binary trees

object MyProtocol extends DefaultProtocol {
	implicit object BTFormat extends Format[BT]{
		def reads(in : Input) = read[Byte](in) match {
			case 0 => Bin(reads(in), reads(in));
			case _ => Leaf(read[String](in))
		}

		def writes(out : Output, value : BT) = value match {
			case Bin(left, right) => write[Byte](out, 0); writes(out, left); writes(out, right);
			case Leaf(label) => write[Byte](out, 1); write(out, label);
		}
	}
}

	// test runner

object main {
	def main(args : Array[String]) : Unit = {
		val input = List("foo", "bar", "baz")
		println(input)

		val binary = toByteArray(input)
		println(showArray(binary))

		val normalAgain = fromByteArray[List[String]](binary)
		println(normalAgain)

		toFile(input)(new java.io.File("foo.bin"))
		println(fromFile[List[String]](new java.io.File("foo.bin")))

		import MyProtocol._

		val someTree = Bin(Leaf("foo"), Bin(Leaf("bar"), Leaf("baz")))
		println(someTree)

		val someTreeInAByteArray = toByteArray[BT](someTree)
		println(showArray(someTreeInAByteArray))

		val theSameTree = fromByteArray[BT](someTreeInAByteArray)
		println(theSameTree)
	}
	// utility methods for printing a byte array
	def showArray(b: Array[Byte]) = b.map(showByte).mkString(" ")
	def showByte(b: Byte) = pad( ((b+256) % 256).toHexString )
	def pad(s: String) = if(s.length == 1) "0" + s else s
}