Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 79 lines (63 sloc) 2.449 kb
d5f4be40 »
2011-07-30 srs org
1 package concrete
2
3 import sbinary.Operations
4 import scalaz._
5 import Scalaz._
6 import concrete.SBinaryScalaz._
7 import concrete.SafeCopy._
8
9 object Example {
10
11 import Instances._
12
13 type Name = String
14 type Address = String
15 type Phone = String
16
17 // Initial Version
18 case class Contacts_v0(contacts: List[(Name, Address)])
19
20 object Contacts_v0 {
21 implicit val safecopy: SafeCopy[Contacts_v0] = new SafeCopy[Contacts_v0] {
22 val getCopy = contain(safeGet[List[(Name, Address)]] map (Contacts_v0(_)))
23
24 def putCopy(cs: Contacts_v0) = contain(safePut(cs.contacts))
25 }
26 }
27
28 // Next version of the data introduces a type:
29 case class Contact(name: Name, address: Address, phone: Phone)
30
31 object Contact {
32 implicit val safecopy: SafeCopy[Contact] = new SafeCopy[Contact] {
33 val getCopy = contain {
34 for (name <- safeGet[Name]; address <- safeGet[Address]; phone <- safeGet[Phone]) yield {Contact(name, address, phone)}
35 }
36
37 def putCopy(c: Contact) = contain {
38 safePut(c.name) >|> safePut(c.address) >|> safePut(c.phone)
39 }
40 }
41 }
42
43 // And a modification of the address book to the Contact type
44 case class Contacts(contacts: List[Contact])
45
46 object Contacts {
47 // TODO: Fix the initialisation order dependencies of this. If the Migrate
48 // instance is declared after the SafeCopy instance, then null pointers
49 // abound.
50
51 // First, declare how to get here from the old version that would be serialised
52 implicit val m1 = new Migrate[Contacts, Contacts_v0] {
53 val extended = implicitly[SafeCopy[Contacts_v0]]
54
55 def migrate(old: Contacts_v0): Contacts = Contacts {
56 old.contacts map {case (name, address) => Contact(name, address, "555-5555")}
57 }
58 }
59
60 implicit val safecopy: SafeCopy[Contacts] = new SafeCopy[Contacts] {
61 override val version = Version(2)
62 override val kind = extension[Contacts, Contacts_v0]
63 val getCopy = contain(safeGet[List[Contact]].map(Contacts(_)))
64 def putCopy(cs: Contacts) = contain(safePut(cs.contacts))
65 }
66 }
67
68 def main(args: Array[String]) {
69 println(implicitly[SafeCopy[Contacts_v0]])
70 val init = Contacts_v0(("Nick", "lolol") :: Nil)
71 println(init)
72 val writtenInit: Write = safePut(init)
73 println("Got a write")
74 val as = Operations.toByteArray(writtenInit)
75 println(as)
76 val next: Contacts = Operations.fromByteArray(as)(safeGet[Contacts])
77 println(next)
78 }
79 }
Something went wrong with that request. Please try again.