msgpack / msgpack-c

MessagePack implementation for C and C++ / msgpack.org[C/C++]
Other
3.03k stars 883 forks source link

JSON-like API? #1104

Closed DUOLabs333 closed 9 months ago

DUOLabs333 commented 9 months ago

Given that one of MessagePack's claims is "JSON, but faster", it's surprising I couldn't find a way to mimic JSON (ie, heterogeneous maps and arrays, like with Boost.JSON). I found boost::type::variant, but it's not clear whether it can be serialized, or is an internal type.

As a follow-up, let's say a variant was created from the number 5. Will both is_uint64_t and is_int64_t work, or just one?

redboltz commented 9 months ago

It is from https://msgpack.org/index.html , MessagePack data format characteristic. As you know, C++ is a strongly typed language. So if you want to use MessagePack type compositely, you need to use msgpack::type::variant.

Here is a document. https://github.com/msgpack/msgpack-c/wiki/v2_0_cpp_variant It is a wiki page. The page itself exists but there was no link from index. Sorry about that.

The element of msgpack::type::variant is decided by MessagePack format, not by commonly used C++ types. Because MessagePack format doesn't have a way to preserve the programming language type information.

As a follow-up, let's say a variant was created from the number 5. Will both is_uint64_t and is_int64_t work, or just one?

So it is mapped to MessagePack's uint_* format. See https://github.com/msgpack/msgpack/blob/master/spec.md#int-format-family. When you unpack 0xcc 0x05 MessagePack data, msgpack::object is created and its type is POSITIVE_INTEGER. Corresponding msgpack::type::variant type is uint64_t. So is_uint64_t() returns true but is_int64_t() returns false. If you have expected C++ type, you can use convert() or as<T>() function with msgpack::object.

See also https://github.com/msgpack/msgpack-c/wiki/v2_0_cpp_adaptor https://github.com/msgpack/msgpack-c/wiki/v2_0_cpp_object