prettywriter.h 9.4 KB

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