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/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. const Ch c = is.Peek();
  403. RAPIDJSON_ASSERT(c != '\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(reinterpret_cast<uint64x2_t>(x), 0); // extract
  587. uint64_t high = vgetq_lane_u64(reinterpret_cast<uint64x2_t>(x), 1); // extract
  588. SizeType len = 0;
  589. bool escaped = false;
  590. if (low == 0) {
  591. if (high != 0) {
  592. unsigned lz = (unsigned)__builtin_clzll(high);
  593. len = 8 + (lz >> 3);
  594. escaped = true;
  595. }
  596. } else {
  597. unsigned lz = (unsigned)__builtin_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_