prettywriter.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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_PRETTYWRITER_H_
  15. #define RAPIDJSON_PRETTYWRITER_H_
  16. #include "writer.h"
  17. #ifdef __GNUC__
  18. RAPIDJSON_DIAG_PUSH
  19. RAPIDJSON_DIAG_OFF(effc++)
  20. #endif
  21. #if defined(__clang__)
  22. RAPIDJSON_DIAG_PUSH
  23. RAPIDJSON_DIAG_OFF(c++98-compat)
  24. #endif
  25. RAPIDJSON_NAMESPACE_BEGIN
  26. //! Combination of PrettyWriter format flags.
  27. /*! \see PrettyWriter::SetFormatOptions
  28. */
  29. enum PrettyFormatOptions {
  30. kFormatDefault = 0, //!< Default pretty formatting.
  31. kFormatSingleLineArray = 1 //!< Format arrays on a single line.
  32. };
  33. //! Writer with indentation and spacing.
  34. /*!
  35. \tparam OutputStream Type of output os.
  36. \tparam SourceEncoding Encoding of source string.
  37. \tparam TargetEncoding Encoding of output stream.
  38. \tparam StackAllocator Type of allocator for allocating memory of stack.
  39. */
  40. template<typename OutputStream, typename SourceEncoding = UTF8<>, typename TargetEncoding = UTF8<>, typename StackAllocator = CrtAllocator, unsigned writeFlags = kWriteDefaultFlags>
  41. class PrettyWriter : public Writer<OutputStream, SourceEncoding, TargetEncoding, StackAllocator, writeFlags> {
  42. public:
  43. typedef Writer<OutputStream, SourceEncoding, TargetEncoding, StackAllocator, writeFlags> Base;
  44. typedef typename Base::Ch Ch;
  45. //! Constructor
  46. /*! \param os Output stream.
  47. \param allocator User supplied allocator. If it is null, it will create a private one.
  48. \param levelDepth Initial capacity of stack.
  49. */
  50. explicit PrettyWriter(OutputStream& os, StackAllocator* allocator = 0, size_t levelDepth = Base::kDefaultLevelDepth) :
  51. Base(os, allocator, levelDepth), indentChar_(' '), indentCharCount_(4), formatOptions_(kFormatDefault) {}
  52. explicit PrettyWriter(StackAllocator* allocator = 0, size_t levelDepth = Base::kDefaultLevelDepth) :
  53. Base(allocator, levelDepth), indentChar_(' '), indentCharCount_(4) {}
  54. #if RAPIDJSON_HAS_CXX11_RVALUE_REFS
  55. PrettyWriter(PrettyWriter&& rhs) :
  56. Base(std::forward<PrettyWriter>(rhs)), indentChar_(rhs.indentChar_), indentCharCount_(rhs.indentCharCount_), formatOptions_(rhs.formatOptions_) {}
  57. #endif
  58. //! Set custom indentation.
  59. /*! \param indentChar Character for indentation. Must be whitespace character (' ', '\\t', '\\n', '\\r').
  60. \param indentCharCount Number of indent characters for each indentation level.
  61. \note The default indentation is 4 spaces.
  62. */
  63. PrettyWriter& SetIndent(Ch indentChar, unsigned indentCharCount) {
  64. RAPIDJSON_ASSERT(indentChar == ' ' || indentChar == '\t' || indentChar == '\n' || indentChar == '\r');
  65. indentChar_ = indentChar;
  66. indentCharCount_ = indentCharCount;
  67. return *this;
  68. }
  69. //! Set pretty writer formatting options.
  70. /*! \param options Formatting options.
  71. */
  72. PrettyWriter& SetFormatOptions(PrettyFormatOptions options) {
  73. formatOptions_ = options;
  74. return *this;
  75. }
  76. /*! @name Implementation of Handler
  77. \see Handler
  78. */
  79. //@{
  80. bool Null() { PrettyPrefix(kNullType); return Base::WriteNull(); }
  81. bool Bool(bool b) { PrettyPrefix(b ? kTrueType : kFalseType); return Base::WriteBool(b); }
  82. bool Int(int i) { PrettyPrefix(kNumberType); return Base::WriteInt(i); }
  83. bool Uint(unsigned u) { PrettyPrefix(kNumberType); return Base::WriteUint(u); }
  84. bool Int64(int64_t i64) { PrettyPrefix(kNumberType); return Base::WriteInt64(i64); }
  85. bool Uint64(uint64_t u64) { PrettyPrefix(kNumberType); return Base::WriteUint64(u64); }
  86. bool Double(double d) { PrettyPrefix(kNumberType); return Base::WriteDouble(d); }
  87. bool RawNumber(const Ch* str, SizeType length, bool copy = false) {
  88. RAPIDJSON_ASSERT(str != 0);
  89. (void)copy;
  90. PrettyPrefix(kNumberType);
  91. return Base::WriteString(str, length);
  92. }
  93. bool String(const Ch* str, SizeType length, bool copy = false) {
  94. RAPIDJSON_ASSERT(str != 0);
  95. (void)copy;
  96. PrettyPrefix(kStringType);
  97. return Base::WriteString(str, length);
  98. }
  99. #if RAPIDJSON_HAS_STDSTRING
  100. bool String(const std::basic_string<Ch>& str) {
  101. return String(str.data(), SizeType(str.size()));
  102. }
  103. #endif
  104. bool StartObject() {
  105. PrettyPrefix(kObjectType);
  106. new (Base::level_stack_.template Push<typename Base::Level>()) typename Base::Level(false);
  107. return Base::WriteStartObject();
  108. }
  109. bool Key(const Ch* str, SizeType length, bool copy = false) { return String(str, length, copy); }
  110. #if RAPIDJSON_HAS_STDSTRING
  111. bool Key(const std::basic_string<Ch>& str) {
  112. return Key(str.data(), SizeType(str.size()));
  113. }
  114. #endif
  115. bool EndObject(SizeType memberCount = 0) {
  116. (void)memberCount;
  117. RAPIDJSON_ASSERT(Base::level_stack_.GetSize() >= sizeof(typename Base::Level)); // not inside an Object
  118. RAPIDJSON_ASSERT(!Base::level_stack_.template Top<typename Base::Level>()->inArray); // currently inside an Array, not Object
  119. RAPIDJSON_ASSERT(0 == Base::level_stack_.template Top<typename Base::Level>()->valueCount % 2); // Object has a Key without a Value
  120. bool empty = Base::level_stack_.template Pop<typename Base::Level>(1)->valueCount == 0;
  121. if (!empty) {
  122. Base::os_->Put('\n');
  123. WriteIndent();
  124. }
  125. bool ret = Base::WriteEndObject();
  126. (void)ret;
  127. RAPIDJSON_ASSERT(ret == true);
  128. if (Base::level_stack_.Empty()) // end of json text
  129. Base::Flush();
  130. return true;
  131. }
  132. bool StartArray() {
  133. PrettyPrefix(kArrayType);
  134. new (Base::level_stack_.template Push<typename Base::Level>()) typename Base::Level(true);
  135. return Base::WriteStartArray();
  136. }
  137. bool EndArray(SizeType memberCount = 0) {
  138. (void)memberCount;
  139. RAPIDJSON_ASSERT(Base::level_stack_.GetSize() >= sizeof(typename Base::Level));
  140. RAPIDJSON_ASSERT(Base::level_stack_.template Top<typename Base::Level>()->inArray);
  141. bool empty = Base::level_stack_.template Pop<typename Base::Level>(1)->valueCount == 0;
  142. if (!empty && !(formatOptions_ & kFormatSingleLineArray)) {
  143. Base::os_->Put('\n');
  144. WriteIndent();
  145. }
  146. bool ret = Base::WriteEndArray();
  147. (void)ret;
  148. RAPIDJSON_ASSERT(ret == true);
  149. if (Base::level_stack_.Empty()) // end of json text
  150. Base::Flush();
  151. return true;
  152. }
  153. //@}
  154. /*! @name Convenience extensions */
  155. //@{
  156. //! Simpler but slower overload.
  157. bool String(const Ch* str) { return String(str, internal::StrLen(str)); }
  158. bool Key(const Ch* str) { return Key(str, internal::StrLen(str)); }
  159. //@}
  160. //! Write a raw JSON value.
  161. /*!
  162. For user to write a stringified JSON as a value.
  163. \param json A well-formed JSON value. It should not contain null character within [0, length - 1] range.
  164. \param length Length of the json.
  165. \param type Type of the root of json.
  166. \note When using PrettyWriter::RawValue(), the result json may not be indented correctly.
  167. */
  168. bool RawValue(const Ch* json, size_t length, Type type) {
  169. RAPIDJSON_ASSERT(json != 0);
  170. PrettyPrefix(type);
  171. return Base::WriteRawValue(json, length);
  172. }
  173. protected:
  174. void PrettyPrefix(Type type) {
  175. (void)type;
  176. if (Base::level_stack_.GetSize() != 0) { // this value is not at root
  177. typename Base::Level* level = Base::level_stack_.template Top<typename Base::Level>();
  178. if (level->inArray) {
  179. if (level->valueCount > 0) {
  180. Base::os_->Put(','); // add comma if it is not the first element in array
  181. if (formatOptions_ & kFormatSingleLineArray)
  182. Base::os_->Put(' ');
  183. }
  184. if (!(formatOptions_ & kFormatSingleLineArray)) {
  185. Base::os_->Put('\n');
  186. WriteIndent();
  187. }
  188. }
  189. else { // in object
  190. if (level->valueCount > 0) {
  191. if (level->valueCount % 2 == 0) {
  192. Base::os_->Put(',');
  193. Base::os_->Put('\n');
  194. }
  195. else {
  196. Base::os_->Put(':');
  197. Base::os_->Put(' ');
  198. }
  199. }
  200. else
  201. Base::os_->Put('\n');
  202. if (level->valueCount % 2 == 0)
  203. WriteIndent();
  204. }
  205. if (!level->inArray && level->valueCount % 2 == 0)
  206. RAPIDJSON_ASSERT(type == kStringType); // if it's in object, then even number should be a name
  207. level->valueCount++;
  208. }
  209. else {
  210. RAPIDJSON_ASSERT(!Base::hasRoot_); // Should only has one and only one root.
  211. Base::hasRoot_ = true;
  212. }
  213. }
  214. void WriteIndent() {
  215. size_t count = (Base::level_stack_.GetSize() / sizeof(typename Base::Level)) * indentCharCount_;
  216. PutN(*Base::os_, static_cast<typename OutputStream::Ch>(indentChar_), count);
  217. }
  218. Ch indentChar_;
  219. unsigned indentCharCount_;
  220. PrettyFormatOptions formatOptions_;
  221. private:
  222. // Prohibit copy constructor & assignment operator.
  223. PrettyWriter(const PrettyWriter&);
  224. PrettyWriter& operator=(const PrettyWriter&);
  225. };
  226. RAPIDJSON_NAMESPACE_END
  227. #if defined(__clang__)
  228. RAPIDJSON_DIAG_POP
  229. #endif
  230. #ifdef __GNUC__
  231. RAPIDJSON_DIAG_POP
  232. #endif
  233. #endif // RAPIDJSON_RAPIDJSON_H_