writer.h 26 KB

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