string.hpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. #include "msgpack/versioning.hpp"
  13. #include "msgpack/adaptor/adaptor_base.hpp"
  14. #include "msgpack/object.hpp"
  15. #include "msgpack/adaptor/check_container_size.hpp"
  16. #include <string>
  17. #include <cstring>
  18. namespace msgpack {
  19. /// @cond
  20. MSGPACK_API_VERSION_NAMESPACE(v1) {
  21. /// @endcond
  22. namespace adaptor {
  23. template <>
  24. struct convert<std::string> {
  25. msgpack::object const& operator()(msgpack::object const& o, std::string& v) const {
  26. switch (o.type) {
  27. case msgpack::type::BIN:
  28. v.assign(o.via.bin.ptr, o.via.bin.size);
  29. break;
  30. case msgpack::type::STR:
  31. v.assign(o.via.str.ptr, o.via.str.size);
  32. break;
  33. default:
  34. throw msgpack::type_error();
  35. break;
  36. }
  37. return o;
  38. }
  39. };
  40. template <>
  41. struct pack<std::string> {
  42. template <typename Stream>
  43. msgpack::packer<Stream>& operator()(msgpack::packer<Stream>& o, const std::string& v) const {
  44. uint32_t size = checked_get_container_size(v.size());
  45. o.pack_str(size);
  46. o.pack_str_body(v.data(), size);
  47. return o;
  48. }
  49. };
  50. template <>
  51. struct object<std::string> {
  52. void operator()(msgpack::object& o, const std::string& v) const {
  53. uint32_t size = checked_get_container_size(v.size());
  54. o.type = msgpack::type::STR;
  55. o.via.str.ptr = v.data();
  56. o.via.str.size = size;
  57. }
  58. };
  59. template <>
  60. struct object_with_zone<std::string> {
  61. void operator()(msgpack::object::with_zone& o, const std::string& v) const {
  62. uint32_t size = checked_get_container_size(v.size());
  63. o.type = msgpack::type::STR;
  64. char* ptr = static_cast<char*>(o.zone.allocate_align(size, MSGPACK_ZONE_ALIGNOF(char)));
  65. o.via.str.ptr = ptr;
  66. o.via.str.size = size;
  67. std::memcpy(ptr, v.data(), v.size());
  68. }
  69. };
  70. } // namespace adaptor
  71. /// @cond
  72. } // MSGPACK_API_VERSION_NAMESPACE(v1)
  73. /// @endcond
  74. } // namespace msgpack
  75. #endif // MSGPACK_V1_TYPE_STRING_HPP