132
|
1
|
|
2 private import tango.io.protocol.Reader,
|
|
3 tango.io.protocol.Writer,
|
|
4 tango.io.FileConduit;
|
|
5
|
|
6 /*******************************************************************************
|
|
7
|
|
8 Use cascading reads & writes to handle a composite class. There is
|
|
9 just one primary call for output, and just one for input, but the
|
|
10 classes propogate the request as appropriate.
|
|
11
|
|
12 Note that the class instances don't know how their content will be
|
|
13 represented; that is dictated by the caller (via the reader/writer
|
|
14 implementation).
|
|
15
|
|
16 Note also that this only serializes the content. To serialize the
|
|
17 classes too, take a look at the Pickle.d example.
|
|
18
|
|
19 *******************************************************************************/
|
|
20
|
|
21 void main()
|
|
22 {
|
|
23 // define a serializable class (via interfaces)
|
|
24 class Wumpus : IReadable, IWritable
|
|
25 {
|
|
26 private int a = 11,
|
|
27 b = 112,
|
|
28 c = 1024;
|
|
29
|
|
30 void read (IReader input)
|
|
31 {
|
|
32 input (a) (b) (c);
|
|
33 }
|
|
34
|
|
35 void write (IWriter output)
|
|
36 {
|
|
37 output (a) (b) (c);
|
|
38 }
|
|
39 }
|
|
40
|
|
41
|
|
42 // define a serializable class (via interfaces)
|
|
43 class Wombat : IReadable, IWritable
|
|
44 {
|
|
45 private Wumpus wumpus;
|
|
46 private char[] x = "xyz";
|
|
47 private bool y = true;
|
|
48 private float z = 3.14159;
|
|
49
|
|
50 this (Wumpus wumpus)
|
|
51 {
|
|
52 this.wumpus = wumpus;
|
|
53 }
|
|
54
|
|
55 void read (IReader input)
|
|
56 {
|
|
57 input (x) (y) (z) (wumpus);
|
|
58 }
|
|
59
|
|
60 void write (IWriter output)
|
|
61 {
|
|
62 output (x) (y) (z) (wumpus);
|
|
63 }
|
|
64 }
|
|
65
|
|
66 // construct a Wombat
|
|
67 auto wombat = new Wombat (new Wumpus);
|
|
68
|
|
69 // open a file for IO
|
|
70 auto file = new FileConduit ("random.bin", FileConduit.ReadWriteCreate);
|
|
71
|
|
72 // construct reader & writer upon the file, with binary IO
|
|
73 auto output = new Writer (file);
|
|
74 auto input = new Reader (file);
|
|
75
|
|
76 // write both Wombat & Wumpus (and flush them)
|
|
77 output (wombat) ();
|
|
78
|
|
79 // rewind to file start
|
|
80 file.seek (0);
|
|
81
|
|
82 // read both back again
|
|
83 input (wombat);
|
|
84 }
|
|
85
|