tarantool / tntcxx

Tarantool C++ connector
Other
8 stars 6 forks source link

mpp: introduce object encoding/decoding #63

Closed alyapunov closed 1 year ago

alyapunov commented 1 year ago

Now it became possible to pass an object of any class to mpp::encode and mpp::decode if a co/dec rule is supplied.

There are two ways to specify a rule for a particular class:

In any case the value of the encoding rule must be a constexpr expression that could contain any values, including standard aggregates like std::tuple and pointers to members of the class that must be encoded/decoded.

Note that one can specify one rule for encoding/decoding as well as different rules for encoding and decoding.

Examples:

struct IntegerWrapper {
    int i;
    static constexpr auto mpp = &IntegerWrapper::i;
};

An object of such a class will be encoded/decoded as one integer (MP_INT) value.

struct Triplet {
    int a;
    double b;
    std::string c;
};

template <>
struct mpp_rule<Triplet> {
    static constexpr auto value = std::make_tuple(&Triplet::a,
                              &Triplet::b,
                              &Triplet::c);
};

An object of this class will be encoded/decoded as array (MP_ARR) of three values - a, b, c - with the corresponding types.

struct Error {
    int code = 0;
    std::string descr;

    static constexpr auto mpp = std::make_tuple(
        std::make_pair(0, &Error::code),
        std::make_pair(1, &Error::descr));
};

This error will be encoded/decoded as map (MP_MAP) with integer keys (0, 1) and corresponding values (code, descr).