writer.h 26 KB

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