json_writer.cpp 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223
  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/writer.h>
  7. #include "json_tool.h"
  8. #endif // if !defined(JSON_IS_AMALGAMATION)
  9. #include <iomanip>
  10. #include <memory>
  11. #include <sstream>
  12. #include <utility>
  13. #include <set>
  14. #include <cassert>
  15. #include <cstring>
  16. #include <cstdio>
  17. #if defined(_MSC_VER) && _MSC_VER >= 1200 && _MSC_VER < 1800 // Between VC++ 6.0 and VC++ 11.0
  18. #include <float.h>
  19. #define isfinite _finite
  20. #elif defined(__sun) && defined(__SVR4) //Solaris
  21. #if !defined(isfinite)
  22. #include <ieeefp.h>
  23. #define isfinite finite
  24. #endif
  25. #elif defined(_AIX)
  26. #if !defined(isfinite)
  27. #include <math.h>
  28. #define isfinite finite
  29. #endif
  30. #elif defined(__hpux)
  31. #if !defined(isfinite)
  32. #if defined(__ia64) && !defined(finite)
  33. #define isfinite(x) ((sizeof(x) == sizeof(float) ? \
  34. _Isfinitef(x) : _IsFinite(x)))
  35. #else
  36. #include <math.h>
  37. #define isfinite finite
  38. #endif
  39. #endif
  40. #else
  41. #include <cmath>
  42. #if !(defined(__QNXNTO__)) // QNX already defines isfinite
  43. #define isfinite std::isfinite
  44. #endif
  45. #endif
  46. #if defined(_MSC_VER)
  47. #if !defined(WINCE) && defined(__STDC_SECURE_LIB__) && _MSC_VER >= 1500 // VC++ 9.0 and above
  48. #define snprintf sprintf_s
  49. #elif _MSC_VER >= 1900 // VC++ 14.0 and above
  50. #define snprintf std::snprintf
  51. #else
  52. #define snprintf _snprintf
  53. #endif
  54. #elif defined(__ANDROID__) || defined(__QNXNTO__)
  55. #define snprintf snprintf
  56. #elif __cplusplus >= 201103L
  57. #if !defined(__MINGW32__) && !defined(__CYGWIN__)
  58. #define snprintf std::snprintf
  59. #endif
  60. #endif
  61. #if defined(__BORLANDC__)
  62. #include <float.h>
  63. #define isfinite _finite
  64. #define snprintf _snprintf
  65. #endif
  66. #if defined(_MSC_VER) && _MSC_VER >= 1400 // VC++ 8.0
  67. // Disable warning about strdup being deprecated.
  68. #pragma warning(disable : 4996)
  69. #endif
  70. namespace Json {
  71. #if __cplusplus >= 201103L || (defined(_CPPLIB_VER) && _CPPLIB_VER >= 520)
  72. typedef std::unique_ptr<StreamWriter> StreamWriterPtr;
  73. #else
  74. typedef std::auto_ptr<StreamWriter> StreamWriterPtr;
  75. #endif
  76. static bool containsControlCharacter(const char* str) {
  77. while (*str) {
  78. if (isControlCharacter(*(str++)))
  79. return true;
  80. }
  81. return false;
  82. }
  83. static bool containsControlCharacter0(const char* str, unsigned len) {
  84. char const* end = str + len;
  85. while (end != str) {
  86. if (isControlCharacter(*str) || 0==*str)
  87. return true;
  88. ++str;
  89. }
  90. return false;
  91. }
  92. JSONCPP_STRING valueToString(LargestInt value) {
  93. UIntToStringBuffer buffer;
  94. char* current = buffer + sizeof(buffer);
  95. if (value == Value::minLargestInt) {
  96. uintToString(LargestUInt(Value::maxLargestInt) + 1, current);
  97. *--current = '-';
  98. } else if (value < 0) {
  99. uintToString(LargestUInt(-value), current);
  100. *--current = '-';
  101. } else {
  102. uintToString(LargestUInt(value), current);
  103. }
  104. assert(current >= buffer);
  105. return current;
  106. }
  107. JSONCPP_STRING valueToString(LargestUInt value) {
  108. UIntToStringBuffer buffer;
  109. char* current = buffer + sizeof(buffer);
  110. uintToString(value, current);
  111. assert(current >= buffer);
  112. return current;
  113. }
  114. #if defined(JSON_HAS_INT64)
  115. JSONCPP_STRING valueToString(Int value) {
  116. return valueToString(LargestInt(value));
  117. }
  118. JSONCPP_STRING valueToString(UInt value) {
  119. return valueToString(LargestUInt(value));
  120. }
  121. #endif // # if defined(JSON_HAS_INT64)
  122. namespace {
  123. JSONCPP_STRING valueToString(double value, bool useSpecialFloats, unsigned int precision) {
  124. // Allocate a buffer that is more than large enough to store the 16 digits of
  125. // precision requested below.
  126. char buffer[36];
  127. int len = -1;
  128. char formatString[15];
  129. snprintf(formatString, sizeof(formatString), "%%.%dg", precision);
  130. // Print into the buffer. We need not request the alternative representation
  131. // that always has a decimal point because JSON doesn't distingish the
  132. // concepts of reals and integers.
  133. if (isfinite(value)) {
  134. len = snprintf(buffer, sizeof(buffer), formatString, value);
  135. fixNumericLocale(buffer, buffer + len);
  136. // try to ensure we preserve the fact that this was given to us as a double on input
  137. if (!strchr(buffer, '.') && !strchr(buffer, 'e')) {
  138. strcat(buffer, ".0");
  139. }
  140. } else {
  141. // IEEE standard states that NaN values will not compare to themselves
  142. if (value != value) {
  143. len = snprintf(buffer, sizeof(buffer), useSpecialFloats ? "NaN" : "null");
  144. } else if (value < 0) {
  145. len = snprintf(buffer, sizeof(buffer), useSpecialFloats ? "-Infinity" : "-1e+9999");
  146. } else {
  147. len = snprintf(buffer, sizeof(buffer), useSpecialFloats ? "Infinity" : "1e+9999");
  148. }
  149. }
  150. assert(len >= 0);
  151. return buffer;
  152. }
  153. }
  154. JSONCPP_STRING valueToString(double value) { return valueToString(value, false, 17); }
  155. JSONCPP_STRING valueToString(bool value) { return value ? "true" : "false"; }
  156. JSONCPP_STRING valueToQuotedString(const char* value) {
  157. if (value == NULL)
  158. return "";
  159. // Not sure how to handle unicode...
  160. if (strpbrk(value, "\"\\\b\f\n\r\t") == NULL &&
  161. !containsControlCharacter(value))
  162. return JSONCPP_STRING("\"") + value + "\"";
  163. // We have to walk value and escape any special characters.
  164. // Appending to JSONCPP_STRING is not efficient, but this should be rare.
  165. // (Note: forward slashes are *not* rare, but I am not escaping them.)
  166. JSONCPP_STRING::size_type maxsize =
  167. strlen(value) * 2 + 3; // allescaped+quotes+NULL
  168. JSONCPP_STRING result;
  169. result.reserve(maxsize); // to avoid lots of mallocs
  170. result += "\"";
  171. for (const char* c = value; *c != 0; ++c) {
  172. switch (*c) {
  173. case '\"':
  174. result += "\\\"";
  175. break;
  176. case '\\':
  177. result += "\\\\";
  178. break;
  179. case '\b':
  180. result += "\\b";
  181. break;
  182. case '\f':
  183. result += "\\f";
  184. break;
  185. case '\n':
  186. result += "\\n";
  187. break;
  188. case '\r':
  189. result += "\\r";
  190. break;
  191. case '\t':
  192. result += "\\t";
  193. break;
  194. // case '/':
  195. // Even though \/ is considered a legal escape in JSON, a bare
  196. // slash is also legal, so I see no reason to escape it.
  197. // (I hope I am not misunderstanding something.
  198. // blep notes: actually escaping \/ may be useful in javascript to avoid </
  199. // sequence.
  200. // Should add a flag to allow this compatibility mode and prevent this
  201. // sequence from occurring.
  202. default:
  203. if (isControlCharacter(*c)) {
  204. JSONCPP_OSTRINGSTREAM oss;
  205. oss << "\\u" << std::hex << std::uppercase << std::setfill('0')
  206. << std::setw(4) << static_cast<int>(*c);
  207. result += oss.str();
  208. } else {
  209. result += *c;
  210. }
  211. break;
  212. }
  213. }
  214. result += "\"";
  215. return result;
  216. }
  217. // https://github.com/upcaste/upcaste/blob/master/src/upcore/src/cstring/strnpbrk.cpp
  218. static char const* strnpbrk(char const* s, char const* accept, size_t n) {
  219. assert((s || !n) && accept);
  220. char const* const end = s + n;
  221. for (char const* cur = s; cur < end; ++cur) {
  222. int const c = *cur;
  223. for (char const* a = accept; *a; ++a) {
  224. if (*a == c) {
  225. return cur;
  226. }
  227. }
  228. }
  229. return NULL;
  230. }
  231. static JSONCPP_STRING valueToQuotedStringN(const char* value, unsigned length) {
  232. if (value == NULL)
  233. return "";
  234. // Not sure how to handle unicode...
  235. if (strnpbrk(value, "\"\\\b\f\n\r\t", length) == NULL &&
  236. !containsControlCharacter0(value, length))
  237. return JSONCPP_STRING("\"") + value + "\"";
  238. // We have to walk value and escape any special characters.
  239. // Appending to JSONCPP_STRING is not efficient, but this should be rare.
  240. // (Note: forward slashes are *not* rare, but I am not escaping them.)
  241. JSONCPP_STRING::size_type maxsize =
  242. length * 2 + 3; // allescaped+quotes+NULL
  243. JSONCPP_STRING result;
  244. result.reserve(maxsize); // to avoid lots of mallocs
  245. result += "\"";
  246. char const* end = value + length;
  247. for (const char* c = value; c != end; ++c) {
  248. switch (*c) {
  249. case '\"':
  250. result += "\\\"";
  251. break;
  252. case '\\':
  253. result += "\\\\";
  254. break;
  255. case '\b':
  256. result += "\\b";
  257. break;
  258. case '\f':
  259. result += "\\f";
  260. break;
  261. case '\n':
  262. result += "\\n";
  263. break;
  264. case '\r':
  265. result += "\\r";
  266. break;
  267. case '\t':
  268. result += "\\t";
  269. break;
  270. // case '/':
  271. // Even though \/ is considered a legal escape in JSON, a bare
  272. // slash is also legal, so I see no reason to escape it.
  273. // (I hope I am not misunderstanding something.)
  274. // blep notes: actually escaping \/ may be useful in javascript to avoid </
  275. // sequence.
  276. // Should add a flag to allow this compatibility mode and prevent this
  277. // sequence from occurring.
  278. default:
  279. if ((isControlCharacter(*c)) || (*c == 0)) {
  280. JSONCPP_OSTRINGSTREAM oss;
  281. oss << "\\u" << std::hex << std::uppercase << std::setfill('0')
  282. << std::setw(4) << static_cast<int>(*c);
  283. result += oss.str();
  284. } else {
  285. result += *c;
  286. }
  287. break;
  288. }
  289. }
  290. result += "\"";
  291. return result;
  292. }
  293. // Class Writer
  294. // //////////////////////////////////////////////////////////////////
  295. Writer::~Writer() {}
  296. // Class FastWriter
  297. // //////////////////////////////////////////////////////////////////
  298. FastWriter::FastWriter()
  299. : yamlCompatiblityEnabled_(false), dropNullPlaceholders_(false),
  300. omitEndingLineFeed_(false) {}
  301. void FastWriter::enableYAMLCompatibility() { yamlCompatiblityEnabled_ = true; }
  302. void FastWriter::dropNullPlaceholders() { dropNullPlaceholders_ = true; }
  303. void FastWriter::omitEndingLineFeed() { omitEndingLineFeed_ = true; }
  304. JSONCPP_STRING FastWriter::write(const Value& root) {
  305. document_.clear();
  306. writeValue(root);
  307. if (!omitEndingLineFeed_)
  308. document_ += "\n";
  309. return document_;
  310. }
  311. void FastWriter::writeValue(const Value& value) {
  312. switch (value.type()) {
  313. case nullValue:
  314. if (!dropNullPlaceholders_)
  315. document_ += "null";
  316. break;
  317. case intValue:
  318. document_ += valueToString(value.asLargestInt());
  319. break;
  320. case uintValue:
  321. document_ += valueToString(value.asLargestUInt());
  322. break;
  323. case realValue:
  324. document_ += valueToString(value.asDouble());
  325. break;
  326. case stringValue:
  327. {
  328. // Is NULL possible for value.string_? No.
  329. char const* str;
  330. char const* end;
  331. bool ok = value.getString(&str, &end);
  332. if (ok) document_ += valueToQuotedStringN(str, static_cast<unsigned>(end-str));
  333. break;
  334. }
  335. case booleanValue:
  336. document_ += valueToString(value.asBool());
  337. break;
  338. case arrayValue: {
  339. document_ += '[';
  340. ArrayIndex size = value.size();
  341. for (ArrayIndex index = 0; index < size; ++index) {
  342. if (index > 0)
  343. document_ += ',';
  344. writeValue(value[index]);
  345. }
  346. document_ += ']';
  347. } break;
  348. case objectValue: {
  349. Value::Members members(value.getMemberNames());
  350. document_ += '{';
  351. for (Value::Members::iterator it = members.begin(); it != members.end();
  352. ++it) {
  353. const JSONCPP_STRING& name = *it;
  354. if (it != members.begin())
  355. document_ += ',';
  356. document_ += valueToQuotedStringN(name.data(), static_cast<unsigned>(name.length()));
  357. document_ += yamlCompatiblityEnabled_ ? ": " : ":";
  358. writeValue(value[name]);
  359. }
  360. document_ += '}';
  361. } break;
  362. }
  363. }
  364. // Class StyledWriter
  365. // //////////////////////////////////////////////////////////////////
  366. StyledWriter::StyledWriter()
  367. : rightMargin_(74), indentSize_(3), addChildValues_() {}
  368. JSONCPP_STRING StyledWriter::write(const Value& root) {
  369. document_.clear();
  370. addChildValues_ = false;
  371. indentString_.clear();
  372. writeCommentBeforeValue(root);
  373. writeValue(root);
  374. writeCommentAfterValueOnSameLine(root);
  375. document_ += "\n";
  376. return document_;
  377. }
  378. void StyledWriter::writeValue(const Value& value) {
  379. switch (value.type()) {
  380. case nullValue:
  381. pushValue("null");
  382. break;
  383. case intValue:
  384. pushValue(valueToString(value.asLargestInt()));
  385. break;
  386. case uintValue:
  387. pushValue(valueToString(value.asLargestUInt()));
  388. break;
  389. case realValue:
  390. pushValue(valueToString(value.asDouble()));
  391. break;
  392. case stringValue:
  393. {
  394. // Is NULL possible for value.string_? No.
  395. char const* str;
  396. char const* end;
  397. bool ok = value.getString(&str, &end);
  398. if (ok) pushValue(valueToQuotedStringN(str, static_cast<unsigned>(end-str)));
  399. else pushValue("");
  400. break;
  401. }
  402. case booleanValue:
  403. pushValue(valueToString(value.asBool()));
  404. break;
  405. case arrayValue:
  406. writeArrayValue(value);
  407. break;
  408. case objectValue: {
  409. Value::Members members(value.getMemberNames());
  410. if (members.empty())
  411. pushValue("{}");
  412. else {
  413. writeWithIndent("{");
  414. indent();
  415. Value::Members::iterator it = members.begin();
  416. for (;;) {
  417. const JSONCPP_STRING& name = *it;
  418. const Value& childValue = value[name];
  419. writeCommentBeforeValue(childValue);
  420. writeWithIndent(valueToQuotedString(name.c_str()));
  421. document_ += " : ";
  422. writeValue(childValue);
  423. if (++it == members.end()) {
  424. writeCommentAfterValueOnSameLine(childValue);
  425. break;
  426. }
  427. document_ += ',';
  428. writeCommentAfterValueOnSameLine(childValue);
  429. }
  430. unindent();
  431. writeWithIndent("}");
  432. }
  433. } break;
  434. }
  435. }
  436. void StyledWriter::writeArrayValue(const Value& value) {
  437. unsigned size = value.size();
  438. if (size == 0)
  439. pushValue("[]");
  440. else {
  441. bool isArrayMultiLine = isMultineArray(value);
  442. if (isArrayMultiLine) {
  443. writeWithIndent("[");
  444. indent();
  445. bool hasChildValue = !childValues_.empty();
  446. unsigned index = 0;
  447. for (;;) {
  448. const Value& childValue = value[index];
  449. writeCommentBeforeValue(childValue);
  450. if (hasChildValue)
  451. writeWithIndent(childValues_[index]);
  452. else {
  453. writeIndent();
  454. writeValue(childValue);
  455. }
  456. if (++index == size) {
  457. writeCommentAfterValueOnSameLine(childValue);
  458. break;
  459. }
  460. document_ += ',';
  461. writeCommentAfterValueOnSameLine(childValue);
  462. }
  463. unindent();
  464. writeWithIndent("]");
  465. } else // output on a single line
  466. {
  467. assert(childValues_.size() == size);
  468. document_ += "[ ";
  469. for (unsigned index = 0; index < size; ++index) {
  470. if (index > 0)
  471. document_ += ", ";
  472. document_ += childValues_[index];
  473. }
  474. document_ += " ]";
  475. }
  476. }
  477. }
  478. bool StyledWriter::isMultineArray(const Value& value) {
  479. ArrayIndex const size = value.size();
  480. bool isMultiLine = size * 3 >= rightMargin_;
  481. childValues_.clear();
  482. for (ArrayIndex index = 0; index < size && !isMultiLine; ++index) {
  483. const Value& childValue = value[index];
  484. isMultiLine = ((childValue.isArray() || childValue.isObject()) &&
  485. childValue.size() > 0);
  486. }
  487. if (!isMultiLine) // check if line length > max line length
  488. {
  489. childValues_.reserve(size);
  490. addChildValues_ = true;
  491. ArrayIndex lineLength = 4 + (size - 1) * 2; // '[ ' + ', '*n + ' ]'
  492. for (ArrayIndex index = 0; index < size; ++index) {
  493. if (hasCommentForValue(value[index])) {
  494. isMultiLine = true;
  495. }
  496. writeValue(value[index]);
  497. lineLength += static_cast<ArrayIndex>(childValues_[index].length());
  498. }
  499. addChildValues_ = false;
  500. isMultiLine = isMultiLine || lineLength >= rightMargin_;
  501. }
  502. return isMultiLine;
  503. }
  504. void StyledWriter::pushValue(const JSONCPP_STRING& value) {
  505. if (addChildValues_)
  506. childValues_.push_back(value);
  507. else
  508. document_ += value;
  509. }
  510. void StyledWriter::writeIndent() {
  511. if (!document_.empty()) {
  512. char last = document_[document_.length() - 1];
  513. if (last == ' ') // already indented
  514. return;
  515. if (last != '\n') // Comments may add new-line
  516. document_ += '\n';
  517. }
  518. document_ += indentString_;
  519. }
  520. void StyledWriter::writeWithIndent(const JSONCPP_STRING& value) {
  521. writeIndent();
  522. document_ += value;
  523. }
  524. void StyledWriter::indent() { indentString_ += JSONCPP_STRING(indentSize_, ' '); }
  525. void StyledWriter::unindent() {
  526. assert(indentString_.size() >= indentSize_);
  527. indentString_.resize(indentString_.size() - indentSize_);
  528. }
  529. void StyledWriter::writeCommentBeforeValue(const Value& root) {
  530. if (!root.hasComment(commentBefore))
  531. return;
  532. document_ += "\n";
  533. writeIndent();
  534. const JSONCPP_STRING& comment = root.getComment(commentBefore);
  535. JSONCPP_STRING::const_iterator iter = comment.begin();
  536. while (iter != comment.end()) {
  537. document_ += *iter;
  538. if (*iter == '\n' &&
  539. (iter != comment.end() && *(iter + 1) == '/'))
  540. writeIndent();
  541. ++iter;
  542. }
  543. // Comments are stripped of trailing newlines, so add one here
  544. document_ += "\n";
  545. }
  546. void StyledWriter::writeCommentAfterValueOnSameLine(const Value& root) {
  547. if (root.hasComment(commentAfterOnSameLine))
  548. document_ += " " + root.getComment(commentAfterOnSameLine);
  549. if (root.hasComment(commentAfter)) {
  550. document_ += "\n";
  551. document_ += root.getComment(commentAfter);
  552. document_ += "\n";
  553. }
  554. }
  555. bool StyledWriter::hasCommentForValue(const Value& value) {
  556. return value.hasComment(commentBefore) ||
  557. value.hasComment(commentAfterOnSameLine) ||
  558. value.hasComment(commentAfter);
  559. }
  560. // Class StyledStreamWriter
  561. // //////////////////////////////////////////////////////////////////
  562. StyledStreamWriter::StyledStreamWriter(JSONCPP_STRING indentation)
  563. : document_(NULL), rightMargin_(74), indentation_(indentation),
  564. addChildValues_() {}
  565. void StyledStreamWriter::write(JSONCPP_OSTREAM& out, const Value& root) {
  566. document_ = &out;
  567. addChildValues_ = false;
  568. indentString_.clear();
  569. indented_ = true;
  570. writeCommentBeforeValue(root);
  571. if (!indented_) writeIndent();
  572. indented_ = true;
  573. writeValue(root);
  574. writeCommentAfterValueOnSameLine(root);
  575. *document_ << "\n";
  576. document_ = NULL; // Forget the stream, for safety.
  577. }
  578. void StyledStreamWriter::writeValue(const Value& value) {
  579. switch (value.type()) {
  580. case nullValue:
  581. pushValue("null");
  582. break;
  583. case intValue:
  584. pushValue(valueToString(value.asLargestInt()));
  585. break;
  586. case uintValue:
  587. pushValue(valueToString(value.asLargestUInt()));
  588. break;
  589. case realValue:
  590. pushValue(valueToString(value.asDouble()));
  591. break;
  592. case stringValue:
  593. {
  594. // Is NULL possible for value.string_? No.
  595. char const* str;
  596. char const* end;
  597. bool ok = value.getString(&str, &end);
  598. if (ok) pushValue(valueToQuotedStringN(str, static_cast<unsigned>(end-str)));
  599. else pushValue("");
  600. break;
  601. }
  602. case booleanValue:
  603. pushValue(valueToString(value.asBool()));
  604. break;
  605. case arrayValue:
  606. writeArrayValue(value);
  607. break;
  608. case objectValue: {
  609. Value::Members members(value.getMemberNames());
  610. if (members.empty())
  611. pushValue("{}");
  612. else {
  613. writeWithIndent("{");
  614. indent();
  615. Value::Members::iterator it = members.begin();
  616. for (;;) {
  617. const JSONCPP_STRING& name = *it;
  618. const Value& childValue = value[name];
  619. writeCommentBeforeValue(childValue);
  620. writeWithIndent(valueToQuotedString(name.c_str()));
  621. *document_ << " : ";
  622. writeValue(childValue);
  623. if (++it == members.end()) {
  624. writeCommentAfterValueOnSameLine(childValue);
  625. break;
  626. }
  627. *document_ << ",";
  628. writeCommentAfterValueOnSameLine(childValue);
  629. }
  630. unindent();
  631. writeWithIndent("}");
  632. }
  633. } break;
  634. }
  635. }
  636. void StyledStreamWriter::writeArrayValue(const Value& value) {
  637. unsigned size = value.size();
  638. if (size == 0)
  639. pushValue("[]");
  640. else {
  641. bool isArrayMultiLine = isMultineArray(value);
  642. if (isArrayMultiLine) {
  643. writeWithIndent("[");
  644. indent();
  645. bool hasChildValue = !childValues_.empty();
  646. unsigned index = 0;
  647. for (;;) {
  648. const Value& childValue = value[index];
  649. writeCommentBeforeValue(childValue);
  650. if (hasChildValue)
  651. writeWithIndent(childValues_[index]);
  652. else {
  653. if (!indented_) writeIndent();
  654. indented_ = true;
  655. writeValue(childValue);
  656. indented_ = false;
  657. }
  658. if (++index == size) {
  659. writeCommentAfterValueOnSameLine(childValue);
  660. break;
  661. }
  662. *document_ << ",";
  663. writeCommentAfterValueOnSameLine(childValue);
  664. }
  665. unindent();
  666. writeWithIndent("]");
  667. } else // output on a single line
  668. {
  669. assert(childValues_.size() == size);
  670. *document_ << "[ ";
  671. for (unsigned index = 0; index < size; ++index) {
  672. if (index > 0)
  673. *document_ << ", ";
  674. *document_ << childValues_[index];
  675. }
  676. *document_ << " ]";
  677. }
  678. }
  679. }
  680. bool StyledStreamWriter::isMultineArray(const Value& value) {
  681. ArrayIndex const size = value.size();
  682. bool isMultiLine = size * 3 >= rightMargin_;
  683. childValues_.clear();
  684. for (ArrayIndex index = 0; index < size && !isMultiLine; ++index) {
  685. const Value& childValue = value[index];
  686. isMultiLine = ((childValue.isArray() || childValue.isObject()) &&
  687. childValue.size() > 0);
  688. }
  689. if (!isMultiLine) // check if line length > max line length
  690. {
  691. childValues_.reserve(size);
  692. addChildValues_ = true;
  693. ArrayIndex lineLength = 4 + (size - 1) * 2; // '[ ' + ', '*n + ' ]'
  694. for (ArrayIndex index = 0; index < size; ++index) {
  695. if (hasCommentForValue(value[index])) {
  696. isMultiLine = true;
  697. }
  698. writeValue(value[index]);
  699. lineLength += static_cast<ArrayIndex>(childValues_[index].length());
  700. }
  701. addChildValues_ = false;
  702. isMultiLine = isMultiLine || lineLength >= rightMargin_;
  703. }
  704. return isMultiLine;
  705. }
  706. void StyledStreamWriter::pushValue(const JSONCPP_STRING& value) {
  707. if (addChildValues_)
  708. childValues_.push_back(value);
  709. else
  710. *document_ << value;
  711. }
  712. void StyledStreamWriter::writeIndent() {
  713. // blep intended this to look at the so-far-written string
  714. // to determine whether we are already indented, but
  715. // with a stream we cannot do that. So we rely on some saved state.
  716. // The caller checks indented_.
  717. *document_ << '\n' << indentString_;
  718. }
  719. void StyledStreamWriter::writeWithIndent(const JSONCPP_STRING& value) {
  720. if (!indented_) writeIndent();
  721. *document_ << value;
  722. indented_ = false;
  723. }
  724. void StyledStreamWriter::indent() { indentString_ += indentation_; }
  725. void StyledStreamWriter::unindent() {
  726. assert(indentString_.size() >= indentation_.size());
  727. indentString_.resize(indentString_.size() - indentation_.size());
  728. }
  729. void StyledStreamWriter::writeCommentBeforeValue(const Value& root) {
  730. if (!root.hasComment(commentBefore))
  731. return;
  732. if (!indented_) writeIndent();
  733. const JSONCPP_STRING& comment = root.getComment(commentBefore);
  734. JSONCPP_STRING::const_iterator iter = comment.begin();
  735. while (iter != comment.end()) {
  736. *document_ << *iter;
  737. if (*iter == '\n' &&
  738. (iter != comment.end() && *(iter + 1) == '/'))
  739. // writeIndent(); // would include newline
  740. *document_ << indentString_;
  741. ++iter;
  742. }
  743. indented_ = false;
  744. }
  745. void StyledStreamWriter::writeCommentAfterValueOnSameLine(const Value& root) {
  746. if (root.hasComment(commentAfterOnSameLine))
  747. *document_ << ' ' << root.getComment(commentAfterOnSameLine);
  748. if (root.hasComment(commentAfter)) {
  749. writeIndent();
  750. *document_ << root.getComment(commentAfter);
  751. }
  752. indented_ = false;
  753. }
  754. bool StyledStreamWriter::hasCommentForValue(const Value& value) {
  755. return value.hasComment(commentBefore) ||
  756. value.hasComment(commentAfterOnSameLine) ||
  757. value.hasComment(commentAfter);
  758. }
  759. //////////////////////////
  760. // BuiltStyledStreamWriter
  761. /// Scoped enums are not available until C++11.
  762. struct CommentStyle {
  763. /// Decide whether to write comments.
  764. enum Enum {
  765. None, ///< Drop all comments.
  766. Most, ///< Recover odd behavior of previous versions (not implemented yet).
  767. All ///< Keep all comments.
  768. };
  769. };
  770. struct BuiltStyledStreamWriter : public StreamWriter
  771. {
  772. BuiltStyledStreamWriter(
  773. JSONCPP_STRING const& indentation,
  774. CommentStyle::Enum cs,
  775. JSONCPP_STRING const& colonSymbol,
  776. JSONCPP_STRING const& nullSymbol,
  777. JSONCPP_STRING const& endingLineFeedSymbol,
  778. bool useSpecialFloats,
  779. unsigned int precision);
  780. int write(Value const& root, JSONCPP_OSTREAM* sout) JSONCPP_OVERRIDE;
  781. private:
  782. void writeValue(Value const& value);
  783. void writeArrayValue(Value const& value);
  784. bool isMultineArray(Value const& value);
  785. void pushValue(JSONCPP_STRING const& value);
  786. void writeIndent();
  787. void writeWithIndent(JSONCPP_STRING const& value);
  788. void indent();
  789. void unindent();
  790. void writeCommentBeforeValue(Value const& root);
  791. void writeCommentAfterValueOnSameLine(Value const& root);
  792. static bool hasCommentForValue(const Value& value);
  793. typedef std::vector<JSONCPP_STRING> ChildValues;
  794. ChildValues childValues_;
  795. JSONCPP_STRING indentString_;
  796. unsigned int rightMargin_;
  797. JSONCPP_STRING indentation_;
  798. CommentStyle::Enum cs_;
  799. JSONCPP_STRING colonSymbol_;
  800. JSONCPP_STRING nullSymbol_;
  801. JSONCPP_STRING endingLineFeedSymbol_;
  802. bool addChildValues_ : 1;
  803. bool indented_ : 1;
  804. bool useSpecialFloats_ : 1;
  805. unsigned int precision_;
  806. };
  807. BuiltStyledStreamWriter::BuiltStyledStreamWriter(
  808. JSONCPP_STRING const& indentation,
  809. CommentStyle::Enum cs,
  810. JSONCPP_STRING const& colonSymbol,
  811. JSONCPP_STRING const& nullSymbol,
  812. JSONCPP_STRING const& endingLineFeedSymbol,
  813. bool useSpecialFloats,
  814. unsigned int precision)
  815. : rightMargin_(74)
  816. , indentation_(indentation)
  817. , cs_(cs)
  818. , colonSymbol_(colonSymbol)
  819. , nullSymbol_(nullSymbol)
  820. , endingLineFeedSymbol_(endingLineFeedSymbol)
  821. , addChildValues_(false)
  822. , indented_(false)
  823. , useSpecialFloats_(useSpecialFloats)
  824. , precision_(precision)
  825. {
  826. }
  827. int BuiltStyledStreamWriter::write(Value const& root, JSONCPP_OSTREAM* sout)
  828. {
  829. sout_ = sout;
  830. addChildValues_ = false;
  831. indented_ = true;
  832. indentString_.clear();
  833. writeCommentBeforeValue(root);
  834. if (!indented_) writeIndent();
  835. indented_ = true;
  836. writeValue(root);
  837. writeCommentAfterValueOnSameLine(root);
  838. *sout_ << endingLineFeedSymbol_;
  839. sout_ = NULL;
  840. return 0;
  841. }
  842. void BuiltStyledStreamWriter::writeValue(Value const& value) {
  843. switch (value.type()) {
  844. case nullValue:
  845. pushValue(nullSymbol_);
  846. break;
  847. case intValue:
  848. pushValue(valueToString(value.asLargestInt()));
  849. break;
  850. case uintValue:
  851. pushValue(valueToString(value.asLargestUInt()));
  852. break;
  853. case realValue:
  854. pushValue(valueToString(value.asDouble(), useSpecialFloats_, precision_));
  855. break;
  856. case stringValue:
  857. {
  858. // Is NULL is possible for value.string_? No.
  859. char const* str;
  860. char const* end;
  861. bool ok = value.getString(&str, &end);
  862. if (ok) pushValue(valueToQuotedStringN(str, static_cast<unsigned>(end-str)));
  863. else pushValue("");
  864. break;
  865. }
  866. case booleanValue:
  867. pushValue(valueToString(value.asBool()));
  868. break;
  869. case arrayValue:
  870. writeArrayValue(value);
  871. break;
  872. case objectValue: {
  873. Value::Members members(value.getMemberNames());
  874. if (members.empty())
  875. pushValue("{}");
  876. else {
  877. writeWithIndent("{");
  878. indent();
  879. Value::Members::iterator it = members.begin();
  880. for (;;) {
  881. JSONCPP_STRING const& name = *it;
  882. Value const& childValue = value[name];
  883. writeCommentBeforeValue(childValue);
  884. writeWithIndent(valueToQuotedStringN(name.data(), static_cast<unsigned>(name.length())));
  885. *sout_ << colonSymbol_;
  886. writeValue(childValue);
  887. if (++it == members.end()) {
  888. writeCommentAfterValueOnSameLine(childValue);
  889. break;
  890. }
  891. *sout_ << ",";
  892. writeCommentAfterValueOnSameLine(childValue);
  893. }
  894. unindent();
  895. writeWithIndent("}");
  896. }
  897. } break;
  898. }
  899. }
  900. void BuiltStyledStreamWriter::writeArrayValue(Value const& value) {
  901. unsigned size = value.size();
  902. if (size == 0)
  903. pushValue("[]");
  904. else {
  905. bool isMultiLine = (cs_ == CommentStyle::All) || isMultineArray(value);
  906. if (isMultiLine) {
  907. writeWithIndent("[");
  908. indent();
  909. bool hasChildValue = !childValues_.empty();
  910. unsigned index = 0;
  911. for (;;) {
  912. Value const& childValue = value[index];
  913. writeCommentBeforeValue(childValue);
  914. if (hasChildValue)
  915. writeWithIndent(childValues_[index]);
  916. else {
  917. if (!indented_) writeIndent();
  918. indented_ = true;
  919. writeValue(childValue);
  920. indented_ = false;
  921. }
  922. if (++index == size) {
  923. writeCommentAfterValueOnSameLine(childValue);
  924. break;
  925. }
  926. *sout_ << ",";
  927. writeCommentAfterValueOnSameLine(childValue);
  928. }
  929. unindent();
  930. writeWithIndent("]");
  931. } else // output on a single line
  932. {
  933. assert(childValues_.size() == size);
  934. *sout_ << "[";
  935. if (!indentation_.empty()) *sout_ << " ";
  936. for (unsigned index = 0; index < size; ++index) {
  937. if (index > 0)
  938. *sout_ << ((!indentation_.empty()) ? ", " : ",");
  939. *sout_ << childValues_[index];
  940. }
  941. if (!indentation_.empty()) *sout_ << " ";
  942. *sout_ << "]";
  943. }
  944. }
  945. }
  946. bool BuiltStyledStreamWriter::isMultineArray(Value const& value) {
  947. ArrayIndex const size = value.size();
  948. bool isMultiLine = size * 3 >= rightMargin_;
  949. childValues_.clear();
  950. for (ArrayIndex index = 0; index < size && !isMultiLine; ++index) {
  951. Value const& childValue = value[index];
  952. isMultiLine = ((childValue.isArray() || childValue.isObject()) &&
  953. childValue.size() > 0);
  954. }
  955. if (!isMultiLine) // check if line length > max line length
  956. {
  957. childValues_.reserve(size);
  958. addChildValues_ = true;
  959. ArrayIndex lineLength = 4 + (size - 1) * 2; // '[ ' + ', '*n + ' ]'
  960. for (ArrayIndex index = 0; index < size; ++index) {
  961. if (hasCommentForValue(value[index])) {
  962. isMultiLine = true;
  963. }
  964. writeValue(value[index]);
  965. lineLength += static_cast<ArrayIndex>(childValues_[index].length());
  966. }
  967. addChildValues_ = false;
  968. isMultiLine = isMultiLine || lineLength >= rightMargin_;
  969. }
  970. return isMultiLine;
  971. }
  972. void BuiltStyledStreamWriter::pushValue(JSONCPP_STRING const& value) {
  973. if (addChildValues_)
  974. childValues_.push_back(value);
  975. else
  976. *sout_ << value;
  977. }
  978. void BuiltStyledStreamWriter::writeIndent() {
  979. // blep intended this to look at the so-far-written string
  980. // to determine whether we are already indented, but
  981. // with a stream we cannot do that. So we rely on some saved state.
  982. // The caller checks indented_.
  983. if (!indentation_.empty()) {
  984. // In this case, drop newlines too.
  985. *sout_ << '\n' << indentString_;
  986. }
  987. }
  988. void BuiltStyledStreamWriter::writeWithIndent(JSONCPP_STRING const& value) {
  989. if (!indented_) writeIndent();
  990. *sout_ << value;
  991. indented_ = false;
  992. }
  993. void BuiltStyledStreamWriter::indent() { indentString_ += indentation_; }
  994. void BuiltStyledStreamWriter::unindent() {
  995. assert(indentString_.size() >= indentation_.size());
  996. indentString_.resize(indentString_.size() - indentation_.size());
  997. }
  998. void BuiltStyledStreamWriter::writeCommentBeforeValue(Value const& root) {
  999. if (cs_ == CommentStyle::None) return;
  1000. if (!root.hasComment(commentBefore))
  1001. return;
  1002. if (!indented_) writeIndent();
  1003. const JSONCPP_STRING& comment = root.getComment(commentBefore);
  1004. JSONCPP_STRING::const_iterator iter = comment.begin();
  1005. while (iter != comment.end()) {
  1006. *sout_ << *iter;
  1007. if (*iter == '\n' &&
  1008. (iter != comment.end() && *(iter + 1) == '/'))
  1009. // writeIndent(); // would write extra newline
  1010. *sout_ << indentString_;
  1011. ++iter;
  1012. }
  1013. indented_ = false;
  1014. }
  1015. void BuiltStyledStreamWriter::writeCommentAfterValueOnSameLine(Value const& root) {
  1016. if (cs_ == CommentStyle::None) return;
  1017. if (root.hasComment(commentAfterOnSameLine))
  1018. *sout_ << " " + root.getComment(commentAfterOnSameLine);
  1019. if (root.hasComment(commentAfter)) {
  1020. writeIndent();
  1021. *sout_ << root.getComment(commentAfter);
  1022. }
  1023. }
  1024. // static
  1025. bool BuiltStyledStreamWriter::hasCommentForValue(const Value& value) {
  1026. return value.hasComment(commentBefore) ||
  1027. value.hasComment(commentAfterOnSameLine) ||
  1028. value.hasComment(commentAfter);
  1029. }
  1030. ///////////////
  1031. // StreamWriter
  1032. StreamWriter::StreamWriter()
  1033. : sout_(NULL)
  1034. {
  1035. }
  1036. StreamWriter::~StreamWriter()
  1037. {
  1038. }
  1039. StreamWriter::Factory::~Factory()
  1040. {}
  1041. StreamWriterBuilder::StreamWriterBuilder()
  1042. {
  1043. setDefaults(&settings_);
  1044. }
  1045. StreamWriterBuilder::~StreamWriterBuilder()
  1046. {}
  1047. StreamWriter* StreamWriterBuilder::newStreamWriter() const
  1048. {
  1049. JSONCPP_STRING indentation = settings_["indentation"].asString();
  1050. JSONCPP_STRING cs_str = settings_["commentStyle"].asString();
  1051. bool eyc = settings_["enableYAMLCompatibility"].asBool();
  1052. bool dnp = settings_["dropNullPlaceholders"].asBool();
  1053. bool usf = settings_["useSpecialFloats"].asBool();
  1054. unsigned int pre = settings_["precision"].asUInt();
  1055. CommentStyle::Enum cs = CommentStyle::All;
  1056. if (cs_str == "All") {
  1057. cs = CommentStyle::All;
  1058. } else if (cs_str == "None") {
  1059. cs = CommentStyle::None;
  1060. } else {
  1061. throwRuntimeError("commentStyle must be 'All' or 'None'");
  1062. }
  1063. JSONCPP_STRING colonSymbol = " : ";
  1064. if (eyc) {
  1065. colonSymbol = ": ";
  1066. } else if (indentation.empty()) {
  1067. colonSymbol = ":";
  1068. }
  1069. JSONCPP_STRING nullSymbol = "null";
  1070. if (dnp) {
  1071. nullSymbol.clear();
  1072. }
  1073. if (pre > 17) pre = 17;
  1074. JSONCPP_STRING endingLineFeedSymbol;
  1075. return new BuiltStyledStreamWriter(
  1076. indentation, cs,
  1077. colonSymbol, nullSymbol, endingLineFeedSymbol, usf, pre);
  1078. }
  1079. static void getValidWriterKeys(std::set<JSONCPP_STRING>* valid_keys)
  1080. {
  1081. valid_keys->clear();
  1082. valid_keys->insert("indentation");
  1083. valid_keys->insert("commentStyle");
  1084. valid_keys->insert("enableYAMLCompatibility");
  1085. valid_keys->insert("dropNullPlaceholders");
  1086. valid_keys->insert("useSpecialFloats");
  1087. valid_keys->insert("precision");
  1088. }
  1089. bool StreamWriterBuilder::validate(Json::Value* invalid) const
  1090. {
  1091. Json::Value my_invalid;
  1092. if (!invalid) invalid = &my_invalid; // so we do not need to test for NULL
  1093. Json::Value& inv = *invalid;
  1094. std::set<JSONCPP_STRING> valid_keys;
  1095. getValidWriterKeys(&valid_keys);
  1096. Value::Members keys = settings_.getMemberNames();
  1097. size_t n = keys.size();
  1098. for (size_t i = 0; i < n; ++i) {
  1099. JSONCPP_STRING const& key = keys[i];
  1100. if (valid_keys.find(key) == valid_keys.end()) {
  1101. inv[key] = settings_[key];
  1102. }
  1103. }
  1104. return 0u == inv.size();
  1105. }
  1106. Value& StreamWriterBuilder::operator[](JSONCPP_STRING key)
  1107. {
  1108. return settings_[key];
  1109. }
  1110. // static
  1111. void StreamWriterBuilder::setDefaults(Json::Value* settings)
  1112. {
  1113. //! [StreamWriterBuilderDefaults]
  1114. (*settings)["commentStyle"] = "All";
  1115. (*settings)["indentation"] = "\t";
  1116. (*settings)["enableYAMLCompatibility"] = false;
  1117. (*settings)["dropNullPlaceholders"] = false;
  1118. (*settings)["useSpecialFloats"] = false;
  1119. (*settings)["precision"] = 17;
  1120. //! [StreamWriterBuilderDefaults]
  1121. }
  1122. JSONCPP_STRING writeString(StreamWriter::Factory const& builder, Value const& root) {
  1123. JSONCPP_OSTRINGSTREAM sout;
  1124. StreamWriterPtr const writer(builder.newStreamWriter());
  1125. writer->write(root, &sout);
  1126. return sout.str();
  1127. }
  1128. JSONCPP_OSTREAM& operator<<(JSONCPP_OSTREAM& sout, Value const& root) {
  1129. StreamWriterBuilder builder;
  1130. StreamWriterPtr const writer(builder.newStreamWriter());
  1131. writer->write(root, &sout);
  1132. return sout;
  1133. }
  1134. } // namespace Json