Split out marshall code into a new file
[invirt/third/libt4.git] / rpc / marshall.h
index 676a682..98856e4 100644 (file)
@@ -1,22 +1,19 @@
 #ifndef marshall_h
 #define marshall_h
 
-#include <iostream>
-#include <sstream>
-#include <string>
-#include <vector>
-#include <map>
-#include <stdlib.h>
-#include <string.h>
+#include "types.h"
+#include <cstring>
 #include <cstddef>
-#include <inttypes.h>
-#include "lang/verify.h"
+#include <cinttypes>
+
+using proc_t = uint32_t;
+using status_t = int32_t;
 
 struct request_header {
-    request_header(int x=0, int p=0, unsigned c=0, unsigned s=0, int xi=0) :
+    request_header(int x=0, proc_t p=0, unsigned c=0, unsigned s=0, int xi=0) :
         xid(x), proc(p), clt_nonce(c), srv_nonce(s), xid_rep(xi) {}
     int xid;
-    int proc;
+    proc_t proc;
     unsigned int clt_nonce;
     unsigned int srv_nonce;
     int xid_rep;
@@ -53,7 +50,9 @@ typedef int rpc_sz_t;
 
 //size of initial buffer allocation
 #define DEFAULT_RPC_SZ 1024
-#define RPC_HEADER_SZ (std::max(sizeof(request_header), sizeof(reply_header)) + sizeof(rpc_sz_t))
+#define RPC_HEADER_SZ (max(sizeof(request_header), sizeof(reply_header)) + sizeof(rpc_sz_t))
+
+struct pass { template <typename... Args> inline pass(Args&&...) {} };
 
 class marshall {
     private:
@@ -63,17 +62,14 @@ class marshall {
 
         inline void reserve(size_t n) {
             if((index_+n) > capacity_){
-                capacity_ += std::max(capacity_, n);
+                capacity_ += max(capacity_, n);
                 VERIFY (buf_ != NULL);
                 buf_ = (char *)realloc(buf_, capacity_);
                 VERIFY(buf_);
             }
         }
     public:
-        struct pass { template <typename... Args> inline pass(Args&&...) {} };
-
         template <typename... Args>
-
         marshall(const Args&... args) {
             buf_ = (char *) malloc(sizeof(char)*DEFAULT_RPC_SZ);
             VERIFY(buf_);
@@ -103,12 +99,12 @@ class marshall {
         }
 
         // Return the current content (excluding header) as a string
-        std::string get_content() {
-            return std::string(buf_+RPC_HEADER_SZ,index_-RPC_HEADER_SZ);
+        string get_content() {
+            return string(buf_+RPC_HEADER_SZ,index_-RPC_HEADER_SZ);
         }
 
         // Return the current content (excluding header) as a string
-        std::string str() {
+        string str() {
             return get_content();
         }
 
@@ -132,9 +128,9 @@ marshall& operator<<(marshall &, int8_t);
 marshall& operator<<(marshall &, uint16_t);
 marshall& operator<<(marshall &, int16_t);
 marshall& operator<<(marshall &, uint64_t);
-marshall& operator<<(marshall &, const std::string &);
+marshall& operator<<(marshall &, const string &);
 
-template <class A> marshall &
+template <class A> typename enable_if<is_iterable<A>::value, marshall>::type &
 operator<<(marshall &m, const A &x) {
     m << (unsigned int) x.size();
     for (const auto &a : x)
@@ -143,10 +139,18 @@ operator<<(marshall &m, const A &x) {
 }
 
 template <class A, class B> marshall &
-operator<<(marshall &m, const std::pair<A,B> &d) {
-    m << d.first;
-    m << d.second;
-    return m;
+operator<<(marshall &m, const pair<A,B> &d) {
+    return m << d.first << d.second;
+}
+
+template<typename E>
+using enum_type_t = typename enable_if<is_enum<E>::value, typename underlying_type<E>::type>::type;
+template<typename E> constexpr inline enum_type_t<E> from_enum(E e) noexcept { return (enum_type_t<E>)e; }
+template<typename E> constexpr inline E to_enum(enum_type_t<E> value) noexcept { return (E)value; }
+
+template <class E> typename enable_if<is_enum<E>::value, marshall>::type &
+operator<<(marshall &m, E e) {
+    return m << from_enum(e);
 }
 
 class unmarshall;
@@ -161,7 +165,9 @@ unmarshall& operator>>(unmarshall &, int32_t &);
 unmarshall& operator>>(unmarshall &, size_t &);
 unmarshall& operator>>(unmarshall &, uint64_t &);
 unmarshall& operator>>(unmarshall &, int64_t &);
-unmarshall& operator>>(unmarshall &, std::string &);
+unmarshall& operator>>(unmarshall &, string &);
+template <class E> typename enable_if<is_enum<E>::value, unmarshall>::type &
+operator>>(unmarshall &u, E &e);
 
 class unmarshall {
     private:
@@ -174,7 +180,7 @@ class unmarshall {
     public:
         unmarshall(): buf_(NULL),sz_(0),index_(0),ok_(false) {}
         unmarshall(char *b, size_t sz): buf_(b),sz_(sz),index_(),ok_(true) {}
-        unmarshall(const std::string &s) : buf_(NULL),sz_(0),index_(0),ok_(false)
+        unmarshall(const string &s) : buf_(NULL),sz_(0),index_(0),ok_(false)
         {
             //take the content which does not exclude a RPC header from a string
             take_content(s);
@@ -187,7 +193,7 @@ class unmarshall {
         void take_in(unmarshall &another);
 
         //take the content which does not exclude a RPC header from a string
-        void take_content(const std::string &s) {
+        void take_content(const string &s) {
             sz_ = s.size()+RPC_HEADER_SZ;
             buf_ = (char *)realloc(buf_,sz_);
             VERIFY(buf_);
@@ -201,7 +207,7 @@ class unmarshall {
         bool okdone() const { return ok_ && index_ == sz_; }
 
         uint8_t rawbyte();
-        void rawbytes(std::string &s, size_t n);
+        void rawbytes(string &s, size_t n);
         template <class T> void rawbytes(T &t);
 
         size_t ind() { return index_;}
@@ -235,7 +241,8 @@ class unmarshall {
         }
 };
 
-template <class A> unmarshall & operator>>(unmarshall &u, A &x) {
+template <class A> typename enable_if<is_iterable<A>::value, unmarshall>::type &
+operator>>(unmarshall &u, A &x) {
     unsigned n = u.grab<unsigned>();
     x.clear();
     while (n--)
@@ -244,20 +251,26 @@ template <class A> unmarshall & operator>>(unmarshall &u, A &x) {
 }
 
 template <class A, class B> unmarshall &
-operator>>(unmarshall &u, std::map<A,B> &x) {
+operator>>(unmarshall &u, map<A,B> &x) {
     unsigned n = u.grab<unsigned>();
     x.clear();
     while (n--)
-        x.emplace(u.grab<std::pair<A,B>>());
+        x.emplace(u.grab<pair<A,B>>());
     return u;
 }
 
 template <class A, class B> unmarshall &
-operator>>(unmarshall &u, std::pair<A,B> &d) {
+operator>>(unmarshall &u, pair<A,B> &d) {
     return u >> d.first >> d.second;
 }
 
-typedef std::function<int(unmarshall &, marshall &)> handler;
+template <class E> typename enable_if<is_enum<E>::value, unmarshall>::type &
+operator>>(unmarshall &u, E &e) {
+    e = to_enum<E>(u.grab<enum_type_t<E>>());
+    return u;
+}
+
+typedef function<int(unmarshall &, marshall &)> handler;
 
 //
 // Automatic marshalling wrappers for RPC handlers
@@ -267,7 +280,7 @@ typedef std::function<int(unmarshall &, marshall &)> handler;
 // C++11 does neither of these two things for us:
 // 1) Declare variables using a parameter pack expansion, like so
 //      Args ...args;
-// 2) Call a function with a std::tuple of the arguments it expects
+// 2) Call a function with a tuple of the arguments it expects
 //
 // We implement an 'invoke' function for functions of the RPC handler
 // signature, i.e. int(R & r, const Args...)
@@ -311,18 +324,18 @@ struct VerifyOnFailure {
 
 // One for function pointers...
 
-template <class F, class R, class args_type, size_t ...Indices>
-typename std::enable_if<!std::is_member_function_pointer<F>::value, int>::type
-invoke(F f, void *, R & r, args_type & t, tuple_indices<Indices...>) {
-    return f(r, std::move(std::get<Indices>(t))...);
+template <class F, class R, class RV, class args_type, size_t ...Indices>
+typename enable_if<!is_member_function_pointer<F>::value, RV>::type
+invoke(RV, F f, void *, R & r, args_type & t, tuple_indices<Indices...>) {
+    return f(r, move(get<Indices>(t))...);
 }
 
 // And one for pointers to member functions...
 
-template <class F, class C, class R, class args_type, size_t ...Indices>
-typename std::enable_if<std::is_member_function_pointer<F>::value, int>::type
-invoke(F f, C *c, R & r, args_type & t, tuple_indices<Indices...>) {
-    return (c->*f)(r, std::move(std::get<Indices>(t))...);
+template <class F, class C, class RV, class R, class args_type, size_t ...Indices>
+typename enable_if<is_member_function_pointer<F>::value, RV>::type
+invoke(RV, F f, C *c, R & r, args_type & t, tuple_indices<Indices...>) {
+    return (c->*f)(r, move(get<Indices>(t))...);
 }
 
 // The class marshalled_func_imp uses partial template specialization to
@@ -339,32 +352,32 @@ template <class Functor, class Instance, class Signature,
 // the same pattern as Signature; this allows us to ignore the distinctions
 // between various types of callable objects at this level of abstraction.
 
-template <class F, class C, class ErrorHandler, class R, class... Args>
-struct marshalled_func_imp<F, C, int(R&, Args...), ErrorHandler> {
+template <class F, class C, class ErrorHandler, class R, class RV, class... Args>
+struct marshalled_func_imp<F, C, RV(R&, Args...), ErrorHandler> {
     static inline handler *wrap(F f, C *c=nullptr) {
         // This type definition corresponds to an empty struct with
         // template parameters running from 0 up to (# args) - 1.
         using Indices = typename make_tuple_indices<sizeof...(Args)>::type;
         // This type definition represents storage for f's unmarshalled
-        // arguments.  std::decay is (most notably) stripping off const
+        // arguments.  decay is (most notably) stripping off const
         // qualifiers.
-        using ArgsStorage = std::tuple<typename std::decay<Args>::type...>;
-        // Allocate a handler (i.e. std::function) to hold the lambda
+        using ArgsStorage = tuple<typename decay<Args>::type...>;
+        // Allocate a handler (i.e. function) to hold the lambda
         // which will unmarshall RPCs and call f.
-        return new handler([=](unmarshall &u, marshall &m) -> int {
+        return new handler([=](unmarshall &u, marshall &m) -> RV {
             // Unmarshall each argument with the correct type and store the
             // result in a tuple.
-            ArgsStorage t = {u.grab<typename std::decay<Args>::type>()...};
+            ArgsStorage t = {u.grab<typename decay<Args>::type>()...};
             // Verify successful unmarshalling of the entire input stream.
             if (!u.okdone())
-                return ErrorHandler::unmarshall_args_failure();
+                return (RV)ErrorHandler::unmarshall_args_failure();
             // Allocate space for the RPC response -- will be passed into the
             // function as an lvalue reference.
             R r;
             // Perform the invocation.  Note that Indices() calls the default
             // constructor of the empty struct with the special template
             // parameters.
-            int b = invoke(f, c, r, t, Indices());
+            RV b = invoke(RV(), f, c, r, t, Indices());
             // Marshall the response.
             m << r;
             // Make like a tree.
@@ -381,16 +394,45 @@ struct marshalled_func_imp<F, C, int(R&, Args...), ErrorHandler> {
 template <class Functor, class ErrorHandler=VerifyOnFailure,
     class Signature=Functor> struct marshalled_func;
 
-template <class F, class ErrorHandler, class... Args>
-struct marshalled_func<F, ErrorHandler, int(*)(Args...)> :
-    public marshalled_func_imp<F, void, int(Args...), ErrorHandler> {};
+template <class F, class ErrorHandler, class RV, class... Args>
+struct marshalled_func<F, ErrorHandler, RV(*)(Args...)> :
+    public marshalled_func_imp<F, void, RV(Args...), ErrorHandler> {};
 
-template <class F, class ErrorHandler, class C, class... Args>
-struct marshalled_func<F, ErrorHandler, int(C::*)(Args...)> :
-    public marshalled_func_imp<F, C, int(Args...), ErrorHandler> {};
+template <class F, class ErrorHandler, class RV, class C, class... Args>
+struct marshalled_func<F, ErrorHandler, RV(C::*)(Args...)> :
+    public marshalled_func_imp<F, C, RV(Args...), ErrorHandler> {};
 
 template <class F, class ErrorHandler, class Signature>
-struct marshalled_func<F, ErrorHandler, std::function<Signature>> :
+struct marshalled_func<F, ErrorHandler, function<Signature>> :
     public marshalled_func_imp<F, void, Signature, ErrorHandler> {};
 
+template <class ...Args, size_t ...Indices> unmarshall &
+tuple_unmarshall_imp(unmarshall & u, tuple<Args &...> t, tuple_indices<Indices...>) {
+    (void)pass{(u >> get<Indices>(t))...};
+    return u;
+}
+
+template <class... Args> unmarshall &
+operator>>(unmarshall & u, tuple<Args &...> && t) {
+    using Indices = typename make_tuple_indices<sizeof...(Args)>::type;
+    return tuple_unmarshall_imp(u, t, Indices());
+}
+
+template <class ...Args, size_t ...Indices> marshall &
+tuple_marshall_imp(marshall & m, tuple<Args...> & t, tuple_indices<Indices...>) {
+    (void)pass{(m << get<Indices>(t))...};
+    return m;
+}
+
+template <class... Args> marshall &
+operator<<(marshall & m, tuple<Args...> && t) {
+    using Indices = typename make_tuple_indices<sizeof...(Args)>::type;
+    return tuple_marshall_imp(m, t, Indices());
+}
+
+// for structs or classes containing a MEMBERS declaration
+#define MARSHALLABLE(_c_) \
+inline unmarshall & operator>>(unmarshall &u, _c_ &a) { return u >> a._tuple_(); } \
+inline marshall & operator<<(marshall &m, _c_ a) { return m << a._tuple_(); }
+
 #endif