1 : #ifndef __SERIALISE_H
2 : #define __SERIALISE_H
3 :
4 : #include "types.hh"
5 :
6 :
7 : namespace nix {
8 :
9 :
10 : /* Abstract destination of binary data. */
11 : struct Sink
12 5783 : {
13 5828 : virtual ~Sink() { }
14 : virtual void operator () (const unsigned char * data, unsigned int len) = 0;
15 : };
16 :
17 :
18 : /* Abstract source of binary data. */
19 : struct Source
20 231 : {
21 276 : virtual ~Source() { }
22 :
23 : /* The callee should store exactly *len bytes in the buffer
24 : pointed to by data. It should block if that much data is not
25 : yet available, or throw an error if it is not going to be
26 : available. */
27 : virtual void operator () (unsigned char * data, unsigned int len) = 0;
28 : };
29 :
30 :
31 : /* A sink that writes data to a file descriptor. */
32 : struct FdSink : Sink
33 196 : {
34 : int fd;
35 :
36 92 : FdSink()
37 92 : {
38 92 : fd = 0;
39 92 : }
40 :
41 59 : FdSink(int fd)
42 59 : {
43 59 : this->fd = fd;
44 59 : }
45 :
46 : void operator () (const unsigned char * data, unsigned int len);
47 : };
48 :
49 :
50 : /* A source that reads data from a file descriptor. */
51 : struct FdSource : Source
52 199 : {
53 : int fd;
54 :
55 92 : FdSource()
56 92 : {
57 92 : fd = 0;
58 92 : }
59 :
60 62 : FdSource(int fd)
61 62 : {
62 62 : this->fd = fd;
63 62 : }
64 :
65 : void operator () (unsigned char * data, unsigned int len);
66 : };
67 :
68 :
69 : /* A sink that writes data to a string. */
70 : struct StringSink : Sink
71 144 : {
72 : string s;
73 1568 : virtual void operator () (const unsigned char * data, unsigned int len)
74 : {
75 1568 : s.append((const char *) data, len);
76 1568 : }
77 : };
78 :
79 :
80 : /* A source that reads data from a string. */
81 : struct StringSource : Source
82 72 : {
83 : string & s;
84 : unsigned int pos;
85 72 : StringSource(string & _s) : s(_s), pos(0) { }
86 1568 : virtual void operator () (unsigned char * data, unsigned int len)
87 : {
88 1568 : s.copy((char *) data, len, pos);
89 1568 : pos += len;
90 1568 : if (pos > s.size())
91 0 : throw Error("end of string reached");
92 1568 : }
93 : };
94 :
95 :
96 : void writePadding(unsigned int len, Sink & sink);
97 : void writeInt(unsigned int n, Sink & sink);
98 : void writeLongLong(unsigned long long n, Sink & sink);
99 : void writeString(const string & s, Sink & sink);
100 : void writeStringSet(const StringSet & ss, Sink & sink);
101 :
102 : void readPadding(unsigned int len, Source & source);
103 : unsigned int readInt(Source & source);
104 : unsigned long long readLongLong(Source & source);
105 : string readString(Source & source);
106 : StringSet readStringSet(Source & source);
107 :
108 :
109 : }
110 :
111 :
112 : #endif /* !__SERIALISE_H */
|