writer.h 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811
  1. // Tencent is pleased to support the open source community by making RapidJSON
  2. // available.
  3. //
  4. // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All
  5. // rights reserved.
  6. //
  7. // Licensed under the MIT License (the "License"); you may not use this file
  8. // except in compliance with the License. You may obtain a copy of the License
  9. // at
  10. //
  11. // http://opensource.org/licenses/MIT
  12. //
  13. // Unless required by applicable law or agreed to in writing, software
  14. // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  15. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  16. // License for the specific language governing permissions and limitations under
  17. // the License.
  18. #ifndef RAPIDJSON_WRITER_H_
  19. #define RAPIDJSON_WRITER_H_
  20. #include <new> // placement new
  21. #include "internal/clzll.h"
  22. #include "internal/dtoa.h"
  23. #include "internal/itoa.h"
  24. #include "internal/meta.h"
  25. #include "internal/stack.h"
  26. #include "internal/strfunc.h"
  27. #include "stream.h"
  28. #include "stringbuffer.h"
  29. #if defined(RAPIDJSON_SIMD) && defined(_MSC_VER)
  30. #include <intrin.h>
  31. #pragma intrinsic(_BitScanForward)
  32. #endif
  33. #ifdef RAPIDJSON_SSE42
  34. #include <nmmintrin.h>
  35. #elif defined(RAPIDJSON_SSE2)
  36. #include <emmintrin.h>
  37. #elif defined(RAPIDJSON_NEON)
  38. #include <arm_neon.h>
  39. #endif
  40. #ifdef __clang__
  41. RAPIDJSON_DIAG_PUSH
  42. RAPIDJSON_DIAG_OFF(padded)
  43. RAPIDJSON_DIAG_OFF(unreachable - code)
  44. RAPIDJSON_DIAG_OFF(c++ 98 - compat)
  45. #elif defined(_MSC_VER)
  46. RAPIDJSON_DIAG_PUSH
  47. RAPIDJSON_DIAG_OFF(4127) // conditional expression is constant
  48. #endif
  49. RAPIDJSON_NAMESPACE_BEGIN
  50. ///////////////////////////////////////////////////////////////////////////////
  51. // WriteFlag
  52. /*! \def RAPIDJSON_WRITE_DEFAULT_FLAGS
  53. \ingroup RAPIDJSON_CONFIG
  54. \brief User-defined kWriteDefaultFlags definition.
  55. User can define this as any \c WriteFlag combinations.
  56. */
  57. #ifndef RAPIDJSON_WRITE_DEFAULT_FLAGS
  58. #define RAPIDJSON_WRITE_DEFAULT_FLAGS kWriteNoFlags
  59. #endif
  60. //! Combination of writeFlags
  61. enum WriteFlag {
  62. kWriteNoFlags = 0, //!< No flags are set.
  63. kWriteValidateEncodingFlag = 1, //!< Validate encoding of JSON strings.
  64. kWriteNanAndInfFlag = 2, //!< Allow writing of Infinity, -Infinity and NaN.
  65. kWriteDefaultFlags =
  66. RAPIDJSON_WRITE_DEFAULT_FLAGS //!< Default write flags. Can be customized
  67. //!< by defining
  68. //!< RAPIDJSON_WRITE_DEFAULT_FLAGS
  69. };
  70. //! JSON writer
  71. /*! Writer implements the concept Handler.
  72. It generates JSON text by events to an output os.
  73. User may programmatically calls the functions of a writer to generate JSON
  74. text.
  75. On the other side, a writer can also be passed to objects that generates
  76. events,
  77. for example Reader::Parse() and Document::Accept().
  78. \tparam OutputStream Type of output stream.
  79. \tparam SourceEncoding Encoding of source string.
  80. \tparam TargetEncoding Encoding of output stream.
  81. \tparam StackAllocator Type of allocator for allocating memory of stack.
  82. \note implements Handler concept
  83. */
  84. template <typename OutputStream, typename SourceEncoding = UTF8<>,
  85. typename TargetEncoding = UTF8<>,
  86. typename StackAllocator = CrtAllocator,
  87. unsigned writeFlags = kWriteDefaultFlags>
  88. class Writer {
  89. public:
  90. typedef typename SourceEncoding::Ch Ch;
  91. static const int kDefaultMaxDecimalPlaces = 324;
  92. //! Constructor
  93. /*! \param os Output stream.
  94. \param stackAllocator User supplied allocator. If it is null, it will
  95. create a private one. \param levelDepth Initial capacity of stack.
  96. */
  97. explicit Writer(OutputStream &os, StackAllocator *stackAllocator = 0,
  98. size_t levelDepth = kDefaultLevelDepth)
  99. : os_(&os),
  100. level_stack_(stackAllocator, levelDepth * sizeof(Level)),
  101. maxDecimalPlaces_(kDefaultMaxDecimalPlaces),
  102. hasRoot_(false) {}
  103. explicit Writer(StackAllocator *allocator = 0,
  104. size_t levelDepth = kDefaultLevelDepth)
  105. : os_(0),
  106. level_stack_(allocator, levelDepth * sizeof(Level)),
  107. maxDecimalPlaces_(kDefaultMaxDecimalPlaces),
  108. hasRoot_(false) {}
  109. #if RAPIDJSON_HAS_CXX11_RVALUE_REFS
  110. Writer(Writer &&rhs)
  111. : os_(rhs.os_),
  112. level_stack_(std::move(rhs.level_stack_)),
  113. maxDecimalPlaces_(rhs.maxDecimalPlaces_),
  114. hasRoot_(rhs.hasRoot_) {
  115. rhs.os_ = 0;
  116. }
  117. #endif
  118. //! Reset the writer with a new stream.
  119. /*!
  120. This function reset the writer with a new stream and default settings,
  121. in order to make a Writer object reusable for output multiple JSONs.
  122. \param os New output stream.
  123. \code
  124. Writer<OutputStream> writer(os1);
  125. writer.StartObject();
  126. // ...
  127. writer.EndObject();
  128. writer.Reset(os2);
  129. writer.StartObject();
  130. // ...
  131. writer.EndObject();
  132. \endcode
  133. */
  134. void Reset(OutputStream &os) {
  135. os_ = &os;
  136. hasRoot_ = false;
  137. level_stack_.Clear();
  138. }
  139. //! Checks whether the output is a complete JSON.
  140. /*!
  141. A complete JSON has a complete root object or array.
  142. */
  143. bool IsComplete() const { return hasRoot_ && level_stack_.Empty(); }
  144. int GetMaxDecimalPlaces() const { return maxDecimalPlaces_; }
  145. //! Sets the maximum number of decimal places for double output.
  146. /*!
  147. This setting truncates the output with specified number of decimal places.
  148. For example,
  149. \code
  150. writer.SetMaxDecimalPlaces(3);
  151. writer.StartArray();
  152. writer.Double(0.12345); // "0.123"
  153. writer.Double(0.0001); // "0.0"
  154. writer.Double(1.234567890123456e30); // "1.234567890123456e30" (do not
  155. truncate significand for positive exponent) writer.Double(1.23e-4); //
  156. "0.0" (do truncate significand for negative exponent)
  157. writer.EndArray();
  158. \endcode
  159. The default setting does not truncate any decimal places. You can restore
  160. to this setting by calling \code
  161. writer.SetMaxDecimalPlaces(Writer::kDefaultMaxDecimalPlaces);
  162. \endcode
  163. */
  164. void SetMaxDecimalPlaces(int maxDecimalPlaces) {
  165. maxDecimalPlaces_ = maxDecimalPlaces;
  166. }
  167. /*!@name Implementation of Handler
  168. \see Handler
  169. */
  170. //@{
  171. bool Null() {
  172. Prefix(kNullType);
  173. return EndValue(WriteNull());
  174. }
  175. bool Bool(bool b) {
  176. Prefix(b ? kTrueType : kFalseType);
  177. return EndValue(WriteBool(b));
  178. }
  179. bool Int(int i) {
  180. Prefix(kNumberType);
  181. return EndValue(WriteInt(i));
  182. }
  183. bool Uint(unsigned u) {
  184. Prefix(kNumberType);
  185. return EndValue(WriteUint(u));
  186. }
  187. bool Int64(int64_t i64) {
  188. Prefix(kNumberType);
  189. return EndValue(WriteInt64(i64));
  190. }
  191. bool Uint64(uint64_t u64) {
  192. Prefix(kNumberType);
  193. return EndValue(WriteUint64(u64));
  194. }
  195. //! Writes the given \c double value to the stream
  196. /*!
  197. \param d The value to be written.
  198. \return Whether it is succeed.
  199. */
  200. bool Double(double d) {
  201. Prefix(kNumberType);
  202. return EndValue(WriteDouble(d));
  203. }
  204. bool RawNumber(const Ch *str, SizeType length, bool copy = false) {
  205. RAPIDJSON_ASSERT(str != 0);
  206. (void)copy;
  207. Prefix(kNumberType);
  208. return EndValue(WriteString(str, length));
  209. }
  210. bool String(const Ch *str, SizeType length, bool copy = false) {
  211. RAPIDJSON_ASSERT(str != 0);
  212. (void)copy;
  213. Prefix(kStringType);
  214. return EndValue(WriteString(str, length));
  215. }
  216. #if RAPIDJSON_HAS_STDSTRING
  217. bool String(const std::basic_string<Ch> &str) {
  218. return String(str.data(), SizeType(str.size()));
  219. }
  220. #endif
  221. bool StartObject() {
  222. Prefix(kObjectType);
  223. new (level_stack_.template Push<Level>()) Level(false);
  224. return WriteStartObject();
  225. }
  226. bool Key(const Ch *str, SizeType length, bool copy = false) {
  227. return String(str, length, copy);
  228. }
  229. #if RAPIDJSON_HAS_STDSTRING
  230. bool Key(const std::basic_string<Ch> &str) {
  231. return Key(str.data(), SizeType(str.size()));
  232. }
  233. #endif
  234. bool EndObject(SizeType memberCount = 0) {
  235. (void)memberCount;
  236. RAPIDJSON_ASSERT(level_stack_.GetSize() >=
  237. sizeof(Level)); // not inside an Object
  238. RAPIDJSON_ASSERT(!level_stack_.template Top<Level>()
  239. ->inArray); // currently inside an Array, not Object
  240. RAPIDJSON_ASSERT(0 ==
  241. level_stack_.template Top<Level>()->valueCount %
  242. 2); // Object has a Key without a Value
  243. level_stack_.template Pop<Level>(1);
  244. return EndValue(WriteEndObject());
  245. }
  246. bool StartArray() {
  247. Prefix(kArrayType);
  248. new (level_stack_.template Push<Level>()) Level(true);
  249. return WriteStartArray();
  250. }
  251. bool EndArray(SizeType elementCount = 0) {
  252. (void)elementCount;
  253. RAPIDJSON_ASSERT(level_stack_.GetSize() >= sizeof(Level));
  254. RAPIDJSON_ASSERT(level_stack_.template Top<Level>()->inArray);
  255. level_stack_.template Pop<Level>(1);
  256. return EndValue(WriteEndArray());
  257. }
  258. //@}
  259. /*! @name Convenience extensions */
  260. //@{
  261. //! Simpler but slower overload.
  262. bool String(const Ch *const &str) {
  263. return String(str, internal::StrLen(str));
  264. }
  265. bool Key(const Ch *const &str) { return Key(str, internal::StrLen(str)); }
  266. //@}
  267. //! Write a raw JSON value.
  268. /*!
  269. For user to write a stringified JSON as a value.
  270. \param json A well-formed JSON value. It should not contain null character
  271. within [0, length - 1] range. \param length Length of the json. \param type
  272. Type of the root of json.
  273. */
  274. bool RawValue(const Ch *json, size_t length, Type type) {
  275. RAPIDJSON_ASSERT(json != 0);
  276. Prefix(type);
  277. return EndValue(WriteRawValue(json, length));
  278. }
  279. //! Flush the output stream.
  280. /*!
  281. Allows the user to flush the output stream immediately.
  282. */
  283. void Flush() { os_->Flush(); }
  284. protected:
  285. //! Information for each nested level
  286. struct Level {
  287. Level(bool inArray_) : valueCount(0), inArray(inArray_) {}
  288. size_t valueCount; //!< number of values in this level
  289. bool inArray; //!< true if in array, otherwise in object
  290. };
  291. static const size_t kDefaultLevelDepth = 32;
  292. bool WriteNull() {
  293. PutReserve(*os_, 4);
  294. PutUnsafe(*os_, 'n');
  295. PutUnsafe(*os_, 'u');
  296. PutUnsafe(*os_, 'l');
  297. PutUnsafe(*os_, 'l');
  298. return true;
  299. }
  300. bool WriteBool(bool b) {
  301. if (b) {
  302. PutReserve(*os_, 4);
  303. PutUnsafe(*os_, 't');
  304. PutUnsafe(*os_, 'r');
  305. PutUnsafe(*os_, 'u');
  306. PutUnsafe(*os_, 'e');
  307. } else {
  308. PutReserve(*os_, 5);
  309. PutUnsafe(*os_, 'f');
  310. PutUnsafe(*os_, 'a');
  311. PutUnsafe(*os_, 'l');
  312. PutUnsafe(*os_, 's');
  313. PutUnsafe(*os_, 'e');
  314. }
  315. return true;
  316. }
  317. bool WriteInt(int i) {
  318. char buffer[11];
  319. const char *end = internal::i32toa(i, buffer);
  320. PutReserve(*os_, static_cast<size_t>(end - buffer));
  321. for (const char *p = buffer; p != end; ++p)
  322. PutUnsafe(*os_, static_cast<typename OutputStream::Ch>(*p));
  323. return true;
  324. }
  325. bool WriteUint(unsigned u) {
  326. char buffer[10];
  327. const char *end = internal::u32toa(u, buffer);
  328. PutReserve(*os_, static_cast<size_t>(end - buffer));
  329. for (const char *p = buffer; p != end; ++p)
  330. PutUnsafe(*os_, static_cast<typename OutputStream::Ch>(*p));
  331. return true;
  332. }
  333. bool WriteInt64(int64_t i64) {
  334. char buffer[21];
  335. const char *end = internal::i64toa(i64, buffer);
  336. PutReserve(*os_, static_cast<size_t>(end - buffer));
  337. for (const char *p = buffer; p != end; ++p)
  338. PutUnsafe(*os_, static_cast<typename OutputStream::Ch>(*p));
  339. return true;
  340. }
  341. bool WriteUint64(uint64_t u64) {
  342. char buffer[20];
  343. char *end = internal::u64toa(u64, buffer);
  344. PutReserve(*os_, static_cast<size_t>(end - buffer));
  345. for (char *p = buffer; p != end; ++p)
  346. PutUnsafe(*os_, static_cast<typename OutputStream::Ch>(*p));
  347. return true;
  348. }
  349. bool WriteDouble(double d) {
  350. if (internal::Double(d).IsNanOrInf()) {
  351. if (!(writeFlags & kWriteNanAndInfFlag)) return false;
  352. if (internal::Double(d).IsNan()) {
  353. PutReserve(*os_, 3);
  354. PutUnsafe(*os_, 'N');
  355. PutUnsafe(*os_, 'a');
  356. PutUnsafe(*os_, 'N');
  357. return true;
  358. }
  359. if (internal::Double(d).Sign()) {
  360. PutReserve(*os_, 9);
  361. PutUnsafe(*os_, '-');
  362. } else
  363. PutReserve(*os_, 8);
  364. PutUnsafe(*os_, 'I');
  365. PutUnsafe(*os_, 'n');
  366. PutUnsafe(*os_, 'f');
  367. PutUnsafe(*os_, 'i');
  368. PutUnsafe(*os_, 'n');
  369. PutUnsafe(*os_, 'i');
  370. PutUnsafe(*os_, 't');
  371. PutUnsafe(*os_, 'y');
  372. return true;
  373. }
  374. char buffer[25];
  375. char *end = internal::dtoa(d, buffer, maxDecimalPlaces_);
  376. PutReserve(*os_, static_cast<size_t>(end - buffer));
  377. for (char *p = buffer; p != end; ++p)
  378. PutUnsafe(*os_, static_cast<typename OutputStream::Ch>(*p));
  379. return true;
  380. }
  381. bool WriteString(const Ch *str, SizeType length) {
  382. static const typename OutputStream::Ch hexDigits[16] = {
  383. '0', '1', '2', '3', '4', '5', '6', '7',
  384. '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
  385. static const char escape[256] = {
  386. #define Z16 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  387. // 0 1 2 3 4 5 6 7 8 9 A B C D E
  388. // F
  389. 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'b', 't',
  390. 'n', 'u', 'f', 'r', 'u', 'u', // 00
  391. 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u',
  392. 'u', 'u', 'u', 'u', 'u', 'u', // 10
  393. 0, 0, '"', 0, 0, 0, 0, 0, 0, 0,
  394. 0, 0, 0, 0, 0, 0, // 20
  395. Z16, Z16, // 30~4F
  396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  397. 0, 0, '\\', 0, 0, 0, // 50
  398. Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16 // 60~FF
  399. #undef Z16
  400. };
  401. if (TargetEncoding::supportUnicode)
  402. PutReserve(*os_, 2 + length * 6); // "\uxxxx..."
  403. else
  404. PutReserve(*os_, 2 + length * 12); // "\uxxxx\uyyyy..."
  405. PutUnsafe(*os_, '\"');
  406. GenericStringStream<SourceEncoding> is(str);
  407. while (ScanWriteUnescapedString(is, length)) {
  408. const Ch c = is.Peek();
  409. if (!TargetEncoding::supportUnicode && static_cast<unsigned>(c) >= 0x80) {
  410. // Unicode escaping
  411. unsigned codepoint;
  412. if (RAPIDJSON_UNLIKELY(!SourceEncoding::Decode(is, &codepoint)))
  413. return false;
  414. PutUnsafe(*os_, '\\');
  415. PutUnsafe(*os_, 'u');
  416. if (codepoint <= 0xD7FF ||
  417. (codepoint >= 0xE000 && codepoint <= 0xFFFF)) {
  418. PutUnsafe(*os_, hexDigits[(codepoint >> 12) & 15]);
  419. PutUnsafe(*os_, hexDigits[(codepoint >> 8) & 15]);
  420. PutUnsafe(*os_, hexDigits[(codepoint >> 4) & 15]);
  421. PutUnsafe(*os_, hexDigits[(codepoint)&15]);
  422. } else {
  423. RAPIDJSON_ASSERT(codepoint >= 0x010000 && codepoint <= 0x10FFFF);
  424. // Surrogate pair
  425. unsigned s = codepoint - 0x010000;
  426. unsigned lead = (s >> 10) + 0xD800;
  427. unsigned trail = (s & 0x3FF) + 0xDC00;
  428. PutUnsafe(*os_, hexDigits[(lead >> 12) & 15]);
  429. PutUnsafe(*os_, hexDigits[(lead >> 8) & 15]);
  430. PutUnsafe(*os_, hexDigits[(lead >> 4) & 15]);
  431. PutUnsafe(*os_, hexDigits[(lead)&15]);
  432. PutUnsafe(*os_, '\\');
  433. PutUnsafe(*os_, 'u');
  434. PutUnsafe(*os_, hexDigits[(trail >> 12) & 15]);
  435. PutUnsafe(*os_, hexDigits[(trail >> 8) & 15]);
  436. PutUnsafe(*os_, hexDigits[(trail >> 4) & 15]);
  437. PutUnsafe(*os_, hexDigits[(trail)&15]);
  438. }
  439. } else if ((sizeof(Ch) == 1 || static_cast<unsigned>(c) < 256) &&
  440. RAPIDJSON_UNLIKELY(escape[static_cast<unsigned char>(c)])) {
  441. is.Take();
  442. PutUnsafe(*os_, '\\');
  443. PutUnsafe(*os_, static_cast<typename OutputStream::Ch>(
  444. escape[static_cast<unsigned char>(c)]));
  445. if (escape[static_cast<unsigned char>(c)] == 'u') {
  446. PutUnsafe(*os_, '0');
  447. PutUnsafe(*os_, '0');
  448. PutUnsafe(*os_, hexDigits[static_cast<unsigned char>(c) >> 4]);
  449. PutUnsafe(*os_, hexDigits[static_cast<unsigned char>(c) & 0xF]);
  450. }
  451. } else if (RAPIDJSON_UNLIKELY(!(
  452. writeFlags & kWriteValidateEncodingFlag
  453. ? Transcoder<SourceEncoding, TargetEncoding>::Validate(
  454. is, *os_)
  455. : Transcoder<SourceEncoding,
  456. TargetEncoding>::TranscodeUnsafe(is,
  457. *os_))))
  458. return false;
  459. }
  460. PutUnsafe(*os_, '\"');
  461. return true;
  462. }
  463. bool ScanWriteUnescapedString(GenericStringStream<SourceEncoding> &is,
  464. size_t length) {
  465. return RAPIDJSON_LIKELY(is.Tell() < length);
  466. }
  467. bool WriteStartObject() {
  468. os_->Put('{');
  469. return true;
  470. }
  471. bool WriteEndObject() {
  472. os_->Put('}');
  473. return true;
  474. }
  475. bool WriteStartArray() {
  476. os_->Put('[');
  477. return true;
  478. }
  479. bool WriteEndArray() {
  480. os_->Put(']');
  481. return true;
  482. }
  483. bool WriteRawValue(const Ch *json, size_t length) {
  484. PutReserve(*os_, length);
  485. GenericStringStream<SourceEncoding> is(json);
  486. while (RAPIDJSON_LIKELY(is.Tell() < length)) {
  487. RAPIDJSON_ASSERT(is.Peek() != '\0');
  488. if (RAPIDJSON_UNLIKELY(!(
  489. writeFlags & kWriteValidateEncodingFlag
  490. ? Transcoder<SourceEncoding, TargetEncoding>::Validate(is,
  491. *os_)
  492. : Transcoder<SourceEncoding, TargetEncoding>::TranscodeUnsafe(
  493. is, *os_))))
  494. return false;
  495. }
  496. return true;
  497. }
  498. void Prefix(Type type) {
  499. (void)type;
  500. if (RAPIDJSON_LIKELY(level_stack_.GetSize() !=
  501. 0)) { // this value is not at root
  502. Level *level = level_stack_.template Top<Level>();
  503. if (level->valueCount > 0) {
  504. if (level->inArray)
  505. os_->Put(','); // add comma if it is not the first element in array
  506. else // in object
  507. os_->Put((level->valueCount % 2 == 0) ? ',' : ':');
  508. }
  509. if (!level->inArray && level->valueCount % 2 == 0)
  510. RAPIDJSON_ASSERT(type == kStringType); // if it's in object, then even
  511. // number should be a name
  512. level->valueCount++;
  513. } else {
  514. RAPIDJSON_ASSERT(!hasRoot_); // Should only has one and only one root.
  515. hasRoot_ = true;
  516. }
  517. }
  518. // Flush the value if it is the top level one.
  519. bool EndValue(bool ret) {
  520. if (RAPIDJSON_UNLIKELY(level_stack_.Empty())) // end of json text
  521. Flush();
  522. return ret;
  523. }
  524. OutputStream *os_;
  525. internal::Stack<StackAllocator> level_stack_;
  526. int maxDecimalPlaces_;
  527. bool hasRoot_;
  528. private:
  529. // Prohibit copy constructor & assignment operator.
  530. Writer(const Writer &);
  531. Writer &operator=(const Writer &);
  532. };
  533. // Full specialization for StringStream to prevent memory copying
  534. template <>
  535. inline bool Writer<StringBuffer>::WriteInt(int i) {
  536. char *buffer = os_->Push(11);
  537. const char *end = internal::i32toa(i, buffer);
  538. os_->Pop(static_cast<size_t>(11 - (end - buffer)));
  539. return true;
  540. }
  541. template <>
  542. inline bool Writer<StringBuffer>::WriteUint(unsigned u) {
  543. char *buffer = os_->Push(10);
  544. const char *end = internal::u32toa(u, buffer);
  545. os_->Pop(static_cast<size_t>(10 - (end - buffer)));
  546. return true;
  547. }
  548. template <>
  549. inline bool Writer<StringBuffer>::WriteInt64(int64_t i64) {
  550. char *buffer = os_->Push(21);
  551. const char *end = internal::i64toa(i64, buffer);
  552. os_->Pop(static_cast<size_t>(21 - (end - buffer)));
  553. return true;
  554. }
  555. template <>
  556. inline bool Writer<StringBuffer>::WriteUint64(uint64_t u) {
  557. char *buffer = os_->Push(20);
  558. const char *end = internal::u64toa(u, buffer);
  559. os_->Pop(static_cast<size_t>(20 - (end - buffer)));
  560. return true;
  561. }
  562. template <>
  563. inline bool Writer<StringBuffer>::WriteDouble(double d) {
  564. if (internal::Double(d).IsNanOrInf()) {
  565. // Note: This code path can only be reached if
  566. // (RAPIDJSON_WRITE_DEFAULT_FLAGS & kWriteNanAndInfFlag).
  567. if (!(kWriteDefaultFlags & kWriteNanAndInfFlag)) return false;
  568. if (internal::Double(d).IsNan()) {
  569. PutReserve(*os_, 3);
  570. PutUnsafe(*os_, 'N');
  571. PutUnsafe(*os_, 'a');
  572. PutUnsafe(*os_, 'N');
  573. return true;
  574. }
  575. if (internal::Double(d).Sign()) {
  576. PutReserve(*os_, 9);
  577. PutUnsafe(*os_, '-');
  578. } else
  579. PutReserve(*os_, 8);
  580. PutUnsafe(*os_, 'I');
  581. PutUnsafe(*os_, 'n');
  582. PutUnsafe(*os_, 'f');
  583. PutUnsafe(*os_, 'i');
  584. PutUnsafe(*os_, 'n');
  585. PutUnsafe(*os_, 'i');
  586. PutUnsafe(*os_, 't');
  587. PutUnsafe(*os_, 'y');
  588. return true;
  589. }
  590. char *buffer = os_->Push(25);
  591. char *end = internal::dtoa(d, buffer, maxDecimalPlaces_);
  592. os_->Pop(static_cast<size_t>(25 - (end - buffer)));
  593. return true;
  594. }
  595. #if defined(RAPIDJSON_SSE2) || defined(RAPIDJSON_SSE42)
  596. template <>
  597. inline bool Writer<StringBuffer>::ScanWriteUnescapedString(StringStream &is,
  598. size_t length) {
  599. if (length < 16) return RAPIDJSON_LIKELY(is.Tell() < length);
  600. if (!RAPIDJSON_LIKELY(is.Tell() < length)) return false;
  601. const char *p = is.src_;
  602. const char *end = is.head_ + length;
  603. const char *nextAligned = reinterpret_cast<const char *>(
  604. (reinterpret_cast<size_t>(p) + 15) & static_cast<size_t>(~15));
  605. const char *endAligned = reinterpret_cast<const char *>(
  606. reinterpret_cast<size_t>(end) & static_cast<size_t>(~15));
  607. if (nextAligned > end) return true;
  608. while (p != nextAligned)
  609. if (*p < 0x20 || *p == '\"' || *p == '\\') {
  610. is.src_ = p;
  611. return RAPIDJSON_LIKELY(is.Tell() < length);
  612. } else
  613. os_->PutUnsafe(*p++);
  614. // The rest of string using SIMD
  615. static const char dquote[16] = {'\"', '\"', '\"', '\"', '\"', '\"',
  616. '\"', '\"', '\"', '\"', '\"', '\"',
  617. '\"', '\"', '\"', '\"'};
  618. static const char bslash[16] = {'\\', '\\', '\\', '\\', '\\', '\\',
  619. '\\', '\\', '\\', '\\', '\\', '\\',
  620. '\\', '\\', '\\', '\\'};
  621. static const char space[16] = {0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F,
  622. 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F,
  623. 0x1F, 0x1F, 0x1F, 0x1F};
  624. const __m128i dq =
  625. _mm_loadu_si128(reinterpret_cast<const __m128i *>(&dquote[0]));
  626. const __m128i bs =
  627. _mm_loadu_si128(reinterpret_cast<const __m128i *>(&bslash[0]));
  628. const __m128i sp =
  629. _mm_loadu_si128(reinterpret_cast<const __m128i *>(&space[0]));
  630. for (; p != endAligned; p += 16) {
  631. const __m128i s = _mm_load_si128(reinterpret_cast<const __m128i *>(p));
  632. const __m128i t1 = _mm_cmpeq_epi8(s, dq);
  633. const __m128i t2 = _mm_cmpeq_epi8(s, bs);
  634. const __m128i t3 = _mm_cmpeq_epi8(_mm_max_epu8(s, sp),
  635. sp); // s < 0x20 <=> max(s, 0x1F) == 0x1F
  636. const __m128i x = _mm_or_si128(_mm_or_si128(t1, t2), t3);
  637. unsigned short r = static_cast<unsigned short>(_mm_movemask_epi8(x));
  638. if (RAPIDJSON_UNLIKELY(r != 0)) { // some of characters is escaped
  639. SizeType len;
  640. #ifdef _MSC_VER // Find the index of first escaped
  641. unsigned long offset;
  642. _BitScanForward(&offset, r);
  643. len = offset;
  644. #else
  645. len = static_cast<SizeType>(__builtin_ffs(r) - 1);
  646. #endif
  647. char *q = reinterpret_cast<char *>(os_->PushUnsafe(len));
  648. for (size_t i = 0; i < len; i++) q[i] = p[i];
  649. p += len;
  650. break;
  651. }
  652. _mm_storeu_si128(reinterpret_cast<__m128i *>(os_->PushUnsafe(16)), s);
  653. }
  654. is.src_ = p;
  655. return RAPIDJSON_LIKELY(is.Tell() < length);
  656. }
  657. #elif defined(RAPIDJSON_NEON)
  658. template <>
  659. inline bool Writer<StringBuffer>::ScanWriteUnescapedString(StringStream &is,
  660. size_t length) {
  661. if (length < 16) return RAPIDJSON_LIKELY(is.Tell() < length);
  662. if (!RAPIDJSON_LIKELY(is.Tell() < length)) return false;
  663. const char *p = is.src_;
  664. const char *end = is.head_ + length;
  665. const char *nextAligned = reinterpret_cast<const char *>(
  666. (reinterpret_cast<size_t>(p) + 15) & static_cast<size_t>(~15));
  667. const char *endAligned = reinterpret_cast<const char *>(
  668. reinterpret_cast<size_t>(end) & static_cast<size_t>(~15));
  669. if (nextAligned > end) return true;
  670. while (p != nextAligned)
  671. if (*p < 0x20 || *p == '\"' || *p == '\\') {
  672. is.src_ = p;
  673. return RAPIDJSON_LIKELY(is.Tell() < length);
  674. } else
  675. os_->PutUnsafe(*p++);
  676. // The rest of string using SIMD
  677. const uint8x16_t s0 = vmovq_n_u8('"');
  678. const uint8x16_t s1 = vmovq_n_u8('\\');
  679. const uint8x16_t s2 = vmovq_n_u8('\b');
  680. const uint8x16_t s3 = vmovq_n_u8(32);
  681. for (; p != endAligned; p += 16) {
  682. const uint8x16_t s = vld1q_u8(reinterpret_cast<const uint8_t *>(p));
  683. uint8x16_t x = vceqq_u8(s, s0);
  684. x = vorrq_u8(x, vceqq_u8(s, s1));
  685. x = vorrq_u8(x, vceqq_u8(s, s2));
  686. x = vorrq_u8(x, vcltq_u8(s, s3));
  687. x = vrev64q_u8(x); // Rev in 64
  688. uint64_t low = vgetq_lane_u64(vreinterpretq_u64_u8(x), 0); // extract
  689. uint64_t high = vgetq_lane_u64(vreinterpretq_u64_u8(x), 1); // extract
  690. SizeType len = 0;
  691. bool escaped = false;
  692. if (low == 0) {
  693. if (high != 0) {
  694. uint32_t lz = RAPIDJSON_CLZLL(high);
  695. len = 8 + (lz >> 3);
  696. escaped = true;
  697. }
  698. } else {
  699. uint32_t lz = RAPIDJSON_CLZLL(low);
  700. len = lz >> 3;
  701. escaped = true;
  702. }
  703. if (RAPIDJSON_UNLIKELY(escaped)) { // some of characters is escaped
  704. char *q = reinterpret_cast<char *>(os_->PushUnsafe(len));
  705. for (size_t i = 0; i < len; i++) q[i] = p[i];
  706. p += len;
  707. break;
  708. }
  709. vst1q_u8(reinterpret_cast<uint8_t *>(os_->PushUnsafe(16)), s);
  710. }
  711. is.src_ = p;
  712. return RAPIDJSON_LIKELY(is.Tell() < length);
  713. }
  714. #endif // RAPIDJSON_NEON
  715. RAPIDJSON_NAMESPACE_END
  716. #if defined(_MSC_VER) || defined(__clang__)
  717. RAPIDJSON_DIAG_POP
  718. #endif
  719. #endif // RAPIDJSON_RAPIDJSON_H_