• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Protocol Buffers - Google's data interchange format
2 // Copyright 2008 Google Inc.  All rights reserved.
3 // https://developers.google.com/protocol-buffers/
4 //
5 // Redistribution and use in source and binary forms, with or without
6 // modification, are permitted provided that the following conditions are
7 // met:
8 //
9 //     * Redistributions of source code must retain the above copyright
10 // notice, this list of conditions and the following disclaimer.
11 //     * Redistributions in binary form must reproduce the above
12 // copyright notice, this list of conditions and the following disclaimer
13 // in the documentation and/or other materials provided with the
14 // distribution.
15 //     * Neither the name of Google Inc. nor the names of its
16 // contributors may be used to endorse or promote products derived from
17 // this software without specific prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 
31 #ifndef GOOGLE_PROTOBUF_UTIL_CONVERTER_JSON_OBJECTWRITER_H__
32 #define GOOGLE_PROTOBUF_UTIL_CONVERTER_JSON_OBJECTWRITER_H__
33 
34 #include <memory>
35 #include <string>
36 
37 #include <google/protobuf/io/coded_stream.h>
38 #include <google/protobuf/util/internal/structured_objectwriter.h>
39 #include <google/protobuf/stubs/bytestream.h>
40 
41 // clang-format off
42 #include <google/protobuf/port_def.inc>
43 // clang-format on
44 
45 namespace google {
46 namespace protobuf {
47 namespace util {
48 namespace converter {
49 
50 
51 // An ObjectWriter implementation that outputs JSON. This ObjectWriter
52 // supports writing a compact form or a pretty printed form.
53 //
54 // Sample usage:
55 //   string output;
56 //   StringOutputStream* str_stream = new StringOutputStream(&output);
57 //   CodedOutputStream* out_stream = new CodedOutputStream(str_stream);
58 //   JsonObjectWriter* ow = new JsonObjectWriter("  ", out_stream);
59 //   ow->StartObject("")
60 //       ->RenderString("name", "value")
61 //       ->RenderString("emptystring", string())
62 //       ->StartObject("nested")
63 //         ->RenderInt64("light", 299792458);
64 //         ->RenderDouble("pi", 3.141592653589793);
65 //       ->EndObject()
66 //       ->StartList("empty")
67 //       ->EndList()
68 //     ->EndObject();
69 //
70 // And then the output string would become:
71 // {
72 //   "name": "value",
73 //   "emptystring": "",
74 //   "nested": {
75 //     "light": "299792458",
76 //     "pi": 3.141592653589793
77 //   },
78 //   "empty": []
79 // }
80 //
81 // JsonObjectWriter does not validate if calls actually result in valid JSON.
82 // For example, passing an empty name when one would be required won't result
83 // in an error, just an invalid output.
84 //
85 // Note that all int64 and uint64 are rendered as strings instead of numbers.
86 // This is because JavaScript parses numbers as 64-bit float thus int64 and
87 // uint64 would lose precision if rendered as numbers.
88 //
89 // JsonObjectWriter is thread-unsafe.
90 class PROTOBUF_EXPORT JsonObjectWriter : public StructuredObjectWriter {
91  public:
JsonObjectWriter(StringPiece indent_string,io::CodedOutputStream * out)92   JsonObjectWriter(StringPiece indent_string, io::CodedOutputStream* out)
93       : element_(new Element(/*parent=*/nullptr, /*is_json_object=*/false)),
94         stream_(out),
95         sink_(out),
96         indent_string_(indent_string),
97         indent_char_('\0'),
98         indent_count_(0),
99         use_websafe_base64_for_bytes_(false) {
100     // See if we have a trivial sequence of indent characters.
101     if (!indent_string.empty()) {
102       indent_char_ = indent_string[0];
103       indent_count_ = indent_string.length();
104       for (int i = 1; i < indent_string.length(); i++) {
105         if (indent_char_ != indent_string_[i]) {
106           indent_char_ = '\0';
107           indent_count_ = 0;
108           break;
109         }
110       }
111     }
112   }
113   virtual ~JsonObjectWriter();
114 
115   // ObjectWriter methods.
116   JsonObjectWriter* StartObject(StringPiece name) override;
117   JsonObjectWriter* EndObject() override;
118   JsonObjectWriter* StartList(StringPiece name) override;
119   JsonObjectWriter* EndList() override;
120   JsonObjectWriter* RenderBool(StringPiece name, bool value) override;
121   JsonObjectWriter* RenderInt32(StringPiece name, int32 value) override;
122   JsonObjectWriter* RenderUint32(StringPiece name, uint32 value) override;
123   JsonObjectWriter* RenderInt64(StringPiece name, int64 value) override;
124   JsonObjectWriter* RenderUint64(StringPiece name, uint64 value) override;
125   JsonObjectWriter* RenderDouble(StringPiece name, double value) override;
126   JsonObjectWriter* RenderFloat(StringPiece name, float value) override;
127   JsonObjectWriter* RenderString(StringPiece name,
128                                  StringPiece value) override;
129   JsonObjectWriter* RenderBytes(StringPiece name, StringPiece value) override;
130   JsonObjectWriter* RenderNull(StringPiece name) override;
131   virtual JsonObjectWriter* RenderNullAsEmpty(StringPiece name);
132 
set_use_websafe_base64_for_bytes(bool value)133   void set_use_websafe_base64_for_bytes(bool value) {
134     use_websafe_base64_for_bytes_ = value;
135   }
136 
137  protected:
138   class PROTOBUF_EXPORT Element : public BaseElement {
139    public:
Element(Element * parent,bool is_json_object)140     Element(Element* parent, bool is_json_object)
141         : BaseElement(parent),
142           is_first_(true),
143           is_json_object_(is_json_object) {}
144 
145     // Called before each field of the Element is to be processed.
146     // Returns true if this is the first call (processing the first field).
is_first()147     bool is_first() {
148       if (is_first_) {
149         is_first_ = false;
150         return true;
151       }
152       return false;
153     }
154 
155     // Whether we are currently renderring inside a JSON object (i.e., between
156     // StartObject() and EndObject()).
is_json_object()157     bool is_json_object() const { return is_json_object_; }
158 
159    private:
160     bool is_first_;
161     bool is_json_object_;
162 
163     GOOGLE_DISALLOW_IMPLICIT_CONSTRUCTORS(Element);
164   };
165 
element()166   Element* element() override { return element_.get(); }
167 
168  private:
169   class PROTOBUF_EXPORT ByteSinkWrapper : public strings::ByteSink {
170    public:
ByteSinkWrapper(io::CodedOutputStream * stream)171     explicit ByteSinkWrapper(io::CodedOutputStream* stream) : stream_(stream) {}
~ByteSinkWrapper()172     ~ByteSinkWrapper() override {}
173 
174     // ByteSink methods.
Append(const char * bytes,size_t n)175     void Append(const char* bytes, size_t n) override {
176       stream_->WriteRaw(bytes, n);
177     }
178 
179    private:
180     io::CodedOutputStream* stream_;
181 
182     GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ByteSinkWrapper);
183   };
184 
185   // Renders a simple value as a string. By default all non-string Render
186   // methods convert their argument to a string and call this method. This
187   // method can then be used to render the simple value without escaping it.
RenderSimple(StringPiece name,StringPiece value)188   JsonObjectWriter* RenderSimple(StringPiece name,
189                                  StringPiece value) {
190     WritePrefix(name);
191     WriteRawString(value);
192     return this;
193   }
194 
195   // Pushes a new JSON array element to the stack.
PushArray()196   void PushArray() {
197     element_.reset(new Element(element_.release(), /*is_json_object=*/false));
198   }
199 
200   // Pushes a new JSON object element to the stack.
PushObject()201   void PushObject() {
202     element_.reset(new Element(element_.release(), /*is_json_object=*/true));
203   }
204 
205   // Pops an element off of the stack and deletes the popped element.
Pop()206   void Pop() {
207     bool needs_newline = !element_->is_first();
208     element_.reset(element_->pop<Element>());
209     if (needs_newline) NewLine();
210   }
211 
212   // If pretty printing is enabled, this will write a newline to the output,
213   // followed by optional indentation. Otherwise this method is a noop.
NewLine()214   void NewLine() {
215     if (!indent_string_.empty()) {
216       size_t len = sizeof('\n') + (indent_string_.size() * element()->level());
217 
218       // Take the slow-path if we don't have sufficient characters remaining in
219       // our buffer or we have a non-trivial indent string which would prevent
220       // us from using memset.
221       uint8* out = nullptr;
222       if (indent_count_ > 0) {
223         out = stream_->GetDirectBufferForNBytesAndAdvance(len);
224       }
225 
226       if (out != nullptr) {
227         out[0] = '\n';
228         memset(&out[1], indent_char_, len - 1);
229       } else {
230         // Slow path, no contiguous output buffer available.
231         WriteChar('\n');
232         for (int i = 0; i < element()->level(); i++) {
233           stream_->WriteRaw(indent_string_.c_str(), indent_string_.length());
234         }
235       }
236     }
237   }
238 
239   // Writes a prefix. This will write out any pretty printing and
240   // commas that are required, followed by the name and a ':' if
241   // the name is not null.
242   void WritePrefix(StringPiece name);
243 
244   // Writes an individual character to the output.
WriteChar(const char c)245   void WriteChar(const char c) { stream_->WriteRaw(&c, sizeof(c)); }
246 
247   // Writes a string to the output.
WriteRawString(StringPiece s)248   void WriteRawString(StringPiece s) {
249     stream_->WriteRaw(s.data(), s.length());
250   }
251 
252   std::unique_ptr<Element> element_;
253   io::CodedOutputStream* stream_;
254   ByteSinkWrapper sink_;
255   const std::string indent_string_;
256 
257   // For the common case of indent being a single character repeated.
258   char indent_char_;
259   int indent_count_;
260 
261   // Whether to use regular or websafe base64 encoding for byte fields. Defaults
262   // to regular base64 encoding.
263   bool use_websafe_base64_for_bytes_;
264 
265   GOOGLE_DISALLOW_IMPLICIT_CONSTRUCTORS(JsonObjectWriter);
266 };
267 
268 }  // namespace converter
269 }  // namespace util
270 }  // namespace protobuf
271 }  // namespace google
272 
273 #include <google/protobuf/port_undef.inc>
274 
275 #endif  // GOOGLE_PROTOBUF_UTIL_CONVERTER_JSON_OBJECTWRITER_H__
276