1 //
2 // MessagePack for C++ static resolution routine
3 //
4 // Copyright (C) 2008-2015 FURUHASHI Sadayuki
5 //
6 //    Distributed under the Boost Software License, Version 1.0.
7 //    (See accompanying file LICENSE_1_0.txt or copy at
8 //    http://www.boost.org/LICENSE_1_0.txt)
9 //
10 #ifndef MSGPACK_V1_TYPE_STRING_HPP
11 #define MSGPACK_V1_TYPE_STRING_HPP
12 
13 #include "msgpack/versioning.hpp"
14 #include "msgpack/adaptor/adaptor_base.hpp"
15 #include "msgpack/adaptor/check_container_size.hpp"
16 
17 #include <string>
18 #include <cstring>
19 
20 namespace msgpack {
21 
22 /// @cond
MSGPACK_API_VERSION_NAMESPACE(v1)23 MSGPACK_API_VERSION_NAMESPACE(v1) {
24 /// @endcond
25 
26 namespace adaptor {
27 
28 template <>
29 struct convert<std::string> {
30     msgpack::object const& operator()(msgpack::object const& o, std::string& v) const {
31         switch (o.type) {
32         case msgpack::type::BIN:
33             v.assign(o.via.bin.ptr, o.via.bin.size);
34             break;
35         case msgpack::type::STR:
36             v.assign(o.via.str.ptr, o.via.str.size);
37             break;
38         default:
39             throw msgpack::type_error();
40             break;
41         }
42         return o;
43     }
44 };
45 
46 template <>
47 struct pack<std::string> {
48     template <typename Stream>
49     msgpack::packer<Stream>& operator()(msgpack::packer<Stream>& o, const std::string& v) const {
50         uint32_t size = checked_get_container_size(v.size());
51         o.pack_str(size);
52         o.pack_str_body(v.data(), size);
53         return o;
54     }
55 };
56 
57 template <>
58 struct object<std::string> {
59     void operator()(msgpack::object& o, const std::string& v) const {
60         uint32_t size = checked_get_container_size(v.size());
61         o.type = msgpack::type::STR;
62         o.via.str.ptr = v.data();
63         o.via.str.size = size;
64     }
65 };
66 
67 template <>
68 struct object_with_zone<std::string> {
69     void operator()(msgpack::object::with_zone& o, const std::string& v) const {
70         uint32_t size = checked_get_container_size(v.size());
71         o.type = msgpack::type::STR;
72         char* ptr = static_cast<char*>(o.zone.allocate_align(size, MSGPACK_ZONE_ALIGNOF(char)));
73         o.via.str.ptr = ptr;
74         o.via.str.size = size;
75         std::memcpy(ptr, v.data(), v.size());
76     }
77 };
78 
79 } // namespace adaptor
80 
81 /// @cond
82 }  // MSGPACK_API_VERSION_NAMESPACE(v1)
83 /// @endcond
84 
85 }  // namespace msgpack
86 
87 #endif // MSGPACK_V1_TYPE_STRING_HPP
88