From ea97ff8e76eca3c8410f9933ca6f6d522ac080ed Mon Sep 17 00:00:00 2001 From: Takatoshi Kondo Date: Tue, 10 Apr 2018 08:16:20 +0900 Subject: [PATCH] Updated v2_0_cpp_tutorial (markdown) --- v2_0_cpp_tutorial.md | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/v2_0_cpp_tutorial.md b/v2_0_cpp_tutorial.md index 1b69b9f..9e27487 100644 --- a/v2_0_cpp_tutorial.md +++ b/v2_0_cpp_tutorial.md @@ -29,3 +29,46 @@ https://wandbox.org/permlink/9g8uhDsVHAW1rpwV Because some environment often has installed older-version of the `msgpack-c` in `/usr/include`. It is very confusing. So I recommend the version of `msgpack-c` that actually you include. +## Packing + +### Single value + +Let's pack the small string "compact". Pack means encoding C++ types to MessagePack format data. +Here is an example: + +```cpp +#include +#include + +#include + +// hex_dump is not a part of msgpack-c. +inline std::ostream& hex_dump(std::ostream& o, std::string const& v) { + std::ios::fmtflags f(o.flags()); + o << std::hex; + for (auto c : v) { + o << "0x" << std::setw(2) << std::setfill('0') << (static_cast(c) & 0xff) << ' '; + } + o.flags(f); + return o; +} + +int main() { + std::stringstream ss; + msgpack::pack(ss, "compact"); + hex_dump(std::cout, ss.str()) << std::endl; +} +``` + +https://wandbox.org/permlink/c6oFGZWtYiGNF8f6 + +You get the following output: + +``` +0xa7 0x63 0x6f 0x6d 0x70 0x61 0x63 0x74 +``` + +`A7` means 7 bytes string. And the body of the string continues. +See https://msgpack.org/ + +This is a string example. Other types are mapped as documented [here](v2_0_cpp_adaptor).