prettywriter.h 7.5 KB

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