writer.h 23 KB

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