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