TEMPLATE MAGIC FOR GREAT JUSTICE
[invirt/third/libt4.git] / rpc / marshall.h
1 #ifndef marshall_h
2 #define marshall_h
3
4 #include <iostream>
5 #include <sstream>
6 #include <string>
7 #include <vector>
8 #include <map>
9 #include <stdlib.h>
10 #include <string.h>
11 #include <cstddef>
12 #include <inttypes.h>
13 #include "lang/verify.h"
14
15 struct req_header {
16         req_header(int x=0, int p=0, int c = 0, int s = 0, int xi = 0):
17                 xid(x), proc(p), clt_nonce(c), srv_nonce(s), xid_rep(xi) {}
18         int xid;
19         int proc;
20         unsigned int clt_nonce;
21         unsigned int srv_nonce;
22         int xid_rep;
23 };
24
25 struct reply_header {
26         reply_header(int x=0, int r=0): xid(x), ret(r) {}
27         int xid;
28         int ret;
29 };
30
31 typedef int rpc_sz_t;
32
33 //size of initial buffer allocation 
34 #define DEFAULT_RPC_SZ 1024
35 #define RPC_HEADER_SZ (std::max(sizeof(req_header), sizeof(reply_header)) + sizeof(rpc_sz_t))
36
37 struct pass {
38     template<typename... Args> inline pass(Args&&...) {}
39 };
40
41 class marshall {
42         private:
43                 char *_buf;     // Base of the raw bytes buffer (dynamically readjusted)
44                 int _capa;      // Capacity of the buffer
45                 int _ind;       // Read/write head position
46
47         public:
48                 marshall() {
49                         _buf = (char *) malloc(sizeof(char)*DEFAULT_RPC_SZ);
50                         VERIFY(_buf);
51                         _capa = DEFAULT_RPC_SZ;
52                         _ind = RPC_HEADER_SZ;
53                 }
54
55         template <typename... Args> marshall(const Args&... args) : marshall() {
56             (void)pass{(*this << args)...};
57         }
58
59                 ~marshall() { 
60                         if (_buf) 
61                                 free(_buf); 
62                 }
63
64                 int size() { return _ind;}
65                 char *cstr() { return _buf;}
66
67                 void rawbyte(unsigned char);
68                 void rawbytes(const char *, int);
69
70                 // Return the current content (excluding header) as a string
71                 std::string get_content() { 
72                         return std::string(_buf+RPC_HEADER_SZ,_ind-RPC_HEADER_SZ);
73                 }
74
75                 // Return the current content (excluding header) as a string
76                 std::string str() {
77                         return get_content();
78                 }
79
80                 void pack(int i);
81
82                 void pack_req_header(const req_header &h) {
83                         int saved_sz = _ind;
84                         //leave the first 4-byte empty for channel to fill size of pdu
85                         _ind = sizeof(rpc_sz_t); 
86                         pack(h.xid);
87                         pack(h.proc);
88                         pack((int)h.clt_nonce);
89                         pack((int)h.srv_nonce);
90                         pack(h.xid_rep);
91                         _ind = saved_sz;
92                 }
93
94                 void pack_reply_header(const reply_header &h) {
95                         int saved_sz = _ind;
96                         //leave the first 4-byte empty for channel to fill size of pdu
97                         _ind = sizeof(rpc_sz_t); 
98                         pack(h.xid);
99                         pack(h.ret);
100                         _ind = saved_sz;
101                 }
102
103                 void take_buf(char **b, int *s) {
104                         *b = _buf;
105                         *s = _ind;
106                         _buf = NULL;
107                         _ind = 0;
108                         return;
109                 }
110 };
111
112 marshall& operator<<(marshall &, bool);
113 marshall& operator<<(marshall &, unsigned int);
114 marshall& operator<<(marshall &, int);
115 marshall& operator<<(marshall &, unsigned char);
116 marshall& operator<<(marshall &, char);
117 marshall& operator<<(marshall &, unsigned short);
118 marshall& operator<<(marshall &, short);
119 marshall& operator<<(marshall &, unsigned long long);
120 marshall& operator<<(marshall &, const std::string &);
121
122 template <class C> marshall &
123 operator<<(marshall &m, std::vector<C> v)
124 {
125         m << (unsigned int) v.size();
126         for(unsigned i = 0; i < v.size(); i++)
127                 m << v[i];
128         return m;
129 }
130
131 template <class A, class B> marshall &
132 operator<<(marshall &m, const std::map<A,B> &d) {
133         typename std::map<A,B>::const_iterator i;
134
135         m << (unsigned int) d.size();
136
137         for (i = d.begin(); i != d.end(); i++) {
138                 m << i->first << i->second;
139         }
140         return m;
141 }
142
143 template <class A> marshall &
144 operator<<(marshall &m, const std::list<A> &d) {
145     m << std::vector<A>(d.begin(), d.end());
146     return m;
147 }
148
149 template <class A, class B> marshall &
150 operator<<(marshall &m, const std::pair<A,B> &d) {
151     m << d.first;
152     m << d.second;
153     return m;
154 }
155
156 class unmarshall {
157         private:
158                 char *_buf;
159                 int _sz;
160                 int _ind;
161                 bool _ok;
162         public:
163                 unmarshall(): _buf(NULL),_sz(0),_ind(0),_ok(false) {}
164                 unmarshall(char *b, int sz): _buf(b),_sz(sz),_ind(),_ok(true) {}
165                 unmarshall(const std::string &s) : _buf(NULL),_sz(0),_ind(0),_ok(false) 
166                 {
167                         //take the content which does not exclude a RPC header from a string
168                         take_content(s);
169                 }
170                 ~unmarshall() {
171                         if (_buf) free(_buf);
172                 }
173
174                 //take contents from another unmarshall object
175                 void take_in(unmarshall &another);
176
177                 //take the content which does not exclude a RPC header from a string
178                 void take_content(const std::string &s) {
179                         _sz = s.size()+RPC_HEADER_SZ;
180                         _buf = (char *)realloc(_buf,_sz);
181                         VERIFY(_buf);
182                         _ind = RPC_HEADER_SZ;
183                         memcpy(_buf+_ind, s.data(), s.size());
184                         _ok = true;
185                 }
186
187                 bool ok() { return _ok; }
188                 char *cstr() { return _buf;}
189                 bool okdone();
190                 unsigned int rawbyte();
191                 void rawbytes(std::string &s, unsigned int n);
192
193                 int ind() { return _ind;}
194                 int size() { return _sz;}
195                 void unpack(int *); //non-const ref
196                 void take_buf(char **b, int *sz) {
197                         *b = _buf;
198                         *sz = _sz;
199                         _sz = _ind = 0;
200                         _buf = NULL;
201                 }
202
203                 void unpack_req_header(req_header *h) {
204                         //the first 4-byte is for channel to fill size of pdu
205                         _ind = sizeof(rpc_sz_t); 
206                         unpack(&h->xid);
207                         unpack(&h->proc);
208                         unpack((int *)&h->clt_nonce);
209                         unpack((int *)&h->srv_nonce);
210                         unpack(&h->xid_rep);
211                         _ind = RPC_HEADER_SZ;
212                 }
213
214                 void unpack_reply_header(reply_header *h) {
215                         //the first 4-byte is for channel to fill size of pdu
216                         _ind = sizeof(rpc_sz_t); 
217                         unpack(&h->xid);
218                         unpack(&h->ret);
219                         _ind = RPC_HEADER_SZ;
220                 }
221
222         template <class A>
223         inline A grab() {
224             A a;
225             *this >> a;
226             return a;
227         }
228 };
229
230 unmarshall& operator>>(unmarshall &, bool &);
231 unmarshall& operator>>(unmarshall &, unsigned char &);
232 unmarshall& operator>>(unmarshall &, char &);
233 unmarshall& operator>>(unmarshall &, unsigned short &);
234 unmarshall& operator>>(unmarshall &, short &);
235 unmarshall& operator>>(unmarshall &, unsigned int &);
236 unmarshall& operator>>(unmarshall &, int &);
237 unmarshall& operator>>(unmarshall &, unsigned long long &);
238 unmarshall& operator>>(unmarshall &, std::string &);
239
240 template <class C> unmarshall &
241 operator>>(unmarshall &u, std::vector<C> &v)
242 {
243         unsigned n;
244         u >> n;
245     v.clear();
246     while (n--) {
247         C c;
248         u >> c;
249         v.push_back(c);
250     }
251         return u;
252 }
253
254 template <class A, class B> unmarshall &
255 operator>>(unmarshall &u, std::map<A,B> &d) {
256         unsigned n;
257         u >> n;
258         d.clear();
259     while (n--) {
260         A a;
261         B b;
262         u >> a >> b;
263         d[a] = b;
264     }
265         return u;
266 }
267
268 template <class C> unmarshall &
269 operator>>(unmarshall &u, std::list<C> &l) {
270     unsigned n;
271     u >> n;
272     l.clear();
273     while (n--) {
274         C c;
275         u >> c;
276         l.push_back(c);
277     }
278     return u;
279 }
280
281 template <class A, class B> unmarshall &
282 operator>>(unmarshall &u, std::pair<A,B> &d) {
283     return u >> d.first >> d.second;
284 }
285
286 template <size_t...> struct tuple_indices {};
287 template <size_t S, class IntTuple, size_t E> struct make_indices_imp;
288 template <size_t S, size_t ...Indices, size_t E> struct make_indices_imp<S, tuple_indices<Indices...>, E> {
289     typedef typename make_indices_imp<S+1, tuple_indices<Indices..., S>, E>::type type;
290 };
291 template <size_t E, size_t ...Indices> struct make_indices_imp<E, tuple_indices<Indices...>, E> {
292     typedef tuple_indices<Indices...> type;
293 };
294 template <size_t E, size_t S = 0> struct make_tuple_indices {
295     typedef typename make_indices_imp<S, tuple_indices<>, E>::type type;
296 };
297
298 struct VerifyOnFailure {
299     static inline int unmarshall_args_failure() {
300         VERIFY(0);
301         return 0;
302     }
303 };
304
305 typedef std::function<int(unmarshall &, marshall &)> handler;
306
307 using std::move;
308 using std::get;
309 using std::tuple;
310 using std::decay;
311
312 #include <iostream>
313
314 template <class F, class R, class args_type, size_t ...Indices>
315 typename std::enable_if<!std::is_member_function_pointer<F>::value, int>::type
316 invoke(F f, void *, R & r, args_type & t, tuple_indices<Indices...>) {
317     return f(r, move(get<Indices>(t))...);
318 }
319
320 template <class F, class C, class R, class args_type, size_t ...Indices>
321 typename std::enable_if<std::is_member_function_pointer<F>::value, int>::type
322 invoke(F f, C *c, R & r, args_type & t, tuple_indices<Indices...>) {
323     return (c->*f)(r, move(get<Indices>(t))...);
324 }
325
326 template <class Functor,
327           class Instance,
328           class Signature,
329           class ErrorHandler=VerifyOnFailure> struct marshalled_func_imp;
330
331 template <class F, class C, class ErrorHandler, class R, class... Args>
332 struct marshalled_func_imp<F, C, int(R&, Args...), ErrorHandler> {
333     using result_type = R;
334     using args_type = tuple<typename decay<Args>::type...>;
335     using index_type = typename make_tuple_indices<sizeof...(Args)>::type;
336
337     static inline int call(F f, C *c, unmarshall &u, marshall &m) {
338         args_type t{std::move(std::tuple<Args...>{u.grab<Args>()...})};
339         if (!u.okdone())
340             return ErrorHandler::unmarshall_args_failure();
341         R r;
342         int b = invoke(f, c, r, t, index_type());
343         m << r;
344         return b;
345     }
346
347     static inline handler *wrap(F f, C *c=nullptr) {
348         typename decay<F>::type f_ = f;
349         return new handler([f_, c](unmarshall &u, marshall &m) -> int {
350             return call(f_, c, u, m);
351         });
352     }
353 };
354
355 template <class Functor,
356           class Signature,
357           class ErrorHandler=VerifyOnFailure> struct marshalled_func;
358
359 template <class F, class ErrorHandler, class... Args>
360 struct marshalled_func<F, int(*)(Args...), ErrorHandler> :
361     public marshalled_func_imp<F, void, int(Args...), ErrorHandler> {};
362
363 template <class F, class ErrorHandler, class C, class... Args>
364 struct marshalled_func<F, int(C::*)(Args...), ErrorHandler> :
365     public marshalled_func_imp<F, C, int(Args...), ErrorHandler> {};
366
367 template <class F, class ErrorHandler, class Signature>
368 struct marshalled_func<F, std::function<Signature>, ErrorHandler> :
369     public marshalled_func_imp<F, void, Signature, ErrorHandler> {};
370
371 #endif