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 <sstream>
12#include <iostream>
13#include <algorithm>
14#include <cctype>
15
16#include <msgpack.hpp>
17
18struct user {
19    std::string name;
20    int age;
21    std::string address;
22    MSGPACK_DEFINE(name, age, address);
23};
24
25struct proc:boost::static_visitor<void> {
26    void operator()(std::string& v) const {
27        std::cout << "  match std::string& v" << std::endl;
28        std::cout << "    v: " << v << std::endl;
29        std::cout << "    capitalize" << std::endl;
30        for (std::string::iterator it = v.begin(), end = v.end();
31             it != end;
32             ++it) {
33            *it = std::toupper(*it);
34        }
35    }
36    void operator()(std::vector<msgpack::type::variant>& v) const {
37        std::cout << "match vector (msgpack::type::ARRAY)" << std::endl;
38        std::vector<msgpack::type::variant>::iterator it = v.begin();
39        std::vector<msgpack::type::variant>::const_iterator end = v.end();
40        for (; it != end; ++it) {
41            boost::apply_visitor(*this, *it);
42        }
43    }
44    template <typename T>
45    void operator()(T const&) const {
46        std::cout << "  match others" << std::endl;
47    }
48};
49
50void print(std::string const& buf) {
51    for (std::string::const_iterator it = buf.begin(), end = buf.end();
52         it != end;
53         ++it) {
54        std::cout
55            << std::setw(2)
56            << std::hex
57            << std::setfill('0')
58            << (static_cast<int>(*it) & 0xff)
59            << ' ';
60    }
61    std::cout << std::dec << std::endl;
62}
63
64
65int main() {
66    std::stringstream ss1;
67    user u;
68    u.name = "Takatoshi Kondo";
69    u.age = 42;
70    u.address = "Tokyo, JAPAN";
71
72    std::cout << "Packing object." << std::endl;
73    msgpack::pack(ss1, u);
74    print(ss1.str());
75
76    msgpack::unpacked unp1 = msgpack::unpack(ss1.str().data(), ss1.str().size());
77    msgpack::object const& obj1 = unp1.get();
78    std::cout << "Unpacked msgpack object." << std::endl;
79    std::cout << obj1 << std::endl;
80
81    msgpack::type::variant v = obj1.as<msgpack::type::variant>();
82    std::cout << "Applying proc..." << std::endl;
83    boost::apply_visitor(proc(), v);
84
85    std::stringstream ss2;
86    std::cout << "Packing modified object." << std::endl;
87    msgpack::pack(ss2, v);
88    print(ss2.str());
89
90    msgpack::unpacked unp2 = msgpack::unpack(ss2.str().data(), ss2.str().size());
91    msgpack::object const& obj2 = unp2.get();
92    std::cout << "Modified msgpack object." << std::endl;
93    std::cout << obj2 << std::endl;
94}
95