writer.h 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  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 _MSC_VER
  36. RAPIDJSON_DIAG_PUSH
  37. RAPIDJSON_DIAG_OFF(4127) // conditional expression is constant
  38. #endif
  39. #ifdef __clang__
  40. RAPIDJSON_DIAG_PUSH
  41. RAPIDJSON_DIAG_OFF(padded)
  42. RAPIDJSON_DIAG_OFF(unreachable-code)
  43. RAPIDJSON_DIAG_OFF(c++98-compat)
  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. for (size_t i = 0; i < length; i++) {
  402. RAPIDJSON_ASSERT(json[i] != '\0');
  403. PutUnsafe(*os_, json[i]);
  404. }
  405. return true;
  406. }
  407. void Prefix(Type type) {
  408. (void)type;
  409. if (RAPIDJSON_LIKELY(level_stack_.GetSize() != 0)) { // this value is not at root
  410. Level* level = level_stack_.template Top<Level>();
  411. if (level->valueCount > 0) {
  412. if (level->inArray)
  413. os_->Put(','); // add comma if it is not the first element in array
  414. else // in object
  415. os_->Put((level->valueCount % 2 == 0) ? ',' : ':');
  416. }
  417. if (!level->inArray && level->valueCount % 2 == 0)
  418. RAPIDJSON_ASSERT(type == kStringType); // if it's in object, then even number should be a name
  419. level->valueCount++;
  420. }
  421. else {
  422. RAPIDJSON_ASSERT(!hasRoot_); // Should only has one and only one root.
  423. hasRoot_ = true;
  424. }
  425. }
  426. // Flush the value if it is the top level one.
  427. bool EndValue(bool ret) {
  428. if (RAPIDJSON_UNLIKELY(level_stack_.Empty())) // end of json text
  429. Flush();
  430. return ret;
  431. }
  432. OutputStream* os_;
  433. internal::Stack<StackAllocator> level_stack_;
  434. int maxDecimalPlaces_;
  435. bool hasRoot_;
  436. private:
  437. // Prohibit copy constructor & assignment operator.
  438. Writer(const Writer&);
  439. Writer& operator=(const Writer&);
  440. };
  441. // Full specialization for StringStream to prevent memory copying
  442. template<>
  443. inline bool Writer<StringBuffer>::WriteInt(int i) {
  444. char *buffer = os_->Push(11);
  445. const char* end = internal::i32toa(i, buffer);
  446. os_->Pop(static_cast<size_t>(11 - (end - buffer)));
  447. return true;
  448. }
  449. template<>
  450. inline bool Writer<StringBuffer>::WriteUint(unsigned u) {
  451. char *buffer = os_->Push(10);
  452. const char* end = internal::u32toa(u, buffer);
  453. os_->Pop(static_cast<size_t>(10 - (end - buffer)));
  454. return true;
  455. }
  456. template<>
  457. inline bool Writer<StringBuffer>::WriteInt64(int64_t i64) {
  458. char *buffer = os_->Push(21);
  459. const char* end = internal::i64toa(i64, buffer);
  460. os_->Pop(static_cast<size_t>(21 - (end - buffer)));
  461. return true;
  462. }
  463. template<>
  464. inline bool Writer<StringBuffer>::WriteUint64(uint64_t u) {
  465. char *buffer = os_->Push(20);
  466. const char* end = internal::u64toa(u, buffer);
  467. os_->Pop(static_cast<size_t>(20 - (end - buffer)));
  468. return true;
  469. }
  470. template<>
  471. inline bool Writer<StringBuffer>::WriteDouble(double d) {
  472. if (internal::Double(d).IsNanOrInf()) {
  473. // Note: This code path can only be reached if (RAPIDJSON_WRITE_DEFAULT_FLAGS & kWriteNanAndInfFlag).
  474. if (!(kWriteDefaultFlags & kWriteNanAndInfFlag))
  475. return false;
  476. if (internal::Double(d).IsNan()) {
  477. PutReserve(*os_, 3);
  478. PutUnsafe(*os_, 'N'); PutUnsafe(*os_, 'a'); PutUnsafe(*os_, 'N');
  479. return true;
  480. }
  481. if (internal::Double(d).Sign()) {
  482. PutReserve(*os_, 9);
  483. PutUnsafe(*os_, '-');
  484. }
  485. else
  486. PutReserve(*os_, 8);
  487. PutUnsafe(*os_, 'I'); PutUnsafe(*os_, 'n'); PutUnsafe(*os_, 'f');
  488. PutUnsafe(*os_, 'i'); PutUnsafe(*os_, 'n'); PutUnsafe(*os_, 'i'); PutUnsafe(*os_, 't'); PutUnsafe(*os_, 'y');
  489. return true;
  490. }
  491. char *buffer = os_->Push(25);
  492. char* end = internal::dtoa(d, buffer, maxDecimalPlaces_);
  493. os_->Pop(static_cast<size_t>(25 - (end - buffer)));
  494. return true;
  495. }
  496. #if defined(RAPIDJSON_SSE2) || defined(RAPIDJSON_SSE42)
  497. template<>
  498. inline bool Writer<StringBuffer>::ScanWriteUnescapedString(StringStream& is, size_t length) {
  499. if (length < 16)
  500. return RAPIDJSON_LIKELY(is.Tell() < length);
  501. if (!RAPIDJSON_LIKELY(is.Tell() < length))
  502. return false;
  503. const char* p = is.src_;
  504. const char* end = is.head_ + length;
  505. const char* nextAligned = reinterpret_cast<const char*>((reinterpret_cast<size_t>(p) + 15) & static_cast<size_t>(~15));
  506. const char* endAligned = reinterpret_cast<const char*>(reinterpret_cast<size_t>(end) & static_cast<size_t>(~15));
  507. if (nextAligned > end)
  508. return true;
  509. while (p != nextAligned)
  510. if (*p < 0x20 || *p == '\"' || *p == '\\') {
  511. is.src_ = p;
  512. return RAPIDJSON_LIKELY(is.Tell() < length);
  513. }
  514. else
  515. os_->PutUnsafe(*p++);
  516. // The rest of string using SIMD
  517. static const char dquote[16] = { '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"' };
  518. static const char bslash[16] = { '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\' };
  519. static const char space[16] = { 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F };
  520. const __m128i dq = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&dquote[0]));
  521. const __m128i bs = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&bslash[0]));
  522. const __m128i sp = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&space[0]));
  523. for (; p != endAligned; p += 16) {
  524. const __m128i s = _mm_load_si128(reinterpret_cast<const __m128i *>(p));
  525. const __m128i t1 = _mm_cmpeq_epi8(s, dq);
  526. const __m128i t2 = _mm_cmpeq_epi8(s, bs);
  527. const __m128i t3 = _mm_cmpeq_epi8(_mm_max_epu8(s, sp), sp); // s < 0x20 <=> max(s, 0x1F) == 0x1F
  528. const __m128i x = _mm_or_si128(_mm_or_si128(t1, t2), t3);
  529. unsigned short r = static_cast<unsigned short>(_mm_movemask_epi8(x));
  530. if (RAPIDJSON_UNLIKELY(r != 0)) { // some of characters is escaped
  531. SizeType len;
  532. #ifdef _MSC_VER // Find the index of first escaped
  533. unsigned long offset;
  534. _BitScanForward(&offset, r);
  535. len = offset;
  536. #else
  537. len = static_cast<SizeType>(__builtin_ffs(r) - 1);
  538. #endif
  539. char* q = reinterpret_cast<char*>(os_->PushUnsafe(len));
  540. for (size_t i = 0; i < len; i++)
  541. q[i] = p[i];
  542. p += len;
  543. break;
  544. }
  545. _mm_storeu_si128(reinterpret_cast<__m128i *>(os_->PushUnsafe(16)), s);
  546. }
  547. is.src_ = p;
  548. return RAPIDJSON_LIKELY(is.Tell() < length);
  549. }
  550. #elif defined(RAPIDJSON_NEON)
  551. template<>
  552. inline bool Writer<StringBuffer>::ScanWriteUnescapedString(StringStream& is, size_t length) {
  553. if (length < 16)
  554. return RAPIDJSON_LIKELY(is.Tell() < length);
  555. if (!RAPIDJSON_LIKELY(is.Tell() < length))
  556. return false;
  557. const char* p = is.src_;
  558. const char* end = is.head_ + length;
  559. const char* nextAligned = reinterpret_cast<const char*>((reinterpret_cast<size_t>(p) + 15) & static_cast<size_t>(~15));
  560. const char* endAligned = reinterpret_cast<const char*>(reinterpret_cast<size_t>(end) & static_cast<size_t>(~15));
  561. if (nextAligned > end)
  562. return true;
  563. while (p != nextAligned)
  564. if (*p < 0x20 || *p == '\"' || *p == '\\') {
  565. is.src_ = p;
  566. return RAPIDJSON_LIKELY(is.Tell() < length);
  567. }
  568. else
  569. os_->PutUnsafe(*p++);
  570. // The rest of string using SIMD
  571. const uint8x16_t s0 = vmovq_n_u8('"');
  572. const uint8x16_t s1 = vmovq_n_u8('\\');
  573. const uint8x16_t s2 = vmovq_n_u8('\b');
  574. const uint8x16_t s3 = vmovq_n_u8(32);
  575. for (; p != endAligned; p += 16) {
  576. const uint8x16_t s = vld1q_u8(reinterpret_cast<const uint8_t *>(p));
  577. uint8x16_t x = vceqq_u8(s, s0);
  578. x = vorrq_u8(x, vceqq_u8(s, s1));
  579. x = vorrq_u8(x, vceqq_u8(s, s2));
  580. x = vorrq_u8(x, vcltq_u8(s, s3));
  581. x = vrev64q_u8(x); // Rev in 64
  582. uint64_t low = vgetq_lane_u64(reinterpret_cast<uint64x2_t>(x), 0); // extract
  583. uint64_t high = vgetq_lane_u64(reinterpret_cast<uint64x2_t>(x), 1); // extract
  584. SizeType len = 0;
  585. bool escaped = false;
  586. if (low == 0) {
  587. if (high != 0) {
  588. unsigned lz = (unsigned)__builtin_clzll(high);
  589. len = 8 + (lz >> 3);
  590. escaped = true;
  591. }
  592. } else {
  593. unsigned lz = (unsigned)__builtin_clzll(low);
  594. len = lz >> 3;
  595. escaped = true;
  596. }
  597. if (RAPIDJSON_UNLIKELY(escaped)) { // some of characters is escaped
  598. char* q = reinterpret_cast<char*>(os_->PushUnsafe(len));
  599. for (size_t i = 0; i < len; i++)
  600. q[i] = p[i];
  601. p += len;
  602. break;
  603. }
  604. vst1q_u8(reinterpret_cast<uint8_t *>(os_->PushUnsafe(16)), s);
  605. }
  606. is.src_ = p;
  607. return RAPIDJSON_LIKELY(is.Tell() < length);
  608. }
  609. #endif // RAPIDJSON_NEON
  610. RAPIDJSON_NAMESPACE_END
  611. #ifdef _MSC_VER
  612. RAPIDJSON_DIAG_POP
  613. #endif
  614. #ifdef __clang__
  615. RAPIDJSON_DIAG_POP
  616. #endif
  617. #endif // RAPIDJSON_RAPIDJSON_H_