prettywriter.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. // Tencent is pleased to support the open source community by making RapidJSON
  2. // available.
  3. //
  4. // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All
  5. // rights reserved.
  6. //
  7. // Licensed under the MIT License (the "License"); you may not use this file
  8. // except in compliance with the License. You may obtain a copy of the License
  9. // at
  10. //
  11. // http://opensource.org/licenses/MIT
  12. //
  13. // Unless required by applicable law or agreed to in writing, software
  14. // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  15. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  16. // License for the specific language governing permissions and limitations under
  17. // the License.
  18. #ifndef RAPIDJSON_PRETTYWRITER_H_
  19. #define RAPIDJSON_PRETTYWRITER_H_
  20. #include "writer.h"
  21. #ifdef __GNUC__
  22. RAPIDJSON_DIAG_PUSH
  23. RAPIDJSON_DIAG_OFF(effc++)
  24. #endif
  25. #if defined(__clang__)
  26. RAPIDJSON_DIAG_PUSH
  27. RAPIDJSON_DIAG_OFF(c++ 98 - compat)
  28. #endif
  29. RAPIDJSON_NAMESPACE_BEGIN
  30. //! Combination of PrettyWriter format flags.
  31. /*! \see PrettyWriter::SetFormatOptions
  32. */
  33. enum PrettyFormatOptions {
  34. kFormatDefault = 0, //!< Default pretty formatting.
  35. kFormatSingleLineArray = 1 //!< Format arrays on a single line.
  36. };
  37. //! Writer with indentation and spacing.
  38. /*!
  39. \tparam OutputStream Type of output os.
  40. \tparam SourceEncoding Encoding of source string.
  41. \tparam TargetEncoding Encoding of output stream.
  42. \tparam StackAllocator Type of allocator for allocating memory of stack.
  43. */
  44. template <typename OutputStream, typename SourceEncoding = UTF8<>,
  45. typename TargetEncoding = UTF8<>,
  46. typename StackAllocator = CrtAllocator,
  47. unsigned writeFlags = kWriteDefaultFlags>
  48. class PrettyWriter : public Writer<OutputStream, SourceEncoding, TargetEncoding,
  49. StackAllocator, writeFlags> {
  50. public:
  51. typedef Writer<OutputStream, SourceEncoding, TargetEncoding, StackAllocator,
  52. writeFlags>
  53. Base;
  54. typedef typename Base::Ch Ch;
  55. //! Constructor
  56. /*! \param os Output stream.
  57. \param allocator User supplied allocator. If it is null, it will create a
  58. private one. \param levelDepth Initial capacity of stack.
  59. */
  60. explicit PrettyWriter(OutputStream &os, StackAllocator *allocator = 0,
  61. size_t levelDepth = Base::kDefaultLevelDepth)
  62. : Base(os, allocator, levelDepth),
  63. indentChar_(' '),
  64. indentCharCount_(4),
  65. formatOptions_(kFormatDefault) {}
  66. explicit PrettyWriter(StackAllocator *allocator = 0,
  67. size_t levelDepth = Base::kDefaultLevelDepth)
  68. : Base(allocator, levelDepth), indentChar_(' '), indentCharCount_(4) {}
  69. #if RAPIDJSON_HAS_CXX11_RVALUE_REFS
  70. PrettyWriter(PrettyWriter &&rhs)
  71. : Base(std::forward<PrettyWriter>(rhs)),
  72. indentChar_(rhs.indentChar_),
  73. indentCharCount_(rhs.indentCharCount_),
  74. formatOptions_(rhs.formatOptions_) {}
  75. #endif
  76. //! Set custom indentation.
  77. /*! \param indentChar Character for indentation. Must be whitespace
  78. character (' ', '\\t', '\\n', '\\r'). \param indentCharCount Number of
  79. indent characters for each indentation level. \note The default indentation
  80. is 4 spaces.
  81. */
  82. PrettyWriter &SetIndent(Ch indentChar, unsigned indentCharCount) {
  83. RAPIDJSON_ASSERT(indentChar == ' ' || indentChar == '\t' ||
  84. indentChar == '\n' || indentChar == '\r');
  85. indentChar_ = indentChar;
  86. indentCharCount_ = indentCharCount;
  87. return *this;
  88. }
  89. //! Set pretty writer formatting options.
  90. /*! \param options Formatting options.
  91. */
  92. PrettyWriter &SetFormatOptions(PrettyFormatOptions options) {
  93. formatOptions_ = options;
  94. return *this;
  95. }
  96. /*! @name Implementation of Handler
  97. \see Handler
  98. */
  99. //@{
  100. bool Null() {
  101. PrettyPrefix(kNullType);
  102. return Base::EndValue(Base::WriteNull());
  103. }
  104. bool Bool(bool b) {
  105. PrettyPrefix(b ? kTrueType : kFalseType);
  106. return Base::EndValue(Base::WriteBool(b));
  107. }
  108. bool Int(int i) {
  109. PrettyPrefix(kNumberType);
  110. return Base::EndValue(Base::WriteInt(i));
  111. }
  112. bool Uint(unsigned u) {
  113. PrettyPrefix(kNumberType);
  114. return Base::EndValue(Base::WriteUint(u));
  115. }
  116. bool Int64(int64_t i64) {
  117. PrettyPrefix(kNumberType);
  118. return Base::EndValue(Base::WriteInt64(i64));
  119. }
  120. bool Uint64(uint64_t u64) {
  121. PrettyPrefix(kNumberType);
  122. return Base::EndValue(Base::WriteUint64(u64));
  123. }
  124. bool Double(double d) {
  125. PrettyPrefix(kNumberType);
  126. return Base::EndValue(Base::WriteDouble(d));
  127. }
  128. bool RawNumber(const Ch *str, SizeType length, bool copy = false) {
  129. RAPIDJSON_ASSERT(str != 0);
  130. (void)copy;
  131. PrettyPrefix(kNumberType);
  132. return Base::EndValue(Base::WriteString(str, length));
  133. }
  134. bool String(const Ch *str, SizeType length, bool copy = false) {
  135. RAPIDJSON_ASSERT(str != 0);
  136. (void)copy;
  137. PrettyPrefix(kStringType);
  138. return Base::EndValue(Base::WriteString(str, length));
  139. }
  140. #if RAPIDJSON_HAS_STDSTRING
  141. bool String(const std::basic_string<Ch> &str) {
  142. return String(str.data(), SizeType(str.size()));
  143. }
  144. #endif
  145. bool StartObject() {
  146. PrettyPrefix(kObjectType);
  147. new (Base::level_stack_.template Push<typename Base::Level>())
  148. typename Base::Level(false);
  149. return Base::WriteStartObject();
  150. }
  151. bool Key(const Ch *str, SizeType length, bool copy = false) {
  152. return String(str, length, copy);
  153. }
  154. #if RAPIDJSON_HAS_STDSTRING
  155. bool Key(const std::basic_string<Ch> &str) {
  156. return Key(str.data(), SizeType(str.size()));
  157. }
  158. #endif
  159. bool EndObject(SizeType memberCount = 0) {
  160. (void)memberCount;
  161. RAPIDJSON_ASSERT(Base::level_stack_.GetSize() >=
  162. sizeof(typename Base::Level)); // not inside an Object
  163. RAPIDJSON_ASSERT(!Base::level_stack_.template Top<typename Base::Level>()
  164. ->inArray); // currently inside an Array, not Object
  165. RAPIDJSON_ASSERT(
  166. 0 ==
  167. Base::level_stack_.template Top<typename Base::Level>()->valueCount %
  168. 2); // Object has a Key without a Value
  169. bool empty =
  170. Base::level_stack_.template Pop<typename Base::Level>(1)->valueCount ==
  171. 0;
  172. if (!empty) {
  173. Base::os_->Put('\n');
  174. WriteIndent();
  175. }
  176. bool ret = Base::EndValue(Base::WriteEndObject());
  177. (void)ret;
  178. RAPIDJSON_ASSERT(ret == true);
  179. if (Base::level_stack_.Empty()) // end of json text
  180. Base::Flush();
  181. return true;
  182. }
  183. bool StartArray() {
  184. PrettyPrefix(kArrayType);
  185. new (Base::level_stack_.template Push<typename Base::Level>())
  186. typename Base::Level(true);
  187. return Base::WriteStartArray();
  188. }
  189. bool EndArray(SizeType memberCount = 0) {
  190. (void)memberCount;
  191. RAPIDJSON_ASSERT(Base::level_stack_.GetSize() >=
  192. sizeof(typename Base::Level));
  193. RAPIDJSON_ASSERT(
  194. Base::level_stack_.template Top<typename Base::Level>()->inArray);
  195. bool empty =
  196. Base::level_stack_.template Pop<typename Base::Level>(1)->valueCount ==
  197. 0;
  198. if (!empty && !(formatOptions_ & kFormatSingleLineArray)) {
  199. Base::os_->Put('\n');
  200. WriteIndent();
  201. }
  202. bool ret = Base::EndValue(Base::WriteEndArray());
  203. (void)ret;
  204. RAPIDJSON_ASSERT(ret == true);
  205. if (Base::level_stack_.Empty()) // end of json text
  206. Base::Flush();
  207. return true;
  208. }
  209. //@}
  210. /*! @name Convenience extensions */
  211. //@{
  212. //! Simpler but slower overload.
  213. bool String(const Ch *str) { return String(str, internal::StrLen(str)); }
  214. bool Key(const Ch *str) { return Key(str, internal::StrLen(str)); }
  215. //@}
  216. //! Write a raw JSON value.
  217. /*!
  218. For user to write a stringified JSON as a value.
  219. \param json A well-formed JSON value. It should not contain null character
  220. within [0, length - 1] range. \param length Length of the json. \param type
  221. Type of the root of json. \note When using PrettyWriter::RawValue(), the
  222. result json may not be indented correctly.
  223. */
  224. bool RawValue(const Ch *json, size_t length, Type type) {
  225. RAPIDJSON_ASSERT(json != 0);
  226. PrettyPrefix(type);
  227. return Base::EndValue(Base::WriteRawValue(json, length));
  228. }
  229. protected:
  230. void PrettyPrefix(Type type) {
  231. (void)type;
  232. if (Base::level_stack_.GetSize() != 0) { // this value is not at root
  233. typename Base::Level *level =
  234. Base::level_stack_.template Top<typename Base::Level>();
  235. if (level->inArray) {
  236. if (level->valueCount > 0) {
  237. Base::os_->Put(
  238. ','); // add comma if it is not the first element in array
  239. if (formatOptions_ & kFormatSingleLineArray) Base::os_->Put(' ');
  240. }
  241. if (!(formatOptions_ & kFormatSingleLineArray)) {
  242. Base::os_->Put('\n');
  243. WriteIndent();
  244. }
  245. } else { // in object
  246. if (level->valueCount > 0) {
  247. if (level->valueCount % 2 == 0) {
  248. Base::os_->Put(',');
  249. Base::os_->Put('\n');
  250. } else {
  251. Base::os_->Put(':');
  252. Base::os_->Put(' ');
  253. }
  254. } else
  255. Base::os_->Put('\n');
  256. if (level->valueCount % 2 == 0) WriteIndent();
  257. }
  258. if (!level->inArray && level->valueCount % 2 == 0)
  259. RAPIDJSON_ASSERT(type == kStringType); // if it's in object, then even
  260. // number should be a name
  261. level->valueCount++;
  262. } else {
  263. RAPIDJSON_ASSERT(
  264. !Base::hasRoot_); // Should only has one and only one root.
  265. Base::hasRoot_ = true;
  266. }
  267. }
  268. void WriteIndent() {
  269. size_t count =
  270. (Base::level_stack_.GetSize() / sizeof(typename Base::Level)) *
  271. indentCharCount_;
  272. PutN(*Base::os_, static_cast<typename OutputStream::Ch>(indentChar_),
  273. count);
  274. }
  275. Ch indentChar_;
  276. unsigned indentCharCount_;
  277. PrettyFormatOptions formatOptions_;
  278. private:
  279. // Prohibit copy constructor & assignment operator.
  280. PrettyWriter(const PrettyWriter &);
  281. PrettyWriter &operator=(const PrettyWriter &);
  282. };
  283. RAPIDJSON_NAMESPACE_END
  284. #if defined(__clang__)
  285. RAPIDJSON_DIAG_POP
  286. #endif
  287. #ifdef __GNUC__
  288. RAPIDJSON_DIAG_POP
  289. #endif
  290. #endif // RAPIDJSON_RAPIDJSON_H_