writer.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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 "rapidjson.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 RAPIDJSON_HAS_STDSTRING
  24. #include <string>
  25. #endif
  26. #ifdef _MSC_VER
  27. RAPIDJSON_DIAG_PUSH
  28. RAPIDJSON_DIAG_OFF(4127) // conditional expression is constant
  29. #endif
  30. RAPIDJSON_NAMESPACE_BEGIN
  31. //! JSON writer
  32. /*! Writer implements the concept Handler.
  33. It generates JSON text by events to an output os.
  34. User may programmatically calls the functions of a writer to generate JSON text.
  35. On the other side, a writer can also be passed to objects that generates events,
  36. for example Reader::Parse() and Document::Accept().
  37. \tparam OutputStream Type of output stream.
  38. \tparam SourceEncoding Encoding of source string.
  39. \tparam TargetEncoding Encoding of output stream.
  40. \tparam StackAllocator Type of allocator for allocating memory of stack.
  41. \note implements Handler concept
  42. */
  43. template<typename OutputStream, typename SourceEncoding = UTF8<>, typename TargetEncoding = UTF8<>, typename StackAllocator = CrtAllocator>
  44. class Writer {
  45. public:
  46. typedef typename SourceEncoding::Ch Ch;
  47. //! Constructor
  48. /*! \param os Output stream.
  49. \param stackAllocator User supplied allocator. If it is null, it will create a private one.
  50. \param levelDepth Initial capacity of stack.
  51. */
  52. explicit
  53. Writer(OutputStream& os, StackAllocator* stackAllocator = 0, size_t levelDepth = kDefaultLevelDepth) :
  54. os_(&os), level_stack_(stackAllocator, levelDepth * sizeof(Level)), hasRoot_(false) {}
  55. explicit
  56. Writer(StackAllocator* allocator = 0, size_t levelDepth = kDefaultLevelDepth) :
  57. os_(0), level_stack_(allocator, levelDepth * sizeof(Level)), hasRoot_(false) {}
  58. //! Reset the writer with a new stream.
  59. /*!
  60. This function reset the writer with a new stream and default settings,
  61. in order to make a Writer object reusable for output multiple JSONs.
  62. \param os New output stream.
  63. \code
  64. Writer<OutputStream> writer(os1);
  65. writer.StartObject();
  66. // ...
  67. writer.EndObject();
  68. writer.Reset(os2);
  69. writer.StartObject();
  70. // ...
  71. writer.EndObject();
  72. \endcode
  73. */
  74. void Reset(OutputStream& os) {
  75. os_ = &os;
  76. hasRoot_ = false;
  77. level_stack_.Clear();
  78. }
  79. //! Checks whether the output is a complete JSON.
  80. /*!
  81. A complete JSON has a complete root object or array.
  82. */
  83. bool IsComplete() const {
  84. return hasRoot_ && level_stack_.Empty();
  85. }
  86. /*!@name Implementation of Handler
  87. \see Handler
  88. */
  89. //@{
  90. bool Null() { Prefix(kNullType); return WriteNull(); }
  91. bool Bool(bool b) { Prefix(b ? kTrueType : kFalseType); return WriteBool(b); }
  92. bool Int(int i) { Prefix(kNumberType); return WriteInt(i); }
  93. bool Uint(unsigned u) { Prefix(kNumberType); return WriteUint(u); }
  94. bool Int64(int64_t i64) { Prefix(kNumberType); return WriteInt64(i64); }
  95. bool Uint64(uint64_t u64) { Prefix(kNumberType); return WriteUint64(u64); }
  96. //! Writes the given \c double value to the stream
  97. /*!
  98. \param d The value to be written.
  99. \return Whether it is succeed.
  100. */
  101. bool Double(double d) { Prefix(kNumberType); return WriteDouble(d); }
  102. bool String(const Ch* str, SizeType length, bool copy = false) {
  103. (void)copy;
  104. Prefix(kStringType);
  105. return WriteString(str, length);
  106. }
  107. #if RAPIDJSON_HAS_STDSTRING
  108. bool String(const std::basic_string<Ch>& str) {
  109. return String(str.data(), SizeType(str.size()));
  110. }
  111. #endif
  112. bool StartObject() {
  113. Prefix(kObjectType);
  114. new (level_stack_.template Push<Level>()) Level(false);
  115. return WriteStartObject();
  116. }
  117. bool Key(const Ch* str, SizeType length, bool copy = false) { return String(str, length, copy); }
  118. bool EndObject(SizeType memberCount = 0) {
  119. (void)memberCount;
  120. RAPIDJSON_ASSERT(level_stack_.GetSize() >= sizeof(Level));
  121. RAPIDJSON_ASSERT(!level_stack_.template Top<Level>()->inArray);
  122. level_stack_.template Pop<Level>(1);
  123. bool ret = WriteEndObject();
  124. if (level_stack_.Empty()) // end of json text
  125. os_->Flush();
  126. return ret;
  127. }
  128. bool StartArray() {
  129. Prefix(kArrayType);
  130. new (level_stack_.template Push<Level>()) Level(true);
  131. return WriteStartArray();
  132. }
  133. bool EndArray(SizeType elementCount = 0) {
  134. (void)elementCount;
  135. RAPIDJSON_ASSERT(level_stack_.GetSize() >= sizeof(Level));
  136. RAPIDJSON_ASSERT(level_stack_.template Top<Level>()->inArray);
  137. level_stack_.template Pop<Level>(1);
  138. bool ret = WriteEndArray();
  139. if (level_stack_.Empty()) // end of json text
  140. os_->Flush();
  141. return ret;
  142. }
  143. //@}
  144. /*! @name Convenience extensions */
  145. //@{
  146. //! Simpler but slower overload.
  147. bool String(const Ch* str) { return String(str, internal::StrLen(str)); }
  148. bool Key(const Ch* str) { return Key(str, internal::StrLen(str)); }
  149. //@}
  150. protected:
  151. //! Information for each nested level
  152. struct Level {
  153. Level(bool inArray_) : valueCount(0), inArray(inArray_) {}
  154. size_t valueCount; //!< number of values in this level
  155. bool inArray; //!< true if in array, otherwise in object
  156. };
  157. static const size_t kDefaultLevelDepth = 32;
  158. bool WriteNull() {
  159. os_->Put('n'); os_->Put('u'); os_->Put('l'); os_->Put('l'); return true;
  160. }
  161. bool WriteBool(bool b) {
  162. if (b) {
  163. os_->Put('t'); os_->Put('r'); os_->Put('u'); os_->Put('e');
  164. }
  165. else {
  166. os_->Put('f'); os_->Put('a'); os_->Put('l'); os_->Put('s'); os_->Put('e');
  167. }
  168. return true;
  169. }
  170. bool WriteInt(int i) {
  171. char buffer[11];
  172. const char* end = internal::i32toa(i, buffer);
  173. for (const char* p = buffer; p != end; ++p)
  174. os_->Put(*p);
  175. return true;
  176. }
  177. bool WriteUint(unsigned u) {
  178. char buffer[10];
  179. const char* end = internal::u32toa(u, buffer);
  180. for (const char* p = buffer; p != end; ++p)
  181. os_->Put(*p);
  182. return true;
  183. }
  184. bool WriteInt64(int64_t i64) {
  185. char buffer[21];
  186. const char* end = internal::i64toa(i64, buffer);
  187. for (const char* p = buffer; p != end; ++p)
  188. os_->Put(*p);
  189. return true;
  190. }
  191. bool WriteUint64(uint64_t u64) {
  192. char buffer[20];
  193. char* end = internal::u64toa(u64, buffer);
  194. for (char* p = buffer; p != end; ++p)
  195. os_->Put(*p);
  196. return true;
  197. }
  198. bool WriteDouble(double d) {
  199. char buffer[25];
  200. char* end = internal::dtoa(d, buffer);
  201. for (char* p = buffer; p != end; ++p)
  202. os_->Put(*p);
  203. return true;
  204. }
  205. bool WriteString(const Ch* str, SizeType length) {
  206. static const char hexDigits[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
  207. static const char escape[256] = {
  208. #define Z16 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
  209. //0 1 2 3 4 5 6 7 8 9 A B C D E F
  210. 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'b', 't', 'n', 'u', 'f', 'r', 'u', 'u', // 00
  211. 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', // 10
  212. 0, 0, '"', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 20
  213. Z16, Z16, // 30~4F
  214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,'\\', 0, 0, 0, // 50
  215. Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16 // 60~FF
  216. #undef Z16
  217. };
  218. os_->Put('\"');
  219. GenericStringStream<SourceEncoding> is(str);
  220. while (is.Tell() < length) {
  221. const Ch c = is.Peek();
  222. if (!TargetEncoding::supportUnicode && (unsigned)c >= 0x80) {
  223. // Unicode escaping
  224. unsigned codepoint;
  225. if (!SourceEncoding::Decode(is, &codepoint))
  226. return false;
  227. os_->Put('\\');
  228. os_->Put('u');
  229. if (codepoint <= 0xD7FF || (codepoint >= 0xE000 && codepoint <= 0xFFFF)) {
  230. os_->Put(hexDigits[(codepoint >> 12) & 15]);
  231. os_->Put(hexDigits[(codepoint >> 8) & 15]);
  232. os_->Put(hexDigits[(codepoint >> 4) & 15]);
  233. os_->Put(hexDigits[(codepoint ) & 15]);
  234. }
  235. else {
  236. RAPIDJSON_ASSERT(codepoint >= 0x010000 && codepoint <= 0x10FFFF);
  237. // Surrogate pair
  238. unsigned s = codepoint - 0x010000;
  239. unsigned lead = (s >> 10) + 0xD800;
  240. unsigned trail = (s & 0x3FF) + 0xDC00;
  241. os_->Put(hexDigits[(lead >> 12) & 15]);
  242. os_->Put(hexDigits[(lead >> 8) & 15]);
  243. os_->Put(hexDigits[(lead >> 4) & 15]);
  244. os_->Put(hexDigits[(lead ) & 15]);
  245. os_->Put('\\');
  246. os_->Put('u');
  247. os_->Put(hexDigits[(trail >> 12) & 15]);
  248. os_->Put(hexDigits[(trail >> 8) & 15]);
  249. os_->Put(hexDigits[(trail >> 4) & 15]);
  250. os_->Put(hexDigits[(trail ) & 15]);
  251. }
  252. }
  253. else if ((sizeof(Ch) == 1 || (unsigned)c < 256) && escape[(unsigned char)c]) {
  254. is.Take();
  255. os_->Put('\\');
  256. os_->Put(escape[(unsigned char)c]);
  257. if (escape[(unsigned char)c] == 'u') {
  258. os_->Put('0');
  259. os_->Put('0');
  260. os_->Put(hexDigits[(unsigned char)c >> 4]);
  261. os_->Put(hexDigits[(unsigned char)c & 0xF]);
  262. }
  263. }
  264. else
  265. if (!Transcoder<SourceEncoding, TargetEncoding>::Transcode(is, *os_))
  266. return false;
  267. }
  268. os_->Put('\"');
  269. return true;
  270. }
  271. bool WriteStartObject() { os_->Put('{'); return true; }
  272. bool WriteEndObject() { os_->Put('}'); return true; }
  273. bool WriteStartArray() { os_->Put('['); return true; }
  274. bool WriteEndArray() { os_->Put(']'); return true; }
  275. void Prefix(Type type) {
  276. (void)type;
  277. if (level_stack_.GetSize() != 0) { // this value is not at root
  278. Level* level = level_stack_.template Top<Level>();
  279. if (level->valueCount > 0) {
  280. if (level->inArray)
  281. os_->Put(','); // add comma if it is not the first element in array
  282. else // in object
  283. os_->Put((level->valueCount % 2 == 0) ? ',' : ':');
  284. }
  285. if (!level->inArray && level->valueCount % 2 == 0)
  286. RAPIDJSON_ASSERT(type == kStringType); // if it's in object, then even number should be a name
  287. level->valueCount++;
  288. }
  289. else {
  290. RAPIDJSON_ASSERT(!hasRoot_); // Should only has one and only one root.
  291. hasRoot_ = true;
  292. }
  293. }
  294. OutputStream* os_;
  295. internal::Stack<StackAllocator> level_stack_;
  296. bool hasRoot_;
  297. private:
  298. // Prohibit copy constructor & assignment operator.
  299. Writer(const Writer&);
  300. Writer& operator=(const Writer&);
  301. };
  302. // Full specialization for StringStream to prevent memory copying
  303. template<>
  304. inline bool Writer<StringBuffer>::WriteInt(int i) {
  305. char *buffer = os_->Push(11);
  306. const char* end = internal::i32toa(i, buffer);
  307. os_->Pop(11 - (end - buffer));
  308. return true;
  309. }
  310. template<>
  311. inline bool Writer<StringBuffer>::WriteUint(unsigned u) {
  312. char *buffer = os_->Push(10);
  313. const char* end = internal::u32toa(u, buffer);
  314. os_->Pop(10 - (end - buffer));
  315. return true;
  316. }
  317. template<>
  318. inline bool Writer<StringBuffer>::WriteInt64(int64_t i64) {
  319. char *buffer = os_->Push(21);
  320. const char* end = internal::i64toa(i64, buffer);
  321. os_->Pop(21 - (end - buffer));
  322. return true;
  323. }
  324. template<>
  325. inline bool Writer<StringBuffer>::WriteUint64(uint64_t u) {
  326. char *buffer = os_->Push(20);
  327. const char* end = internal::u64toa(u, buffer);
  328. os_->Pop(20 - (end - buffer));
  329. return true;
  330. }
  331. template<>
  332. inline bool Writer<StringBuffer>::WriteDouble(double d) {
  333. char *buffer = os_->Push(25);
  334. char* end = internal::dtoa(d, buffer);
  335. os_->Pop(25 - (end - buffer));
  336. return true;
  337. }
  338. RAPIDJSON_NAMESPACE_END
  339. #ifdef _MSC_VER
  340. RAPIDJSON_DIAG_POP
  341. #endif
  342. #endif // RAPIDJSON_RAPIDJSON_H_