json_serializer.hpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. // Copyright (c) 2018-2020 Jsonxx - Nomango
  2. //
  3. // Permission is hereby granted, free of charge, to any person obtaining a copy
  4. // of this software and associated documentation files (the "Software"), to deal
  5. // in the Software without restriction, including without limitation the rights
  6. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. // copies of the Software, and to permit persons to whom the Software is
  8. // furnished to do so, subject to the following conditions:
  9. //
  10. // The above copyright notice and this permission notice shall be included in
  11. // all copies or substantial portions of the Software.
  12. //
  13. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. // THE SOFTWARE.
  20. #pragma once
  21. #include <cstdio> // snprintf_s
  22. #include <type_traits>
  23. #include <ios>
  24. #include <random>
  25. #include "json_value.hpp"
  26. namespace jsonxx {
  27. //
  28. // output_adapter
  29. //
  30. template<typename _CharTy>
  31. struct output_adapter {
  32. using char_type = _CharTy;
  33. using char_traits = std::char_traits<char_type>;
  34. virtual void write(const _CharTy ch) = 0;
  35. virtual void write(const _CharTy *str, std::size_t size) = 0;
  36. virtual void write(const _CharTy *str) {
  37. const auto size = char_traits::length(str);
  38. write(str, static_cast<std::size_t>(size));
  39. }
  40. };
  41. template<typename _StringTy>
  42. struct string_output_adapter
  43. : public output_adapter<typename _StringTy::value_type> {
  44. using char_type = typename _StringTy::value_type;
  45. using size_type = typename _StringTy::size_type;
  46. using char_traits = std::char_traits<char_type>;
  47. string_output_adapter(_StringTy &str) : str_(str) {}
  48. virtual void write(const char_type ch) override {
  49. str_.push_back(ch);
  50. }
  51. virtual void write(const char_type *str, std::size_t size) override {
  52. str_.append(str, static_cast<size_type>(size));
  53. }
  54. private:
  55. _StringTy &str_;
  56. };
  57. template<typename _CharTy>
  58. struct stream_output_adapter
  59. : public output_adapter<_CharTy> {
  60. using char_type = _CharTy;
  61. using size_type = typename std::streamsize;
  62. using char_traits = std::char_traits<char_type>;
  63. stream_output_adapter(std::basic_ostream<char_type> &stream) : stream_(stream) {}
  64. virtual void write(const char_type ch) override {
  65. stream_.put(ch);
  66. }
  67. virtual void write(const char_type *str, std::size_t size) override {
  68. stream_.write(str, static_cast<size_type>(size));
  69. }
  70. private:
  71. std::basic_ostream<char_type> &stream_;
  72. };
  73. //
  74. // json_serializer
  75. //
  76. template<typename _BasicJsonTy>
  77. struct json_serializer {
  78. using string_type = typename _BasicJsonTy::string_type;
  79. using char_type = typename _BasicJsonTy::char_type;
  80. using integer_type = typename _BasicJsonTy::integer_type;
  81. using float_type = typename _BasicJsonTy::float_type;
  82. using boolean_type = typename _BasicJsonTy::boolean_type;
  83. using array_type = typename _BasicJsonTy::array_type;
  84. using object_type = typename _BasicJsonTy::object_type;
  85. json_serializer(output_adapter<char_type> *out, const char_type indent_char)
  86. : out(out), indent_char(indent_char), indent_string(32, indent_char) {
  87. }
  88. void dump(
  89. const _BasicJsonTy &json,
  90. const bool pretty_print,
  91. const unsigned int indent_step,
  92. const unsigned int current_indent = 0) {
  93. switch (json.type()) {
  94. case json_type::object: {
  95. auto &object = *json.value_.data.object;
  96. if (object.empty()) {
  97. out->write("{}");
  98. return;
  99. }
  100. if (pretty_print) {
  101. out->write("{\n");
  102. const auto new_indent = current_indent + indent_step;
  103. if (indent_string.size() < new_indent) {
  104. indent_string.resize(indent_string.size() * 2, indent_char);
  105. }
  106. auto iter = object.cbegin();
  107. const auto size = object.size();
  108. for (std::size_t i = 0; i < size; ++i, ++iter) {
  109. out->write(indent_string.c_str(), new_indent);
  110. out->write('\"');
  111. out->write(iter->first.c_str());
  112. out->write("\": ");
  113. dump(iter->second, true, indent_step, new_indent);
  114. // not last element
  115. if (i != size - 1)
  116. out->write(",\n");
  117. }
  118. out->write('\n');
  119. out->write(indent_string.c_str(), current_indent);
  120. out->write('}');
  121. } else {
  122. out->write('{');
  123. auto iter = object.cbegin();
  124. const auto size = object.size();
  125. for (std::size_t i = 0; i < size; ++i, ++iter) {
  126. out->write('\"');
  127. out->write(iter->first.c_str());
  128. out->write("\":");
  129. dump(iter->second, false, indent_step, current_indent);
  130. // not last element
  131. if (i != size - 1)
  132. out->write(',');
  133. }
  134. out->write('}');
  135. }
  136. return;
  137. }
  138. case json_type::array: {
  139. auto &vector = *json.value_.data.vector;
  140. if (vector.empty()) {
  141. out->write("[]");
  142. return;
  143. }
  144. if (pretty_print) {
  145. out->write("[\n");
  146. const auto new_indent = current_indent + indent_step;
  147. if (indent_string.size() < new_indent) {
  148. indent_string.resize(indent_string.size() * 2, indent_char);
  149. }
  150. auto iter = vector.cbegin();
  151. const auto size = vector.size();
  152. for (std::size_t i = 0; i < size; ++i, ++iter) {
  153. out->write(indent_string.c_str(), new_indent);
  154. dump(*iter, true, indent_step, new_indent);
  155. // not last element
  156. if (i != size - 1)
  157. out->write(",\n");
  158. }
  159. out->write('\n');
  160. out->write(indent_string.c_str(), current_indent);
  161. out->write(']');
  162. } else {
  163. out->write('[');
  164. auto iter = vector.cbegin();
  165. const auto size = vector.size();
  166. for (std::size_t i = 0; i < size; ++i, ++iter) {
  167. dump(*iter, false, indent_step, current_indent);
  168. // not last element
  169. if (i != size - 1)
  170. out->write(',');
  171. }
  172. out->write(']');
  173. }
  174. return;
  175. }
  176. case json_type::string: {
  177. out->write('\"');
  178. dump_string(*json.value_.data.string);
  179. out->write('\"');
  180. return;
  181. }
  182. case json_type::boolean: {
  183. if (json.value_.data.boolean) {
  184. out->write("true");
  185. } else {
  186. out->write("false");
  187. }
  188. return;
  189. }
  190. case json_type::number_integer: {
  191. dump_integer(json.value_.data.number_integer);
  192. return;
  193. }
  194. case json_type::number_float: {
  195. dump_float(json.value_.data.number_float);
  196. return;
  197. }
  198. case json_type::null: {
  199. out->write("null");
  200. return;
  201. }
  202. }
  203. }
  204. void dump_integer(integer_type val) {
  205. if (val == 0) {
  206. out->write('0');
  207. return;
  208. }
  209. auto uval = static_cast<typename std::make_unsigned<integer_type>::type>(val);
  210. if (val < 0)
  211. uval = 0 - uval;
  212. auto next = number_buffer.rbegin();
  213. *next = '\0';
  214. do {
  215. *(++next) = static_cast<char_type>('0' + uval % 10);
  216. uval /= 10;
  217. } while (uval != 0);
  218. if (val < 0)
  219. *(++next) = '-';
  220. out->write(&(*next));
  221. }
  222. void dump_float(float_type val) {
  223. const auto digits = std::numeric_limits<float_type>::max_digits10;
  224. const auto len = ::std::snprintf(nullptr, 0, "%.*g", digits, val);
  225. if (len) {
  226. number_buffer[0] = '\0';
  227. std::snprintf(&number_buffer[0], len + 1, "%.*g", digits, val);
  228. } else {
  229. number_buffer[0] = '0';
  230. number_buffer[1] = '.';
  231. number_buffer[2] = '0';
  232. number_buffer[3] = '\0';
  233. }
  234. out->write(number_buffer.data());
  235. }
  236. void dump_string(const string_type &val) {
  237. for (const auto &ch : val) {
  238. switch (ch) {
  239. case '\t': {
  240. out->write("\\t");
  241. break;
  242. }
  243. case '\r': {
  244. out->write("\\r");
  245. break;
  246. }
  247. case '\n': {
  248. out->write("\\n");
  249. break;
  250. }
  251. case '\b': {
  252. out->write("\\b");
  253. break;
  254. }
  255. case '\f': {
  256. out->write("\\f");
  257. break;
  258. }
  259. case '\"': {
  260. out->write("\\\"");
  261. break;
  262. }
  263. case '\\': {
  264. out->write("\\\\");
  265. break;
  266. }
  267. default: {
  268. const auto char_byte = static_cast<uint16_t>(ch);
  269. if ((char_byte > 0x1F) && (char_byte < 0x7F)) {
  270. out->write(ch);
  271. } else {
  272. char_type escaped[7] = {0};
  273. std::snprintf(escaped, 7, "\\u%04x", char_byte);
  274. out->write(escaped);
  275. }
  276. break;
  277. }
  278. }
  279. }
  280. }
  281. private:
  282. output_adapter<char_type> *out;
  283. char_type indent_char;
  284. string_type indent_string;
  285. std::array<char_type, 21> number_buffer;
  286. };
  287. } // namespace Jsonxx