You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1495 lines
36 KiB

7 years ago
​
​
​
​
​
​
​
7 years ago
​
​
​
​
​
​
​
​
​
​
7 years ago
​
​
7 years ago
​
​
7 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
7 years ago
​
​
​
7 years ago
​
​
7 years ago
​
7 years ago
7 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
7 years ago
​
​
​
​
​
7 years ago
​
​
​
7 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
7 years ago
​
  1. // Copyright 2011 Baptiste Lepilleur and The JsonCpp Authors
  2. // Distributed under MIT license, or public domain if desired and
  3. // recognized in your jurisdiction.
  4. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
  5. #if ! defined(JSON_IS_AMALGAMATION)
  6. #include "json_tool.h"
  7. #include <json/writer.h>
  8. #endif // if !defined(JSON_IS_AMALGAMATION)
  9. #include <cassert>
  10. #include <cstring>
  11. #include <iomanip>
  12. #include <memory>
  13. #include <set>
  14. #include <sstream>
  15. #include <utility>
  16. #if __cplusplus >= 201103L
  17. #include <cmath>
  18. #include <cstdio>
  19. #if ! defined(isnan)
  20. #define isnan std::isnan
  21. #endif
  22. #if ! defined(isfinite)
  23. #define isfinite std::isfinite
  24. #endif
  25. #else
  26. #include <cmath>
  27. #include <cstdio>
  28. #if defined(_MSC_VER)
  29. #if ! defined(isnan)
  30. #include <float.h>
  31. #define isnan _isnan
  32. #endif
  33. #if ! defined(isfinite)
  34. #include <float.h>
  35. #define isfinite _finite
  36. #endif
  37. #if ! defined(_CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES)
  38. #define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1
  39. #endif //_CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES
  40. #endif //_MSC_VER
  41. #if defined(__sun) && defined(__SVR4) // Solaris
  42. #if ! defined(isfinite)
  43. #include <ieeefp.h>
  44. #define isfinite finite
  45. #endif
  46. #endif
  47. #if defined(__hpux)
  48. #if ! defined(isfinite)
  49. #if defined(__ia64) && ! defined(finite)
  50. #define isfinite(x) ((sizeof(x) == sizeof(float) ? _Isfinitef(x) : _IsFinite(x)))
  51. #endif
  52. #endif
  53. #endif
  54. #if ! defined(isnan)
  55. // IEEE standard states that NaN values will not compare to themselves
  56. #define isnan(x) (x != x)
  57. #endif
  58. #if ! defined(__APPLE__)
  59. #if ! defined(isfinite)
  60. #define isfinite finite
  61. #endif
  62. #endif
  63. #endif
  64. #if defined(_MSC_VER)
  65. // Disable warning about strdup being deprecated.
  66. #pragma warning(disable : 4996)
  67. #endif
  68. namespace Json
  69. {
  70. #if __cplusplus >= 201103L || (defined(_CPPLIB_VER) && _CPPLIB_VER >= 520)
  71. typedef std::unique_ptr<StreamWriter> StreamWriterPtr;
  72. #else
  73. typedef std::auto_ptr<StreamWriter> StreamWriterPtr;
  74. #endif
  75. String valueToString(LargestInt value)
  76. {
  77. UIntToStringBuffer buffer;
  78. char * current = buffer + sizeof(buffer);
  79. if (value == Value::minLargestInt)
  80. {
  81. uintToString(LargestUInt(Value::maxLargestInt) + 1, current);
  82. *--current = '-';
  83. }
  84. else if (value < 0)
  85. {
  86. uintToString(LargestUInt(-value), current);
  87. *--current = '-';
  88. }
  89. else
  90. {
  91. uintToString(LargestUInt(value), current);
  92. }
  93. assert(current >= buffer);
  94. return current;
  95. }
  96. String valueToString(LargestUInt value)
  97. {
  98. UIntToStringBuffer buffer;
  99. char * current = buffer + sizeof(buffer);
  100. uintToString(value, current);
  101. assert(current >= buffer);
  102. return current;
  103. }
  104. #if defined(JSON_HAS_INT64)
  105. String valueToString(Int value)
  106. {
  107. return valueToString(LargestInt(value));
  108. }
  109. String valueToString(UInt value)
  110. {
  111. return valueToString(LargestUInt(value));
  112. }
  113. #endif // # if defined(JSON_HAS_INT64)
  114. namespace
  115. {
  116. String valueToString(double value, bool useSpecialFloats, unsigned int precision, PrecisionType precisionType)
  117. {
  118. // Print into the buffer. We need not request the alternative representation
  119. // that always has a decimal point because JSON doesn't distinguish the
  120. // concepts of reals and integers.
  121. if (! isfinite(value))
  122. {
  123. static const char * const reps[2][3] = {
  124. {"NaN", "-Infinity", "Infinity"},
  125. {"null", "-1e+9999", "1e+9999" }
  126. };
  127. return reps[useSpecialFloats ? 0 : 1][isnan(value) ? 0 : (value < 0) ? 1 : 2];
  128. }
  129. String buffer(size_t(36), '\0');
  130. while (true)
  131. {
  132. int len = jsoncpp_snprintf(&*buffer.begin(), buffer.size(), (precisionType == PrecisionType::significantDigits) ? "%.*g" : "%.*f", precision, value);
  133. assert(len >= 0);
  134. auto wouldPrint = static_cast<size_t>(len);
  135. if (wouldPrint >= buffer.size())
  136. {
  137. buffer.resize(wouldPrint + 1);
  138. continue;
  139. }
  140. buffer.resize(wouldPrint);
  141. break;
  142. }
  143. buffer.erase(fixNumericLocale(buffer.begin(), buffer.end()), buffer.end());
  144. // strip the zero padding from the right
  145. if (precisionType == PrecisionType::decimalPlaces)
  146. {
  147. buffer.erase(fixZerosInTheEnd(buffer.begin(), buffer.end()), buffer.end());
  148. }
  149. // try to ensure we preserve the fact that this was given to us as a double on
  150. // input
  151. if (buffer.find('.') == buffer.npos && buffer.find('e') == buffer.npos)
  152. {
  153. buffer += ".0";
  154. }
  155. return buffer;
  156. }
  157. } // namespace
  158. String valueToString(double value, unsigned int precision, PrecisionType precisionType)
  159. {
  160. return valueToString(value, false, precision, precisionType);
  161. }
  162. String valueToString(bool value)
  163. {
  164. return value ? "true" : "false";
  165. }
  166. static bool isAnyCharRequiredQuoting(const char * s, size_t n)
  167. {
  168. assert(s || ! n);
  169. const char * const end = s + n;
  170. for (const char * cur = s; cur < end; ++cur)
  171. {
  172. if (*cur == '\\' || *cur == '\"' || *cur < ' ' || static_cast<unsigned char>(*cur) < 0x80)
  173. {
  174. return true;
  175. }
  176. }
  177. return false;
  178. }
  179. static unsigned int utf8ToCodepoint(const char *& s, const char * e)
  180. {
  181. const unsigned int REPLACEMENT_CHARACTER = 0xFFFD;
  182. unsigned int firstByte = static_cast<unsigned char>(*s);
  183. if (firstByte < 0x80)
  184. {
  185. return firstByte;
  186. }
  187. if (firstByte < 0xE0)
  188. {
  189. if (e - s < 2)
  190. {
  191. return REPLACEMENT_CHARACTER;
  192. }
  193. unsigned int calculated = ((firstByte & 0x1F) << 6) | (static_cast<unsigned int>(s[1]) & 0x3F);
  194. s += 1;
  195. // oversized encoded characters are invalid
  196. return calculated < 0x80 ? REPLACEMENT_CHARACTER : calculated;
  197. }
  198. if (firstByte < 0xF0)
  199. {
  200. if (e - s < 3)
  201. {
  202. return REPLACEMENT_CHARACTER;
  203. }
  204. unsigned int calculated = ((firstByte & 0x0F) << 12) | ((static_cast<unsigned int>(s[1]) & 0x3F) << 6) | (static_cast<unsigned int>(s[2]) & 0x3F);
  205. s += 2;
  206. // surrogates aren't valid codepoints itself
  207. // shouldn't be UTF-8 encoded
  208. if (calculated >= 0xD800 && calculated <= 0xDFFF)
  209. {
  210. return REPLACEMENT_CHARACTER;
  211. }
  212. // oversized encoded characters are invalid
  213. return calculated < 0x800 ? REPLACEMENT_CHARACTER : calculated;
  214. }
  215. if (firstByte < 0xF8)
  216. {
  217. if (e - s < 4)
  218. {
  219. return REPLACEMENT_CHARACTER;
  220. }
  221. unsigned int calculated = ((firstByte & 0x07) << 18) | ((static_cast<unsigned int>(s[1]) & 0x3F) << 12) | ((static_cast<unsigned int>(s[2]) & 0x3F) << 6) | (static_cast<unsigned int>(s[3]) & 0x3F);
  222. s += 3;
  223. // oversized encoded characters are invalid
  224. return calculated < 0x10000 ? REPLACEMENT_CHARACTER : calculated;
  225. }
  226. return REPLACEMENT_CHARACTER;
  227. }
  228. static const char hex2[] =
  229. "000102030405060708090a0b0c0d0e0f"
  230. "101112131415161718191a1b1c1d1e1f"
  231. "202122232425262728292a2b2c2d2e2f"
  232. "303132333435363738393a3b3c3d3e3f"
  233. "404142434445464748494a4b4c4d4e4f"
  234. "505152535455565758595a5b5c5d5e5f"
  235. "606162636465666768696a6b6c6d6e6f"
  236. "707172737475767778797a7b7c7d7e7f"
  237. "808182838485868788898a8b8c8d8e8f"
  238. "909192939495969798999a9b9c9d9e9f"
  239. "a0a1a2a3a4a5a6a7a8a9aaabacadaeaf"
  240. "b0b1b2b3b4b5b6b7b8b9babbbcbdbebf"
  241. "c0c1c2c3c4c5c6c7c8c9cacbcccdcecf"
  242. "d0d1d2d3d4d5d6d7d8d9dadbdcdddedf"
  243. "e0e1e2e3e4e5e6e7e8e9eaebecedeeef"
  244. "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff";
  245. static String toHex16Bit(unsigned int x)
  246. {
  247. const unsigned int hi = (x >> 8) & 0xff;
  248. const unsigned int lo = x & 0xff;
  249. String result(4, ' ');
  250. result[0] = hex2[2 * hi];
  251. result[1] = hex2[2 * hi + 1];
  252. result[2] = hex2[2 * lo];
  253. result[3] = hex2[2 * lo + 1];
  254. return result;
  255. }
  256. static String valueToQuotedStringN(const char * value, unsigned length)
  257. {
  258. if (value == nullptr)
  259. {
  260. return "";
  261. }
  262. if (! isAnyCharRequiredQuoting(value, length))
  263. {
  264. return String("\"") + value + "\"";
  265. }
  266. // We have to walk value and escape any special characters.
  267. // Appending to String is not efficient, but this should be rare.
  268. // (Note: forward slashes are *not* rare, but I am not escaping them.)
  269. String::size_type maxsize = length * 2 + 3; // allescaped+quotes+NULL
  270. String result;
  271. result.reserve(maxsize); // to avoid lots of mallocs
  272. result += "\"";
  273. const char * end = value + length;
  274. for (const char * c = value; c != end; ++c)
  275. {
  276. switch (*c)
  277. {
  278. case '\"': result += "\\\""; break;
  279. case '\\': result += "\\\\"; break;
  280. case '\b': result += "\\b"; break;
  281. case '\f': result += "\\f"; break;
  282. case '\n': result += "\\n"; break;
  283. case '\r': result += "\\r"; break;
  284. case '\t': result += "\\t"; break;
  285. // case '/':
  286. // Even though \/ is considered a legal escape in JSON, a bare
  287. // slash is also legal, so I see no reason to escape it.
  288. // (I hope I am not misunderstanding something.)
  289. // blep notes: actually escaping \/ may be useful in javascript to avoid </
  290. // sequence.
  291. // Should add a flag to allow this compatibility mode and prevent this
  292. // sequence from occurring.
  293. default:
  294. {
  295. unsigned int cp = utf8ToCodepoint(c, end);
  296. // don't escape non-control characters
  297. // (short escape sequence are applied above)
  298. if (cp < 0x80 && cp >= 0x20)
  299. {
  300. result += static_cast<char>(cp);
  301. }
  302. else if (cp < 0x10000)
  303. { // codepoint is in Basic Multilingual Plane
  304. result += "\\u";
  305. result += toHex16Bit(cp);
  306. }
  307. else
  308. { // codepoint is not in Basic Multilingual Plane
  309. // convert to surrogate pair first
  310. cp -= 0x10000;
  311. result += "\\u";
  312. result += toHex16Bit((cp >> 10) + 0xD800);
  313. result += "\\u";
  314. result += toHex16Bit((cp & 0x3FF) + 0xDC00);
  315. }
  316. }
  317. break;
  318. }
  319. }
  320. result += "\"";
  321. return result;
  322. }
  323. String valueToQuotedString(const char * value)
  324. {
  325. return valueToQuotedStringN(value, static_cast<unsigned int>(strlen(value)));
  326. }
  327. // Class Writer
  328. // //////////////////////////////////////////////////////////////////
  329. Writer::~Writer() = default;
  330. // Class FastWriter
  331. // //////////////////////////////////////////////////////////////////
  332. FastWriter::FastWriter() = default;
  333. void FastWriter::enableYAMLCompatibility()
  334. {
  335. yamlCompatibilityEnabled_ = true;
  336. }
  337. void FastWriter::dropNullPlaceholders()
  338. {
  339. dropNullPlaceholders_ = true;
  340. }
  341. void FastWriter::omitEndingLineFeed()
  342. {
  343. omitEndingLineFeed_ = true;
  344. }
  345. String FastWriter::write(const Value & root)
  346. {
  347. document_.clear();
  348. writeValue(root);
  349. if (! omitEndingLineFeed_)
  350. {
  351. document_ += '\n';
  352. }
  353. return document_;
  354. }
  355. void FastWriter::writeValue(const Value & value)
  356. {
  357. switch (value.type())
  358. {
  359. case nullValue:
  360. if (! dropNullPlaceholders_)
  361. {
  362. document_ += "null";
  363. }
  364. break;
  365. case intValue : document_ += valueToString(value.asLargestInt()); break;
  366. case uintValue: document_ += valueToString(value.asLargestUInt()); break;
  367. case realValue: document_ += valueToString(value.asDouble()); break;
  368. case stringValue:
  369. {
  370. // Is NULL possible for value.string_? No.
  371. const char * str;
  372. const char * end;
  373. bool ok = value.getString(&str, &end);
  374. if (ok)
  375. {
  376. document_ += valueToQuotedStringN(str, static_cast<unsigned>(end - str));
  377. }
  378. break;
  379. }
  380. case booleanValue: document_ += valueToString(value.asBool()); break;
  381. case arrayValue:
  382. {
  383. document_ += '[';
  384. ArrayIndex size = value.size();
  385. for (ArrayIndex index = 0; index < size; ++index)
  386. {
  387. if (index > 0)
  388. {
  389. document_ += ',';
  390. }
  391. writeValue(value[index]);
  392. }
  393. document_ += ']';
  394. }
  395. break;
  396. case objectValue:
  397. {
  398. Value::Members members(value.getMemberNames());
  399. document_ += '{';
  400. for (auto it = members.begin(); it != members.end(); ++it)
  401. {
  402. const String & name = *it;
  403. if (it != members.begin())
  404. {
  405. document_ += ',';
  406. }
  407. document_ += valueToQuotedStringN(name.data(), static_cast<unsigned>(name.length()));
  408. document_ += yamlCompatibilityEnabled_ ? ": " : ":";
  409. writeValue(value[name]);
  410. }
  411. document_ += '}';
  412. }
  413. break;
  414. }
  415. }
  416. // Class StyledWriter
  417. // //////////////////////////////////////////////////////////////////
  418. StyledWriter::StyledWriter() = default;
  419. String StyledWriter::write(const Value & root)
  420. {
  421. document_.clear();
  422. addChildValues_ = false;
  423. indentString_.clear();
  424. writeCommentBeforeValue(root);
  425. writeValue(root);
  426. writeCommentAfterValueOnSameLine(root);
  427. document_ += '\n';
  428. return document_;
  429. }
  430. void StyledWriter::writeValue(const Value & value)
  431. {
  432. switch (value.type())
  433. {
  434. case nullValue: pushValue("null"); break;
  435. case intValue : pushValue(valueToString(value.asLargestInt())); break;
  436. case uintValue: pushValue(valueToString(value.asLargestUInt())); break;
  437. case realValue: pushValue(valueToString(value.asDouble())); break;
  438. case stringValue:
  439. {
  440. // Is NULL possible for value.string_? No.
  441. const char * str;
  442. const char * end;
  443. bool ok = value.getString(&str, &end);
  444. if (ok)
  445. {
  446. pushValue(valueToQuotedStringN(str, static_cast<unsigned>(end - str)));
  447. }
  448. else
  449. {
  450. pushValue("");
  451. }
  452. break;
  453. }
  454. case booleanValue: pushValue(valueToString(value.asBool())); break;
  455. case arrayValue : writeArrayValue(value); break;
  456. case objectValue:
  457. {
  458. Value::Members members(value.getMemberNames());
  459. if (members.empty())
  460. {
  461. pushValue("{}");
  462. }
  463. else
  464. {
  465. writeWithIndent("{");
  466. indent();
  467. auto it = members.begin();
  468. for (;;)
  469. {
  470. const String & name = *it;
  471. const Value & childValue = value[name];
  472. writeCommentBeforeValue(childValue);
  473. writeWithIndent(valueToQuotedString(name.c_str()));
  474. document_ += " : ";
  475. writeValue(childValue);
  476. if (++it == members.end())
  477. {
  478. writeCommentAfterValueOnSameLine(childValue);
  479. break;
  480. }
  481. document_ += ',';
  482. writeCommentAfterValueOnSameLine(childValue);
  483. }
  484. unindent();
  485. writeWithIndent("}");
  486. }
  487. }
  488. break;
  489. }
  490. }
  491. void StyledWriter::writeArrayValue(const Value & value)
  492. {
  493. unsigned size = value.size();
  494. if (size == 0)
  495. {
  496. pushValue("[]");
  497. }
  498. else
  499. {
  500. bool isArrayMultiLine = isMultilineArray(value);
  501. if (isArrayMultiLine)
  502. {
  503. writeWithIndent("[");
  504. indent();
  505. bool hasChildValue = ! childValues_.empty();
  506. unsigned index = 0;
  507. for (;;)
  508. {
  509. const Value & childValue = value[index];
  510. writeCommentBeforeValue(childValue);
  511. if (hasChildValue)
  512. {
  513. writeWithIndent(childValues_[index]);
  514. }
  515. else
  516. {
  517. writeIndent();
  518. writeValue(childValue);
  519. }
  520. if (++index == size)
  521. {
  522. writeCommentAfterValueOnSameLine(childValue);
  523. break;
  524. }
  525. document_ += ',';
  526. writeCommentAfterValueOnSameLine(childValue);
  527. }
  528. unindent();
  529. writeWithIndent("]");
  530. }
  531. else // output on a single line
  532. {
  533. assert(childValues_.size() == size);
  534. document_ += "[ ";
  535. for (unsigned index = 0; index < size; ++index)
  536. {
  537. if (index > 0)
  538. {
  539. document_ += ", ";
  540. }
  541. document_ += childValues_[index];
  542. }
  543. document_ += " ]";
  544. }
  545. }
  546. }
  547. bool StyledWriter::isMultilineArray(const Value & value)
  548. {
  549. const ArrayIndex size = value.size();
  550. bool isMultiLine = size * 3 >= rightMargin_;
  551. childValues_.clear();
  552. for (ArrayIndex index = 0; index < size && ! isMultiLine; ++index)
  553. {
  554. const Value & childValue = value[index];
  555. isMultiLine = ((childValue.isArray() || childValue.isObject()) && ! childValue.empty());
  556. }
  557. if (! isMultiLine) // check if line length > max line length
  558. {
  559. childValues_.reserve(size);
  560. addChildValues_ = true;
  561. ArrayIndex lineLength = 4 + (size - 1) * 2; // '[ ' + ', '*n + ' ]'
  562. for (ArrayIndex index = 0; index < size; ++index)
  563. {
  564. if (hasCommentForValue(value[index]))
  565. {
  566. isMultiLine = true;
  567. }
  568. writeValue(value[index]);
  569. lineLength += static_cast<ArrayIndex>(childValues_[index].length());
  570. }
  571. addChildValues_ = false;
  572. isMultiLine = isMultiLine || lineLength >= rightMargin_;
  573. }
  574. return isMultiLine;
  575. }
  576. void StyledWriter::pushValue(const String & value)
  577. {
  578. if (addChildValues_)
  579. {
  580. childValues_.push_back(value);
  581. }
  582. else
  583. {
  584. document_ += value;
  585. }
  586. }
  587. void StyledWriter::writeIndent()
  588. {
  589. if (! document_.empty())
  590. {
  591. char last = document_[document_.length() - 1];
  592. if (last == ' ') // already indented
  593. {
  594. return;
  595. }
  596. if (last != '\n') // Comments may add new-line
  597. {
  598. document_ += '\n';
  599. }
  600. }
  601. document_ += indentString_;
  602. }
  603. void StyledWriter::writeWithIndent(const String & value)
  604. {
  605. writeIndent();
  606. document_ += value;
  607. }
  608. void StyledWriter::indent()
  609. {
  610. indentString_ += String(indentSize_, ' ');
  611. }
  612. void StyledWriter::unindent()
  613. {
  614. assert(indentString_.size() >= indentSize_);
  615. indentString_.resize(indentString_.size() - indentSize_);
  616. }
  617. void StyledWriter::writeCommentBeforeValue(const Value & root)
  618. {
  619. if (! root.hasComment(commentBefore))
  620. {
  621. return;
  622. }
  623. document_ += '\n';
  624. writeIndent();
  625. const String & comment = root.getComment(commentBefore);
  626. String::const_iterator iter = comment.begin();
  627. while (iter != comment.end())
  628. {
  629. document_ += *iter;
  630. if (*iter == '\n' && ((iter + 1) != comment.end() && *(iter + 1) == '/'))
  631. {
  632. writeIndent();
  633. }
  634. ++iter;
  635. }
  636. // Comments are stripped of trailing newlines, so add one here
  637. document_ += '\n';
  638. }
  639. void StyledWriter::writeCommentAfterValueOnSameLine(const Value & root)
  640. {
  641. if (root.hasComment(commentAfterOnSameLine))
  642. {
  643. document_ += " " + root.getComment(commentAfterOnSameLine);
  644. }
  645. if (root.hasComment(commentAfter))
  646. {
  647. document_ += '\n';
  648. document_ += root.getComment(commentAfter);
  649. document_ += '\n';
  650. }
  651. }
  652. bool StyledWriter::hasCommentForValue(const Value & value)
  653. {
  654. return value.hasComment(commentBefore) || value.hasComment(commentAfterOnSameLine) || value.hasComment(commentAfter);
  655. }
  656. // Class StyledStreamWriter
  657. // //////////////////////////////////////////////////////////////////
  658. StyledStreamWriter::StyledStreamWriter(String indentation) :
  659. document_(nullptr),
  660. indentation_(std::move(indentation)),
  661. addChildValues_(),
  662. indented_(false)
  663. {
  664. }
  665. void StyledStreamWriter::write(OStream & out, const Value & root)
  666. {
  667. document_ = &out;
  668. addChildValues_ = false;
  669. indentString_.clear();
  670. indented_ = true;
  671. writeCommentBeforeValue(root);
  672. if (! indented_)
  673. {
  674. writeIndent();
  675. }
  676. indented_ = true;
  677. writeValue(root);
  678. writeCommentAfterValueOnSameLine(root);
  679. *document_ << "\n";
  680. document_ = nullptr; // Forget the stream, for safety.
  681. }
  682. void StyledStreamWriter::writeValue(const Value & value)
  683. {
  684. switch (value.type())
  685. {
  686. case nullValue: pushValue("null"); break;
  687. case intValue : pushValue(valueToString(value.asLargestInt())); break;
  688. case uintValue: pushValue(valueToString(value.asLargestUInt())); break;
  689. case realValue: pushValue(valueToString(value.asDouble())); break;
  690. case stringValue:
  691. {
  692. // Is NULL possible for value.string_? No.
  693. const char * str;
  694. const char * end;
  695. bool ok = value.getString(&str, &end);
  696. if (ok)
  697. {
  698. pushValue(valueToQuotedStringN(str, static_cast<unsigned>(end - str)));
  699. }
  700. else
  701. {
  702. pushValue("");
  703. }
  704. break;
  705. }
  706. case booleanValue: pushValue(valueToString(value.asBool())); break;
  707. case arrayValue : writeArrayValue(value); break;
  708. case objectValue:
  709. {
  710. Value::Members members(value.getMemberNames());
  711. if (members.empty())
  712. {
  713. pushValue("{}");
  714. }
  715. else
  716. {
  717. writeWithIndent("{");
  718. indent();
  719. auto it = members.begin();
  720. for (;;)
  721. {
  722. const String & name = *it;
  723. const Value & childValue = value[name];
  724. writeCommentBeforeValue(childValue);
  725. writeWithIndent(valueToQuotedString(name.c_str()));
  726. *document_ << " : ";
  727. writeValue(childValue);
  728. if (++it == members.end())
  729. {
  730. writeCommentAfterValueOnSameLine(childValue);
  731. break;
  732. }
  733. *document_ << ",";
  734. writeCommentAfterValueOnSameLine(childValue);
  735. }
  736. unindent();
  737. writeWithIndent("}");
  738. }
  739. }
  740. break;
  741. }
  742. }
  743. void StyledStreamWriter::writeArrayValue(const Value & value)
  744. {
  745. unsigned size = value.size();
  746. if (size == 0)
  747. {
  748. pushValue("[]");
  749. }
  750. else
  751. {
  752. bool isArrayMultiLine = isMultilineArray(value);
  753. if (isArrayMultiLine)
  754. {
  755. writeWithIndent("[");
  756. indent();
  757. bool hasChildValue = ! childValues_.empty();
  758. unsigned index = 0;
  759. for (;;)
  760. {
  761. const Value & childValue = value[index];
  762. writeCommentBeforeValue(childValue);
  763. if (hasChildValue)
  764. {
  765. writeWithIndent(childValues_[index]);
  766. }
  767. else
  768. {
  769. if (! indented_)
  770. {
  771. writeIndent();
  772. }
  773. indented_ = true;
  774. writeValue(childValue);
  775. indented_ = false;
  776. }
  777. if (++index == size)
  778. {
  779. writeCommentAfterValueOnSameLine(childValue);
  780. break;
  781. }
  782. *document_ << ",";
  783. writeCommentAfterValueOnSameLine(childValue);
  784. }
  785. unindent();
  786. writeWithIndent("]");
  787. }
  788. else // output on a single line
  789. {
  790. assert(childValues_.size() == size);
  791. *document_ << "[ ";
  792. for (unsigned index = 0; index < size; ++index)
  793. {
  794. if (index > 0)
  795. {
  796. *document_ << ", ";
  797. }
  798. *document_ << childValues_[index];
  799. }
  800. *document_ << " ]";
  801. }
  802. }
  803. }
  804. bool StyledStreamWriter::isMultilineArray(const Value & value)
  805. {
  806. const ArrayIndex size = value.size();
  807. bool isMultiLine = size * 3 >= rightMargin_;
  808. childValues_.clear();
  809. for (ArrayIndex index = 0; index < size && ! isMultiLine; ++index)
  810. {
  811. const Value & childValue = value[index];
  812. isMultiLine = ((childValue.isArray() || childValue.isObject()) && ! childValue.empty());
  813. }
  814. if (! isMultiLine) // check if line length > max line length
  815. {
  816. childValues_.reserve(size);
  817. addChildValues_ = true;
  818. ArrayIndex lineLength = 4 + (size - 1) * 2; // '[ ' + ', '*n + ' ]'
  819. for (ArrayIndex index = 0; index < size; ++index)
  820. {
  821. if (hasCommentForValue(value[index]))
  822. {
  823. isMultiLine = true;
  824. }
  825. writeValue(value[index]);
  826. lineLength += static_cast<ArrayIndex>(childValues_[index].length());
  827. }
  828. addChildValues_ = false;
  829. isMultiLine = isMultiLine || lineLength >= rightMargin_;
  830. }
  831. return isMultiLine;
  832. }
  833. void StyledStreamWriter::pushValue(const String & value)
  834. {
  835. if (addChildValues_)
  836. {
  837. childValues_.push_back(value);
  838. }
  839. else
  840. {
  841. *document_ << value;
  842. }
  843. }
  844. void StyledStreamWriter::writeIndent()
  845. {
  846. // blep intended this to look at the so-far-written string
  847. // to determine whether we are already indented, but
  848. // with a stream we cannot do that. So we rely on some saved state.
  849. // The caller checks indented_.
  850. *document_ << '\n' << indentString_;
  851. }
  852. void StyledStreamWriter::writeWithIndent(const String & value)
  853. {
  854. if (! indented_)
  855. {
  856. writeIndent();
  857. }
  858. *document_ << value;
  859. indented_ = false;
  860. }
  861. void StyledStreamWriter::indent()
  862. {
  863. indentString_ += indentation_;
  864. }
  865. void StyledStreamWriter::unindent()
  866. {
  867. assert(indentString_.size() >= indentation_.size());
  868. indentString_.resize(indentString_.size() - indentation_.size());
  869. }
  870. void StyledStreamWriter::writeCommentBeforeValue(const Value & root)
  871. {
  872. if (! root.hasComment(commentBefore))
  873. {
  874. return;
  875. }
  876. if (! indented_)
  877. {
  878. writeIndent();
  879. }
  880. const String & comment = root.getComment(commentBefore);
  881. String::const_iterator iter = comment.begin();
  882. while (iter != comment.end())
  883. {
  884. *document_ << *iter;
  885. if (*iter == '\n' && ((iter + 1) != comment.end() && *(iter + 1) == '/'))
  886. {
  887. // writeIndent(); // would include newline
  888. *document_ << indentString_;
  889. }
  890. ++iter;
  891. }
  892. indented_ = false;
  893. }
  894. void StyledStreamWriter::writeCommentAfterValueOnSameLine(const Value & root)
  895. {
  896. if (root.hasComment(commentAfterOnSameLine))
  897. {
  898. *document_ << ' ' << root.getComment(commentAfterOnSameLine);
  899. }
  900. if (root.hasComment(commentAfter))
  901. {
  902. writeIndent();
  903. *document_ << root.getComment(commentAfter);
  904. }
  905. indented_ = false;
  906. }
  907. bool StyledStreamWriter::hasCommentForValue(const Value & value)
  908. {
  909. return value.hasComment(commentBefore) || value.hasComment(commentAfterOnSameLine) || value.hasComment(commentAfter);
  910. }
  911. //////////////////////////
  912. // BuiltStyledStreamWriter
  913. /// Scoped enums are not available until C++11.
  914. struct CommentStyle
  915. {
  916. /// Decide whether to write comments.
  917. enum Enum
  918. {
  919. None, ///< Drop all comments.
  920. Most, ///< Recover odd behavior of previous versions (not implemented yet).
  921. All ///< Keep all comments.
  922. };
  923. };
  924. struct BuiltStyledStreamWriter : public StreamWriter
  925. {
  926. BuiltStyledStreamWriter(String indentation, CommentStyle::Enum cs, String colonSymbol, String nullSymbol, String endingLineFeedSymbol, bool useSpecialFloats, unsigned int precision, PrecisionType precisionType);
  927. int write(const Value & root, OStream * sout) override;
  928. private:
  929. void writeValue(const Value & value);
  930. void writeArrayValue(const Value & value);
  931. bool isMultilineArray(const Value & value);
  932. void pushValue(const String & value);
  933. void writeIndent();
  934. void writeWithIndent(const String & value);
  935. void indent();
  936. void unindent();
  937. void writeCommentBeforeValue(const Value & root);
  938. void writeCommentAfterValueOnSameLine(const Value & root);
  939. static bool hasCommentForValue(const Value & value);
  940. typedef std::vector<String> ChildValues;
  941. ChildValues childValues_;
  942. String indentString_;
  943. unsigned int rightMargin_;
  944. String indentation_;
  945. CommentStyle::Enum cs_;
  946. String colonSymbol_;
  947. String nullSymbol_;
  948. String endingLineFeedSymbol_;
  949. bool addChildValues_ : 1;
  950. bool indented_ : 1;
  951. bool useSpecialFloats_ : 1;
  952. unsigned int precision_;
  953. PrecisionType precisionType_;
  954. };
  955. BuiltStyledStreamWriter::BuiltStyledStreamWriter(String indentation, CommentStyle::Enum cs, String colonSymbol, String nullSymbol, String endingLineFeedSymbol, bool useSpecialFloats, unsigned int precision, PrecisionType precisionType) :
  956. rightMargin_(74),
  957. indentation_(std::move(indentation)),
  958. cs_(cs),
  959. colonSymbol_(std::move(colonSymbol)),
  960. nullSymbol_(std::move(nullSymbol)),
  961. endingLineFeedSymbol_(std::move(endingLineFeedSymbol)),
  962. addChildValues_(false),
  963. indented_(false),
  964. useSpecialFloats_(useSpecialFloats),
  965. precision_(precision),
  966. precisionType_(precisionType)
  967. {
  968. }
  969. int BuiltStyledStreamWriter::write(const Value & root, OStream * sout)
  970. {
  971. sout_ = sout;
  972. addChildValues_ = false;
  973. indented_ = true;
  974. indentString_.clear();
  975. writeCommentBeforeValue(root);
  976. if (! indented_)
  977. {
  978. writeIndent();
  979. }
  980. indented_ = true;
  981. writeValue(root);
  982. writeCommentAfterValueOnSameLine(root);
  983. *sout_ << endingLineFeedSymbol_;
  984. sout_ = nullptr;
  985. return 0;
  986. }
  987. void BuiltStyledStreamWriter::writeValue(const Value & value)
  988. {
  989. switch (value.type())
  990. {
  991. case nullValue: pushValue(nullSymbol_); break;
  992. case intValue : pushValue(valueToString(value.asLargestInt())); break;
  993. case uintValue: pushValue(valueToString(value.asLargestUInt())); break;
  994. case realValue: pushValue(valueToString(value.asDouble(), useSpecialFloats_, precision_, precisionType_)); break;
  995. case stringValue:
  996. {
  997. // Is NULL is possible for value.string_? No.
  998. const char * str;
  999. const char * end;
  1000. bool ok = value.getString(&str, &end);
  1001. if (ok)
  1002. {
  1003. pushValue(valueToQuotedStringN(str, static_cast<unsigned>(end - str)));
  1004. }
  1005. else
  1006. {
  1007. pushValue("");
  1008. }
  1009. break;
  1010. }
  1011. case booleanValue: pushValue(valueToString(value.asBool())); break;
  1012. case arrayValue : writeArrayValue(value); break;
  1013. case objectValue:
  1014. {
  1015. Value::Members members(value.getMemberNames());
  1016. if (members.empty())
  1017. {
  1018. pushValue("{}");
  1019. }
  1020. else
  1021. {
  1022. writeWithIndent("{");
  1023. indent();
  1024. auto it = members.begin();
  1025. for (;;)
  1026. {
  1027. const String & name = *it;
  1028. const Value & childValue = value[name];
  1029. writeCommentBeforeValue(childValue);
  1030. writeWithIndent(valueToQuotedStringN(name.data(), static_cast<unsigned>(name.length())));
  1031. *sout_ << colonSymbol_;
  1032. writeValue(childValue);
  1033. if (++it == members.end())
  1034. {
  1035. writeCommentAfterValueOnSameLine(childValue);
  1036. break;
  1037. }
  1038. *sout_ << ",";
  1039. writeCommentAfterValueOnSameLine(childValue);
  1040. }
  1041. unindent();
  1042. writeWithIndent("}");
  1043. }
  1044. }
  1045. break;
  1046. }
  1047. }
  1048. void BuiltStyledStreamWriter::writeArrayValue(const Value & value)
  1049. {
  1050. unsigned size = value.size();
  1051. if (size == 0)
  1052. {
  1053. pushValue("[]");
  1054. }
  1055. else
  1056. {
  1057. bool isMultiLine = (cs_ == CommentStyle::All) || isMultilineArray(value);
  1058. if (isMultiLine)
  1059. {
  1060. writeWithIndent("[");
  1061. indent();
  1062. bool hasChildValue = ! childValues_.empty();
  1063. unsigned index = 0;
  1064. for (;;)
  1065. {
  1066. const Value & childValue = value[index];
  1067. writeCommentBeforeValue(childValue);
  1068. if (hasChildValue)
  1069. {
  1070. writeWithIndent(childValues_[index]);
  1071. }
  1072. else
  1073. {
  1074. if (! indented_)
  1075. {
  1076. writeIndent();
  1077. }
  1078. indented_ = true;
  1079. writeValue(childValue);
  1080. indented_ = false;
  1081. }
  1082. if (++index == size)
  1083. {
  1084. writeCommentAfterValueOnSameLine(childValue);
  1085. break;
  1086. }
  1087. *sout_ << ",";
  1088. writeCommentAfterValueOnSameLine(childValue);
  1089. }
  1090. unindent();
  1091. writeWithIndent("]");
  1092. }
  1093. else // output on a single line
  1094. {
  1095. assert(childValues_.size() == size);
  1096. *sout_ << "[";
  1097. if (! indentation_.empty())
  1098. {
  1099. *sout_ << " ";
  1100. }
  1101. for (unsigned index = 0; index < size; ++index)
  1102. {
  1103. if (index > 0)
  1104. {
  1105. *sout_ << ((! indentation_.empty()) ? ", " : ",");
  1106. }
  1107. *sout_ << childValues_[index];
  1108. }
  1109. if (! indentation_.empty())
  1110. {
  1111. *sout_ << " ";
  1112. }
  1113. *sout_ << "]";
  1114. }
  1115. }
  1116. }
  1117. bool BuiltStyledStreamWriter::isMultilineArray(const Value & value)
  1118. {
  1119. const ArrayIndex size = value.size();
  1120. bool isMultiLine = size * 3 >= rightMargin_;
  1121. childValues_.clear();
  1122. for (ArrayIndex index = 0; index < size && ! isMultiLine; ++index)
  1123. {
  1124. const Value & childValue = value[index];
  1125. isMultiLine = ((childValue.isArray() || childValue.isObject()) && ! childValue.empty());
  1126. }
  1127. if (! isMultiLine) // check if line length > max line length
  1128. {
  1129. childValues_.reserve(size);
  1130. addChildValues_ = true;
  1131. ArrayIndex lineLength = 4 + (size - 1) * 2; // '[ ' + ', '*n + ' ]'
  1132. for (ArrayIndex index = 0; index < size; ++index)
  1133. {
  1134. if (hasCommentForValue(value[index]))
  1135. {
  1136. isMultiLine = true;
  1137. }
  1138. writeValue(value[index]);
  1139. lineLength += static_cast<ArrayIndex>(childValues_[index].length());
  1140. }
  1141. addChildValues_ = false;
  1142. isMultiLine = isMultiLine || lineLength >= rightMargin_;
  1143. }
  1144. return isMultiLine;
  1145. }
  1146. void BuiltStyledStreamWriter::pushValue(const String & value)
  1147. {
  1148. if (addChildValues_)
  1149. {
  1150. childValues_.push_back(value);
  1151. }
  1152. else
  1153. {
  1154. *sout_ << value;
  1155. }
  1156. }
  1157. void BuiltStyledStreamWriter::writeIndent()
  1158. {
  1159. // blep intended this to look at the so-far-written string
  1160. // to determine whether we are already indented, but
  1161. // with a stream we cannot do that. So we rely on some saved state.
  1162. // The caller checks indented_.
  1163. if (! indentation_.empty())
  1164. {
  1165. // In this case, drop newlines too.
  1166. *sout_ << '\n' << indentString_;
  1167. }
  1168. }
  1169. void BuiltStyledStreamWriter::writeWithIndent(const String & value)
  1170. {
  1171. if (! indented_)
  1172. {
  1173. writeIndent();
  1174. }
  1175. *sout_ << value;
  1176. indented_ = false;
  1177. }
  1178. void BuiltStyledStreamWriter::indent()
  1179. {
  1180. indentString_ += indentation_;
  1181. }
  1182. void BuiltStyledStreamWriter::unindent()
  1183. {
  1184. assert(indentString_.size() >= indentation_.size());
  1185. indentString_.resize(indentString_.size() - indentation_.size());
  1186. }
  1187. void BuiltStyledStreamWriter::writeCommentBeforeValue(const Value & root)
  1188. {
  1189. if (cs_ == CommentStyle::None)
  1190. {
  1191. return;
  1192. }
  1193. if (! root.hasComment(commentBefore))
  1194. {
  1195. return;
  1196. }
  1197. if (! indented_)
  1198. {
  1199. writeIndent();
  1200. }
  1201. const String & comment = root.getComment(commentBefore);
  1202. String::const_iterator iter = comment.begin();
  1203. while (iter != comment.end())
  1204. {
  1205. *sout_ << *iter;
  1206. if (*iter == '\n' && ((iter + 1) != comment.end() && *(iter + 1) == '/'))
  1207. {
  1208. // writeIndent(); // would write extra newline
  1209. *sout_ << indentString_;
  1210. }
  1211. ++iter;
  1212. }
  1213. indented_ = false;
  1214. }
  1215. void BuiltStyledStreamWriter::writeCommentAfterValueOnSameLine(const Value & root)
  1216. {
  1217. if (cs_ == CommentStyle::None)
  1218. {
  1219. return;
  1220. }
  1221. if (root.hasComment(commentAfterOnSameLine))
  1222. {
  1223. *sout_ << " " + root.getComment(commentAfterOnSameLine);
  1224. }
  1225. if (root.hasComment(commentAfter))
  1226. {
  1227. writeIndent();
  1228. *sout_ << root.getComment(commentAfter);
  1229. }
  1230. }
  1231. // static
  1232. bool BuiltStyledStreamWriter::hasCommentForValue(const Value & value)
  1233. {
  1234. return value.hasComment(commentBefore) || value.hasComment(commentAfterOnSameLine) || value.hasComment(commentAfter);
  1235. }
  1236. ///////////////
  1237. // StreamWriter
  1238. StreamWriter::StreamWriter() :
  1239. sout_(nullptr)
  1240. {
  1241. }
  1242. StreamWriter::~StreamWriter() = default;
  1243. StreamWriter::Factory::~Factory() = default;
  1244. StreamWriterBuilder::StreamWriterBuilder()
  1245. {
  1246. setDefaults(&settings_);
  1247. }
  1248. StreamWriterBuilder::~StreamWriterBuilder() = default;
  1249. StreamWriter * StreamWriterBuilder::newStreamWriter() const
  1250. {
  1251. String indentation = settings_["indentation"].asString();
  1252. String cs_str = settings_["commentStyle"].asString();
  1253. String pt_str = settings_["precisionType"].asString();
  1254. bool eyc = settings_["enableYAMLCompatibility"].asBool();
  1255. bool dnp = settings_["dropNullPlaceholders"].asBool();
  1256. bool usf = settings_["useSpecialFloats"].asBool();
  1257. unsigned int pre = settings_["precision"].asUInt();
  1258. CommentStyle::Enum cs = CommentStyle::All;
  1259. if (cs_str == "All")
  1260. {
  1261. cs = CommentStyle::All;
  1262. }
  1263. else if (cs_str == "None")
  1264. {
  1265. cs = CommentStyle::None;
  1266. }
  1267. else
  1268. {
  1269. throwRuntimeError("commentStyle must be 'All' or 'None'");
  1270. }
  1271. PrecisionType precisionType(significantDigits);
  1272. if (pt_str == "significant")
  1273. {
  1274. precisionType = PrecisionType::significantDigits;
  1275. }
  1276. else if (pt_str == "decimal")
  1277. {
  1278. precisionType = PrecisionType::decimalPlaces;
  1279. }
  1280. else
  1281. {
  1282. throwRuntimeError("precisionType must be 'significant' or 'decimal'");
  1283. }
  1284. String colonSymbol = " : ";
  1285. if (eyc)
  1286. {
  1287. colonSymbol = ": ";
  1288. }
  1289. else if (indentation.empty())
  1290. {
  1291. colonSymbol = ":";
  1292. }
  1293. String nullSymbol = "null";
  1294. if (dnp)
  1295. {
  1296. nullSymbol.clear();
  1297. }
  1298. if (pre > 17)
  1299. {
  1300. pre = 17;
  1301. }
  1302. String endingLineFeedSymbol;
  1303. return new BuiltStyledStreamWriter(indentation, cs, colonSymbol, nullSymbol, endingLineFeedSymbol, usf, pre, precisionType);
  1304. }
  1305. static void getValidWriterKeys(std::set<String> * valid_keys)
  1306. {
  1307. valid_keys->clear();
  1308. valid_keys->insert("indentation");
  1309. valid_keys->insert("commentStyle");
  1310. valid_keys->insert("enableYAMLCompatibility");
  1311. valid_keys->insert("dropNullPlaceholders");
  1312. valid_keys->insert("useSpecialFloats");
  1313. valid_keys->insert("precision");
  1314. valid_keys->insert("precisionType");
  1315. }
  1316. bool StreamWriterBuilder::validate(Json::Value * invalid) const
  1317. {
  1318. Json::Value my_invalid;
  1319. if (! invalid)
  1320. {
  1321. invalid = &my_invalid; // so we do not need to test for NULL
  1322. }
  1323. Json::Value & inv = *invalid;
  1324. std::set<String> valid_keys;
  1325. getValidWriterKeys(&valid_keys);
  1326. Value::Members keys = settings_.getMemberNames();
  1327. size_t n = keys.size();
  1328. for (size_t i = 0; i < n; ++i)
  1329. {
  1330. const String & key = keys[i];
  1331. if (valid_keys.find(key) == valid_keys.end())
  1332. {
  1333. inv[key] = settings_[key];
  1334. }
  1335. }
  1336. return inv.empty();
  1337. }
  1338. Value & StreamWriterBuilder::operator[](const String & key)
  1339. {
  1340. return settings_[key];
  1341. }
  1342. // static
  1343. void StreamWriterBuilder::setDefaults(Json::Value * settings)
  1344. {
  1345. //! [StreamWriterBuilderDefaults]
  1346. (*settings)["commentStyle"] = "All";
  1347. (*settings)["indentation"] = "\t";
  1348. (*settings)["enableYAMLCompatibility"] = false;
  1349. (*settings)["dropNullPlaceholders"] = false;
  1350. (*settings)["useSpecialFloats"] = false;
  1351. (*settings)["precision"] = 17;
  1352. (*settings)["precisionType"] = "significant";
  1353. //! [StreamWriterBuilderDefaults]
  1354. }
  1355. String writeString(const StreamWriter::Factory & factory, const Value & root)
  1356. {
  1357. OStringStream sout;
  1358. const StreamWriterPtr writer(factory.newStreamWriter());
  1359. writer->write(root, &sout);
  1360. return sout.str();
  1361. }
  1362. OStream & operator<<(OStream & sout, const Value & root)
  1363. {
  1364. StreamWriterBuilder builder;
  1365. const StreamWriterPtr writer(builder.newStreamWriter());
  1366. writer->write(root, &sout);
  1367. return sout;
  1368. }
  1369. } // namespace Json