c++ - what does msgpack's object_with_zone do? -
when writing custom serializer msgpack_c 1 needs implement object_with_zone.
the documentation how implement sparse ( https://github.com/msgpack/msgpack-c/wiki/v2_0_cpp_adaptor ).
in circumstances method called?
you can create msgpack::object c++ types. see https://github.com/msgpack/msgpack-c/wiki/v2_0_cpp_object#conversion
when call msgpack::object constructor zone msgpack::object(mc, z);, object_with_zone<t>::operator() called internally.
if don't want create msgpack::object c++ types, don't need define object_with_zone specialization. packing, unpacking, , converting c++ types msgpack::object don't require it.
here example:
#include <iostream> #include <msgpack.hpp> class my_class { public: my_class(std::string const& name, int age):name_(name), age_(age) {} std::string const& get_name() const { return name_; } int get_age() const { return age_; } private: std::string name_; int age_; }; // user defined class template specialization namespace msgpack { msgpack_api_version_namespace(msgpack_default_api_ns) { namespace adaptor { template <> struct object_with_zone<my_class> { void operator()(msgpack::object::with_zone& o, my_class const& v) const { std::cout << "object_with_zone<my_class> called" << std::endl; o.type = type::array; o.via.array.size = 2; o.via.array.ptr = static_cast<msgpack::object*>( o.zone.allocate_align(sizeof(msgpack::object) * o.via.array.size, msgpack_zone_alignof(msgpack::object))); o.via.array.ptr[0] = msgpack::object(v.get_name(), o.zone); o.via.array.ptr[1] = msgpack::object(v.get_age(), o.zone); } }; } // namespace adaptor } // msgpack_api_version_namespace(msgpack_default_api_ns) } // namespace msgpack int main() { my_class mc("john", 42); msgpack::zone z; auto obj = msgpack::object(mc, z); std::cout << obj << std::endl; } output:
object_with_zone<my_class> called ["john", 42] running demo: https://wandbox.org/permlink/dnmzx1fpul3w8d5m
updated
additional question. why want use zone ?
answer:
a zone used internally when unpack messagepack formatted byte stream. msgpack::object_handle. msgpack::object_handle has zone , msgpack::object. see https://github.com/msgpack/msgpack-c/wiki/v2_0_cpp_object#what-is-msgpackobject.
the reason of using msgpack::zone performance. if msgpack::object str, bin, or ext, msgpack::object need allocate memory dynamically. msgpack::object can have handle of memory inefficient. destructor of msgpack::object need deallocate memory, if msgpack::object allocate memory. msgpack::object composite data structure. means destructor cannot inlined.
one of goal of msgpack-c efficient unpacking. msgpack-c uses msgpack::zone.
it unpacking story. msgpack::zone used when msgpack::object created c++ types. i'm not sure when users want do, is users.
Comments
Post a Comment