1 // MessagePack for C++ example
2 //
3 // Copyright (C) 2015 KONDO Takatoshi
4 //
5 // Distributed under the Boost Software License, Version 1.0.
6 // (See accompanying file LICENSE_1_0.txt or copy at
7 // http://www.boost.org/LICENSE_1_0.txt)
8 //
9
10 #include <string>
11 #include <iostream>
12 #include <iomanip>
13 #include <sstream>
14 #include <cassert>
15
16 #include <msgpack.hpp>
17
18
19 class my_class {
20 public:
my_class()21 my_class() {} // When you want to convert from msgpack::object to my_class,
22 // my_class should be default constractible.
23 // If you use C++11, you can adapt non-default constructible
24 // classes to msgpack::object.
25 // See https://github.com/msgpack/msgpack-c/wiki/v1_1_cpp_adaptor#non-default-constructible-class-support-c11-only
my_class(std::string const & name,int age)26 my_class(std::string const& name, int age):name_(name), age_(age) {}
27
operator ==(my_class const & lhs,my_class const & rhs)28 friend bool operator==(my_class const& lhs, my_class const& rhs) {
29 return lhs.name_ == rhs.name_ && lhs.age_ == rhs.age_;
30 }
31
32 private:
33 std::string name_;
34 int age_;
35
36 public:
37 MSGPACK_DEFINE_MAP(name_, age_);
38 };
39
print(std::string const & buf)40 void print(std::string const& buf) {
41 for (std::string::const_iterator it = buf.begin(), end = buf.end();
42 it != end;
43 ++it) {
44 std::cout
45 << std::setw(2)
46 << std::hex
47 << std::setfill('0')
48 << (static_cast<int>(*it) & 0xff)
49 << ' ';
50 }
51 std::cout << std::dec << std::endl;
52 }
53
main()54 int main() {
55 { // pack, unpack
56 my_class my("John Smith", 42);
57 std::stringstream ss;
58 msgpack::pack(ss, my);
59
60 print(ss.str());
61
62 msgpack::object_handle oh =
63 msgpack::unpack(ss.str().data(), ss.str().size());
64 msgpack::object obj = oh.get();
65 std::cout << obj << std::endl;
66 assert(obj.as<my_class>() == my);
67 }
68 { // create object with zone
69 my_class my("John Smith", 42);
70 msgpack::zone z;
71 msgpack::object obj(my, z);
72 std::cout << obj << std::endl;
73 assert(obj.as<my_class>() == my);
74 }
75 }
76