string.hpp 2.2 KB

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