• 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 #include <google/protobuf/util/internal/protostream_objectwriter.h>
32 
33 #include <functional>
34 #include <stack>
35 #include <unordered_map>
36 #include <unordered_set>
37 
38 #include <google/protobuf/stubs/once.h>
39 #include <google/protobuf/wire_format_lite.h>
40 #include <google/protobuf/util/internal/field_mask_utility.h>
41 #include <google/protobuf/util/internal/object_location_tracker.h>
42 #include <google/protobuf/util/internal/constants.h>
43 #include <google/protobuf/util/internal/utility.h>
44 #include <google/protobuf/stubs/strutil.h>
45 #include <google/protobuf/stubs/time.h>
46 #include <google/protobuf/stubs/map_util.h>
47 #include <google/protobuf/stubs/statusor.h>
48 
49 
50 #include <google/protobuf/port_def.inc>
51 
52 namespace google {
53 namespace protobuf {
54 namespace util {
55 namespace converter {
56 
57 using ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite;
58 using std::placeholders::_1;
59 using util::Status;
60 using util::StatusOr;
61 using util::error::INVALID_ARGUMENT;
62 
63 
ProtoStreamObjectWriter(TypeResolver * type_resolver,const google::protobuf::Type & type,strings::ByteSink * output,ErrorListener * listener,const ProtoStreamObjectWriter::Options & options)64 ProtoStreamObjectWriter::ProtoStreamObjectWriter(
65     TypeResolver* type_resolver, const google::protobuf::Type& type,
66     strings::ByteSink* output, ErrorListener* listener,
67     const ProtoStreamObjectWriter::Options& options)
68     : ProtoWriter(type_resolver, type, output, listener),
69       master_type_(type),
70       current_(nullptr),
71       options_(options) {
72   set_ignore_unknown_fields(options_.ignore_unknown_fields);
73   set_ignore_unknown_enum_values(options_.ignore_unknown_enum_values);
74   set_use_lower_camel_for_enums(options_.use_lower_camel_for_enums);
75   set_case_insensitive_enum_parsing(options_.case_insensitive_enum_parsing);
76 }
77 
ProtoStreamObjectWriter(const TypeInfo * typeinfo,const google::protobuf::Type & type,strings::ByteSink * output,ErrorListener * listener,const ProtoStreamObjectWriter::Options & options)78 ProtoStreamObjectWriter::ProtoStreamObjectWriter(
79     const TypeInfo* typeinfo, const google::protobuf::Type& type,
80     strings::ByteSink* output, ErrorListener* listener,
81     const ProtoStreamObjectWriter::Options& options)
82     : ProtoWriter(typeinfo, type, output, listener),
83       master_type_(type),
84       current_(nullptr),
85       options_(options) {
86   set_ignore_unknown_fields(options_.ignore_unknown_fields);
87   set_use_lower_camel_for_enums(options.use_lower_camel_for_enums);
88   set_case_insensitive_enum_parsing(options_.case_insensitive_enum_parsing);
89 }
90 
ProtoStreamObjectWriter(const TypeInfo * typeinfo,const google::protobuf::Type & type,strings::ByteSink * output,ErrorListener * listener)91 ProtoStreamObjectWriter::ProtoStreamObjectWriter(
92     const TypeInfo* typeinfo, const google::protobuf::Type& type,
93     strings::ByteSink* output, ErrorListener* listener)
94     : ProtoWriter(typeinfo, type, output, listener),
95       master_type_(type),
96       current_(nullptr),
97       options_(ProtoStreamObjectWriter::Options::Defaults()) {}
98 
~ProtoStreamObjectWriter()99 ProtoStreamObjectWriter::~ProtoStreamObjectWriter() {
100   if (current_ == nullptr) return;
101   // Cleanup explicitly in order to avoid destructor stack overflow when input
102   // is deeply nested.
103   // Cast to BaseElement to avoid doing additional checks (like missing fields)
104   // during pop().
105   std::unique_ptr<BaseElement> element(
106       static_cast<BaseElement*>(current_.get())->pop<BaseElement>());
107   while (element != nullptr) {
108     element.reset(element->pop<BaseElement>());
109   }
110 }
111 
112 namespace {
113 // Utility method to split a string representation of Timestamp or Duration and
114 // return the parts.
SplitSecondsAndNanos(StringPiece input,StringPiece * seconds,StringPiece * nanos)115 void SplitSecondsAndNanos(StringPiece input, StringPiece* seconds,
116                           StringPiece* nanos) {
117   size_t idx = input.rfind('.');
118   if (idx != std::string::npos) {
119     *seconds = input.substr(0, idx);
120     *nanos = input.substr(idx + 1);
121   } else {
122     *seconds = input;
123     *nanos = StringPiece();
124   }
125 }
126 
GetNanosFromStringPiece(StringPiece s_nanos,const char * parse_failure_message,const char * exceeded_limit_message,int32 * nanos)127 Status GetNanosFromStringPiece(StringPiece s_nanos,
128                                const char* parse_failure_message,
129                                const char* exceeded_limit_message,
130                                int32* nanos) {
131   *nanos = 0;
132 
133   // Count the number of leading 0s and consume them.
134   int num_leading_zeros = 0;
135   while (s_nanos.Consume("0")) {
136     num_leading_zeros++;
137   }
138   int32 i_nanos = 0;
139   // 's_nanos' contains fractional seconds -- i.e. 'nanos' is equal to
140   // "0." + s_nanos.ToString() seconds. An int32 is used for the
141   // conversion to 'nanos', rather than a double, so that there is no
142   // loss of precision.
143   if (!s_nanos.empty() && !safe_strto32(s_nanos, &i_nanos)) {
144     return Status(util::error::INVALID_ARGUMENT, parse_failure_message);
145   }
146   if (i_nanos > kNanosPerSecond || i_nanos < 0) {
147     return Status(util::error::INVALID_ARGUMENT, exceeded_limit_message);
148   }
149   // s_nanos should only have digits. No whitespace.
150   if (s_nanos.find_first_not_of("0123456789") != StringPiece::npos) {
151     return Status(util::error::INVALID_ARGUMENT, parse_failure_message);
152   }
153 
154   if (i_nanos > 0) {
155     // 'scale' is the number of digits to the right of the decimal
156     // point in "0." + s_nanos.ToString()
157     int32 scale = num_leading_zeros + s_nanos.size();
158     // 'conversion' converts i_nanos into nanoseconds.
159     // conversion = kNanosPerSecond / static_cast<int32>(std::pow(10, scale))
160     // For efficiency, we precompute the conversion factor.
161     int32 conversion = 0;
162     switch (scale) {
163       case 1:
164         conversion = 100000000;
165         break;
166       case 2:
167         conversion = 10000000;
168         break;
169       case 3:
170         conversion = 1000000;
171         break;
172       case 4:
173         conversion = 100000;
174         break;
175       case 5:
176         conversion = 10000;
177         break;
178       case 6:
179         conversion = 1000;
180         break;
181       case 7:
182         conversion = 100;
183         break;
184       case 8:
185         conversion = 10;
186         break;
187       case 9:
188         conversion = 1;
189         break;
190       default:
191         return Status(util::error::INVALID_ARGUMENT,
192                       exceeded_limit_message);
193     }
194     *nanos = i_nanos * conversion;
195   }
196 
197   return Status();
198 }
199 
200 }  // namespace
201 
AnyWriter(ProtoStreamObjectWriter * parent)202 ProtoStreamObjectWriter::AnyWriter::AnyWriter(ProtoStreamObjectWriter* parent)
203     : parent_(parent),
204       ow_(),
205       invalid_(false),
206       data_(),
207       output_(&data_),
208       depth_(0),
209       is_well_known_type_(false),
210       well_known_type_render_(nullptr) {}
211 
~AnyWriter()212 ProtoStreamObjectWriter::AnyWriter::~AnyWriter() {}
213 
StartObject(StringPiece name)214 void ProtoStreamObjectWriter::AnyWriter::StartObject(StringPiece name) {
215   ++depth_;
216   // If an object writer is absent, that means we have not called StartAny()
217   // before reaching here, which happens when we have data before the "@type"
218   // field.
219   if (ow_ == nullptr) {
220     // Save data before the "@type" field for later replay.
221     uninterpreted_events_.push_back(Event(Event::START_OBJECT, name));
222   } else if (is_well_known_type_ && depth_ == 1) {
223     // For well-known types, the only other field besides "@type" should be a
224     // "value" field.
225     if (name != "value" && !invalid_) {
226       parent_->InvalidValue("Any",
227                             "Expect a \"value\" field for well-known types.");
228       invalid_ = true;
229     }
230     ow_->StartObject("");
231   } else {
232     // Forward the call to the child writer if:
233     //   1. the type is not a well-known type.
234     //   2. or, we are in a nested Any, Struct, or Value object.
235     ow_->StartObject(name);
236   }
237 }
238 
EndObject()239 bool ProtoStreamObjectWriter::AnyWriter::EndObject() {
240   --depth_;
241   if (ow_ == nullptr) {
242     if (depth_ >= 0) {
243       // Save data before the "@type" field for later replay.
244       uninterpreted_events_.push_back(Event(Event::END_OBJECT));
245     }
246   } else if (depth_ >= 0 || !is_well_known_type_) {
247     // As long as depth_ >= 0, we know we haven't reached the end of Any.
248     // Propagate these EndObject() calls to the contained ow_. For regular
249     // message types, we propagate the end of Any as well.
250     ow_->EndObject();
251   }
252   // A negative depth_ implies that we have reached the end of Any
253   // object. Now we write out its contents.
254   if (depth_ < 0) {
255     WriteAny();
256     return false;
257   }
258   return true;
259 }
260 
StartList(StringPiece name)261 void ProtoStreamObjectWriter::AnyWriter::StartList(StringPiece name) {
262   ++depth_;
263   if (ow_ == nullptr) {
264     // Save data before the "@type" field for later replay.
265     uninterpreted_events_.push_back(Event(Event::START_LIST, name));
266   } else if (is_well_known_type_ && depth_ == 1) {
267     if (name != "value" && !invalid_) {
268       parent_->InvalidValue("Any",
269                             "Expect a \"value\" field for well-known types.");
270       invalid_ = true;
271     }
272     ow_->StartList("");
273   } else {
274     ow_->StartList(name);
275   }
276 }
277 
EndList()278 void ProtoStreamObjectWriter::AnyWriter::EndList() {
279   --depth_;
280   if (depth_ < 0) {
281     GOOGLE_LOG(DFATAL) << "Mismatched EndList found, should not be possible";
282     depth_ = 0;
283   }
284   if (ow_ == nullptr) {
285     // Save data before the "@type" field for later replay.
286     uninterpreted_events_.push_back(Event(Event::END_LIST));
287   } else {
288     ow_->EndList();
289   }
290 }
291 
RenderDataPiece(StringPiece name,const DataPiece & value)292 void ProtoStreamObjectWriter::AnyWriter::RenderDataPiece(
293     StringPiece name, const DataPiece& value) {
294   // Start an Any only at depth_ 0. Other RenderDataPiece calls with "@type"
295   // should go to the contained ow_ as they indicate nested Anys.
296   if (depth_ == 0 && ow_ == nullptr && name == "@type") {
297     StartAny(value);
298   } else if (ow_ == nullptr) {
299     // Save data before the "@type" field.
300     uninterpreted_events_.push_back(Event(name, value));
301   } else if (depth_ == 0 && is_well_known_type_) {
302     if (name != "value" && !invalid_) {
303       parent_->InvalidValue("Any",
304                             "Expect a \"value\" field for well-known types.");
305       invalid_ = true;
306     }
307     if (well_known_type_render_ == nullptr) {
308       // Only Any and Struct don't have a special type render but both of
309       // them expect a JSON object (i.e., a StartObject() call).
310       if (value.type() != DataPiece::TYPE_NULL && !invalid_) {
311         parent_->InvalidValue("Any", "Expect a JSON object.");
312         invalid_ = true;
313       }
314     } else {
315       ow_->ProtoWriter::StartObject("");
316       Status status = (*well_known_type_render_)(ow_.get(), value);
317       if (!status.ok()) ow_->InvalidValue("Any", status.message());
318       ow_->ProtoWriter::EndObject();
319     }
320   } else {
321     ow_->RenderDataPiece(name, value);
322   }
323 }
324 
StartAny(const DataPiece & value)325 void ProtoStreamObjectWriter::AnyWriter::StartAny(const DataPiece& value) {
326   // Figure out the type url. This is a copy-paste from WriteString but we also
327   // need the value, so we can't just call through to that.
328   if (value.type() == DataPiece::TYPE_STRING) {
329     type_url_ = std::string(value.str());
330   } else {
331     StatusOr<std::string> s = value.ToString();
332     if (!s.ok()) {
333       parent_->InvalidValue("String", s.status().message());
334       invalid_ = true;
335       return;
336     }
337     type_url_ = s.value();
338   }
339   // Resolve the type url, and report an error if we failed to resolve it.
340   StatusOr<const google::protobuf::Type*> resolved_type =
341       parent_->typeinfo()->ResolveTypeUrl(type_url_);
342   if (!resolved_type.ok()) {
343     parent_->InvalidValue("Any", resolved_type.status().message());
344     invalid_ = true;
345     return;
346   }
347   // At this point, type is never null.
348   const google::protobuf::Type* type = resolved_type.value();
349 
350   well_known_type_render_ = FindTypeRenderer(type_url_);
351   if (well_known_type_render_ != nullptr ||
352       // Explicitly list Any and Struct here because they don't have a
353       // custom renderer.
354       type->name() == kAnyType || type->name() == kStructType) {
355     is_well_known_type_ = true;
356   }
357 
358   // Create our object writer and initialize it with the first StartObject
359   // call.
360   ow_.reset(new ProtoStreamObjectWriter(parent_->typeinfo(), *type, &output_,
361                                         parent_->listener(),
362                                         parent_->options_));
363 
364   // Don't call StartObject() for well-known types yet. Depending on the
365   // type of actual data, we may not need to call StartObject(). For
366   // example:
367   // {
368   //   "@type": "type.googleapis.com/google.protobuf.Value",
369   //   "value": [1, 2, 3],
370   // }
371   // With the above JSON representation, we will only call StartList() on the
372   // contained ow_.
373   if (!is_well_known_type_) {
374     ow_->StartObject("");
375   }
376 
377   // Now we know the proto type and can interpret all data fields we gathered
378   // before the "@type" field.
379   for (int i = 0; i < uninterpreted_events_.size(); ++i) {
380     uninterpreted_events_[i].Replay(this);
381   }
382 }
383 
WriteAny()384 void ProtoStreamObjectWriter::AnyWriter::WriteAny() {
385   if (ow_ == nullptr) {
386     if (uninterpreted_events_.empty()) {
387       // We never got any content, so just return immediately, which is
388       // equivalent to writing an empty Any.
389       return;
390     } else {
391       // There are uninterpreted data, but we never got a "@type" field.
392       if (!invalid_) {
393         parent_->InvalidValue("Any",
394                               StrCat("Missing @type for any field in ",
395                                            parent_->master_type_.name()));
396         invalid_ = true;
397       }
398       return;
399     }
400   }
401   // Render the type_url and value fields directly to the stream.
402   // type_url has tag 1 and value has tag 2.
403   WireFormatLite::WriteString(1, type_url_, parent_->stream());
404   if (!data_.empty()) {
405     WireFormatLite::WriteBytes(2, data_, parent_->stream());
406   }
407 }
408 
Replay(AnyWriter * writer) const409 void ProtoStreamObjectWriter::AnyWriter::Event::Replay(
410     AnyWriter* writer) const {
411   switch (type_) {
412     case START_OBJECT:
413       writer->StartObject(name_);
414       break;
415     case END_OBJECT:
416       writer->EndObject();
417       break;
418     case START_LIST:
419       writer->StartList(name_);
420       break;
421     case END_LIST:
422       writer->EndList();
423       break;
424     case RENDER_DATA_PIECE:
425       writer->RenderDataPiece(name_, value_);
426       break;
427   }
428 }
429 
DeepCopy()430 void ProtoStreamObjectWriter::AnyWriter::Event::DeepCopy() {
431   // DataPiece only contains a string reference. To make sure the referenced
432   // string value stays valid, we make a copy of the string value and update
433   // DataPiece to reference our own copy.
434   if (value_.type() == DataPiece::TYPE_STRING) {
435     StrAppend(&value_storage_, value_.str());
436     value_ = DataPiece(value_storage_, value_.use_strict_base64_decoding());
437   } else if (value_.type() == DataPiece::TYPE_BYTES) {
438     value_storage_ = value_.ToBytes().ValueOrDie();
439     value_ =
440         DataPiece(value_storage_, true, value_.use_strict_base64_decoding());
441   }
442 }
443 
Item(ProtoStreamObjectWriter * enclosing,ItemType item_type,bool is_placeholder,bool is_list)444 ProtoStreamObjectWriter::Item::Item(ProtoStreamObjectWriter* enclosing,
445                                     ItemType item_type, bool is_placeholder,
446                                     bool is_list)
447     : BaseElement(nullptr),
448       ow_(enclosing),
449       any_(),
450       item_type_(item_type),
451       is_placeholder_(is_placeholder),
452       is_list_(is_list) {
453   if (item_type_ == ANY) {
454     any_.reset(new AnyWriter(ow_));
455   }
456   if (item_type == MAP) {
457     map_keys_.reset(new std::unordered_set<std::string>);
458   }
459 }
460 
Item(ProtoStreamObjectWriter::Item * parent,ItemType item_type,bool is_placeholder,bool is_list)461 ProtoStreamObjectWriter::Item::Item(ProtoStreamObjectWriter::Item* parent,
462                                     ItemType item_type, bool is_placeholder,
463                                     bool is_list)
464     : BaseElement(parent),
465       ow_(this->parent()->ow_),
466       any_(),
467       item_type_(item_type),
468       is_placeholder_(is_placeholder),
469       is_list_(is_list) {
470   if (item_type == ANY) {
471     any_.reset(new AnyWriter(ow_));
472   }
473   if (item_type == MAP) {
474     map_keys_.reset(new std::unordered_set<std::string>);
475   }
476 }
477 
InsertMapKeyIfNotPresent(StringPiece map_key)478 bool ProtoStreamObjectWriter::Item::InsertMapKeyIfNotPresent(
479     StringPiece map_key) {
480   return InsertIfNotPresent(map_keys_.get(), std::string(map_key));
481 }
482 
483 
StartObject(StringPiece name)484 ProtoStreamObjectWriter* ProtoStreamObjectWriter::StartObject(
485     StringPiece name) {
486   if (invalid_depth() > 0) {
487     IncrementInvalidDepth();
488     return this;
489   }
490 
491   // Starting the root message. Create the root Item and return.
492   // ANY message type does not need special handling, just set the ItemType
493   // to ANY.
494   if (current_ == nullptr) {
495     ProtoWriter::StartObject(name);
496     current_.reset(new Item(
497         this, master_type_.name() == kAnyType ? Item::ANY : Item::MESSAGE,
498         false, false));
499 
500     // If master type is a special type that needs extra values to be written to
501     // stream, we write those values.
502     if (master_type_.name() == kStructType) {
503       // Struct has a map<string, Value> field called "fields".
504       // https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/struct.proto
505       // "fields": [
506       Push("fields", Item::MAP, true, true);
507       return this;
508     }
509 
510     if (master_type_.name() == kStructValueType) {
511       // We got a StartObject call with google.protobuf.Value field. The only
512       // object within that type is a struct type. So start a struct.
513       //
514       // The struct field in Value type is named "struct_value"
515       // https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/struct.proto
516       // Also start the map field "fields" within the struct.
517       // "struct_value": {
518       //   "fields": [
519       Push("struct_value", Item::MESSAGE, true, false);
520       Push("fields", Item::MAP, true, true);
521       return this;
522     }
523 
524     if (master_type_.name() == kStructListValueType) {
525       InvalidValue(kStructListValueType,
526                    "Cannot start root message with ListValue.");
527     }
528 
529     return this;
530   }
531 
532   // Send all ANY events to AnyWriter.
533   if (current_->IsAny()) {
534     current_->any()->StartObject(name);
535     return this;
536   }
537 
538   // If we are within a map, we render name as keys and send StartObject to the
539   // value field.
540   if (current_->IsMap()) {
541     if (!ValidMapKey(name)) {
542       IncrementInvalidDepth();
543       return this;
544     }
545 
546     // Map is a repeated field of message type with a "key" and a "value" field.
547     // https://developers.google.com/protocol-buffers/docs/proto3?hl=en#maps
548     // message MapFieldEntry {
549     //   key_type key = 1;
550     //   value_type value = 2;
551     // }
552     //
553     // repeated MapFieldEntry map_field = N;
554     //
555     // That means, we render the following element within a list (hence no
556     // name):
557     // { "key": "<name>", "value": {
558     Push("", Item::MESSAGE, false, false);
559     ProtoWriter::RenderDataPiece("key",
560                                  DataPiece(name, use_strict_base64_decoding()));
561     Push("value", IsAny(*Lookup("value")) ? Item::ANY : Item::MESSAGE, true,
562          false);
563 
564     // Make sure we are valid so far after starting map fields.
565     if (invalid_depth() > 0) return this;
566 
567     // If top of stack is g.p.Struct type, start the struct the map field within
568     // it.
569     if (element() != nullptr && IsStruct(*element()->parent_field())) {
570       // Render "fields": [
571       Push("fields", Item::MAP, true, true);
572       return this;
573     }
574 
575     // If top of stack is g.p.Value type, start the Struct within it.
576     if (element() != nullptr && IsStructValue(*element()->parent_field())) {
577       // Render
578       // "struct_value": {
579       //   "fields": [
580       Push("struct_value", Item::MESSAGE, true, false);
581       Push("fields", Item::MAP, true, true);
582     }
583     return this;
584   }
585 
586   const google::protobuf::Field* field = BeginNamed(name, false);
587 
588   if (field == nullptr) return this;
589 
590   if (IsStruct(*field)) {
591     // Start a struct object.
592     // Render
593     // "<name>": {
594     //   "fields": {
595     Push(name, Item::MESSAGE, false, false);
596     Push("fields", Item::MAP, true, true);
597     return this;
598   }
599 
600   if (IsStructValue(*field)) {
601     // We got a StartObject call with google.protobuf.Value field.  The only
602     // object within that type is a struct type. So start a struct.
603     // Render
604     // "<name>": {
605     //   "struct_value": {
606     //     "fields": {
607     Push(name, Item::MESSAGE, false, false);
608     Push("struct_value", Item::MESSAGE, true, false);
609     Push("fields", Item::MAP, true, true);
610     return this;
611   }
612 
613   // Legacy JSON map is a list of key value pairs. Starts a map entry object.
614   if (options_.use_legacy_json_map_format && name.empty()) {
615     Push(name, IsAny(*field) ? Item::ANY : Item::MESSAGE, false, false);
616     return this;
617   }
618 
619   if (IsMap(*field)) {
620     // Begin a map. A map is triggered by a StartObject() call if the current
621     // field has a map type.
622     // A map type is always repeated, hence set is_list to true.
623     // Render
624     // "<name>": [
625     Push(name, Item::MAP, false, true);
626     return this;
627   }
628 
629   // A regular message type. Pass it directly to ProtoWriter.
630   // Render
631   // "<name>": {
632   Push(name, IsAny(*field) ? Item::ANY : Item::MESSAGE, false, false);
633   return this;
634 }
635 
EndObject()636 ProtoStreamObjectWriter* ProtoStreamObjectWriter::EndObject() {
637   if (invalid_depth() > 0) {
638     DecrementInvalidDepth();
639     return this;
640   }
641 
642   if (current_ == nullptr) return this;
643 
644   if (current_->IsAny()) {
645     if (current_->any()->EndObject()) return this;
646   }
647 
648   Pop();
649 
650   return this;
651 }
652 
653 
StartList(StringPiece name)654 ProtoStreamObjectWriter* ProtoStreamObjectWriter::StartList(
655     StringPiece name) {
656   if (invalid_depth() > 0) {
657     IncrementInvalidDepth();
658     return this;
659   }
660 
661   // Since we cannot have a top-level repeated item in protobuf, the only way
662   // this is valid is if we start a special type google.protobuf.ListValue or
663   // google.protobuf.Value.
664   if (current_ == nullptr) {
665     if (!name.empty()) {
666       InvalidName(name, "Root element should not be named.");
667       IncrementInvalidDepth();
668       return this;
669     }
670 
671     // If master type is a special type that needs extra values to be written to
672     // stream, we write those values.
673     if (master_type_.name() == kStructValueType) {
674       // We got a StartList with google.protobuf.Value master type. This means
675       // we have to start the "list_value" within google.protobuf.Value.
676       //
677       // See
678       // https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/struct.proto
679       //
680       // Render
681       // "<name>": {
682       //   "list_value": {
683       //     "values": [  // Start this list.
684       ProtoWriter::StartObject(name);
685       current_.reset(new Item(this, Item::MESSAGE, false, false));
686       Push("list_value", Item::MESSAGE, true, false);
687       Push("values", Item::MESSAGE, true, true);
688       return this;
689     }
690 
691     if (master_type_.name() == kStructListValueType) {
692       // We got a StartList with google.protobuf.ListValue master type. This
693       // means we have to start the "values" within google.protobuf.ListValue.
694       //
695       // Render
696       // "<name>": {
697       //   "values": [  // Start this list.
698       ProtoWriter::StartObject(name);
699       current_.reset(new Item(this, Item::MESSAGE, false, false));
700       Push("values", Item::MESSAGE, true, true);
701       return this;
702     }
703 
704     // Send the event to ProtoWriter so proper errors can be reported.
705     //
706     // Render a regular list:
707     // "<name>": [
708     ProtoWriter::StartList(name);
709     current_.reset(new Item(this, Item::MESSAGE, false, true));
710     return this;
711   }
712 
713   if (current_->IsAny()) {
714     current_->any()->StartList(name);
715     return this;
716   }
717 
718   // If the top of stack is a map, we are starting a list value within a map.
719   // Since map does not allow repeated values, this can only happen when the map
720   // value is of a special type that renders a list in JSON.  These can be one
721   // of 3 cases:
722   // i. We are rendering a list value within google.protobuf.Struct
723   // ii. We are rendering a list value within google.protobuf.Value
724   // iii. We are rendering a list value with type google.protobuf.ListValue.
725   if (current_->IsMap()) {
726     if (!ValidMapKey(name)) {
727       IncrementInvalidDepth();
728       return this;
729     }
730 
731     // Start the repeated map entry object.
732     // Render
733     // { "key": "<name>", "value": {
734     Push("", Item::MESSAGE, false, false);
735     ProtoWriter::RenderDataPiece("key",
736                                  DataPiece(name, use_strict_base64_decoding()));
737     Push("value", Item::MESSAGE, true, false);
738 
739     // Make sure we are valid after pushing all above items.
740     if (invalid_depth() > 0) return this;
741 
742     // case i and ii above. Start "list_value" field within g.p.Value
743     if (element() != nullptr && element()->parent_field() != nullptr) {
744       // Render
745       // "list_value": {
746       //   "values": [  // Start this list
747       if (IsStructValue(*element()->parent_field())) {
748         Push("list_value", Item::MESSAGE, true, false);
749         Push("values", Item::MESSAGE, true, true);
750         return this;
751       }
752 
753       // Render
754       // "values": [
755       if (IsStructListValue(*element()->parent_field())) {
756         // case iii above. Bind directly to g.p.ListValue
757         Push("values", Item::MESSAGE, true, true);
758         return this;
759       }
760     }
761 
762     // Report an error.
763     InvalidValue("Map", StrCat("Cannot have repeated items ('", name,
764                                      "') within a map."));
765     return this;
766   }
767 
768   // When name is empty and stack is not empty, we are rendering an item within
769   // a list.
770   if (name.empty()) {
771     if (element() != nullptr && element()->parent_field() != nullptr) {
772       if (IsStructValue(*element()->parent_field())) {
773         // Since it is g.p.Value, we bind directly to the list_value.
774         // Render
775         // {  // g.p.Value item within the list
776         //   "list_value": {
777         //     "values": [
778         Push("", Item::MESSAGE, false, false);
779         Push("list_value", Item::MESSAGE, true, false);
780         Push("values", Item::MESSAGE, true, true);
781         return this;
782       }
783 
784       if (IsStructListValue(*element()->parent_field())) {
785         // Since it is g.p.ListValue, we bind to it directly.
786         // Render
787         // {  // g.p.ListValue item within the list
788         //   "values": [
789         Push("", Item::MESSAGE, false, false);
790         Push("values", Item::MESSAGE, true, true);
791         return this;
792       }
793     }
794 
795     // Pass the event to underlying ProtoWriter.
796     Push(name, Item::MESSAGE, false, true);
797     return this;
798   }
799 
800   // name is not empty
801   const google::protobuf::Field* field = Lookup(name);
802 
803   if (field == nullptr) {
804     IncrementInvalidDepth();
805     return this;
806   }
807 
808   if (IsStructValue(*field)) {
809     // If g.p.Value is repeated, start that list. Otherwise, start the
810     // "list_value" within it.
811     if (IsRepeated(*field)) {
812       // Render it just like a regular repeated field.
813       // "<name>": [
814       Push(name, Item::MESSAGE, false, true);
815       return this;
816     }
817 
818     // Start the "list_value" field.
819     // Render
820     // "<name>": {
821     //   "list_value": {
822     //     "values": [
823     Push(name, Item::MESSAGE, false, false);
824     Push("list_value", Item::MESSAGE, true, false);
825     Push("values", Item::MESSAGE, true, true);
826     return this;
827   }
828 
829   if (IsStructListValue(*field)) {
830     // If g.p.ListValue is repeated, start that list. Otherwise, start the
831     // "values" within it.
832     if (IsRepeated(*field)) {
833       // Render it just like a regular repeated field.
834       // "<name>": [
835       Push(name, Item::MESSAGE, false, true);
836       return this;
837     }
838 
839     // Start the "values" field within g.p.ListValue.
840     // Render
841     // "<name>": {
842     //   "values": [
843     Push(name, Item::MESSAGE, false, false);
844     Push("values", Item::MESSAGE, true, true);
845     return this;
846   }
847 
848   // If we are here, the field should be repeated. Report an error otherwise.
849   if (!IsRepeated(*field)) {
850     IncrementInvalidDepth();
851     InvalidName(name, "Proto field is not repeating, cannot start list.");
852     return this;
853   }
854 
855   if (IsMap(*field)) {
856     if (options_.use_legacy_json_map_format) {
857       Push(name, Item::MESSAGE, false, true);
858       return this;
859     }
860     InvalidValue("Map", StrCat("Cannot bind a list to map for field '",
861                                      name, "'."));
862     IncrementInvalidDepth();
863     return this;
864   }
865 
866   // Pass the event to ProtoWriter.
867   // Render
868   // "<name>": [
869   Push(name, Item::MESSAGE, false, true);
870   return this;
871 }
872 
EndList()873 ProtoStreamObjectWriter* ProtoStreamObjectWriter::EndList() {
874   if (invalid_depth() > 0) {
875     DecrementInvalidDepth();
876     return this;
877   }
878 
879   if (current_ == nullptr) return this;
880 
881   if (current_->IsAny()) {
882     current_->any()->EndList();
883     return this;
884   }
885 
886   Pop();
887   return this;
888 }
889 
RenderStructValue(ProtoStreamObjectWriter * ow,const DataPiece & data)890 Status ProtoStreamObjectWriter::RenderStructValue(ProtoStreamObjectWriter* ow,
891                                                   const DataPiece& data) {
892   std::string struct_field_name;
893   switch (data.type()) {
894     case DataPiece::TYPE_INT32: {
895       if (ow->options_.struct_integers_as_strings) {
896         StatusOr<int32> int_value = data.ToInt32();
897         if (int_value.ok()) {
898           ow->ProtoWriter::RenderDataPiece(
899               "string_value",
900               DataPiece(SimpleDtoa(int_value.value()), true));
901           return Status();
902         }
903       }
904       struct_field_name = "number_value";
905       break;
906     }
907     case DataPiece::TYPE_UINT32: {
908       if (ow->options_.struct_integers_as_strings) {
909         StatusOr<uint32> int_value = data.ToUint32();
910         if (int_value.ok()) {
911           ow->ProtoWriter::RenderDataPiece(
912               "string_value",
913               DataPiece(SimpleDtoa(int_value.value()), true));
914           return Status();
915         }
916       }
917       struct_field_name = "number_value";
918       break;
919     }
920     case DataPiece::TYPE_INT64: {
921       // If the option to treat integers as strings is set, then render them as
922       // strings. Otherwise, fallback to rendering them as double.
923       if (ow->options_.struct_integers_as_strings) {
924         StatusOr<int64> int_value = data.ToInt64();
925         if (int_value.ok()) {
926           ow->ProtoWriter::RenderDataPiece(
927               "string_value", DataPiece(StrCat(int_value.value()), true));
928           return Status();
929         }
930       }
931       struct_field_name = "number_value";
932       break;
933     }
934     case DataPiece::TYPE_UINT64: {
935       // If the option to treat integers as strings is set, then render them as
936       // strings. Otherwise, fallback to rendering them as double.
937       if (ow->options_.struct_integers_as_strings) {
938         StatusOr<uint64> int_value = data.ToUint64();
939         if (int_value.ok()) {
940           ow->ProtoWriter::RenderDataPiece(
941               "string_value", DataPiece(StrCat(int_value.value()), true));
942           return Status();
943         }
944       }
945       struct_field_name = "number_value";
946       break;
947     }
948     case DataPiece::TYPE_FLOAT: {
949       if (ow->options_.struct_integers_as_strings) {
950         StatusOr<float> float_value = data.ToFloat();
951         if (float_value.ok()) {
952           ow->ProtoWriter::RenderDataPiece(
953               "string_value",
954               DataPiece(SimpleDtoa(float_value.value()), true));
955           return Status();
956         }
957       }
958       struct_field_name = "number_value";
959       break;
960     }
961     case DataPiece::TYPE_DOUBLE: {
962       if (ow->options_.struct_integers_as_strings) {
963         StatusOr<double> double_value = data.ToDouble();
964         if (double_value.ok()) {
965           ow->ProtoWriter::RenderDataPiece(
966               "string_value",
967               DataPiece(SimpleDtoa(double_value.value()), true));
968           return Status();
969         }
970       }
971       struct_field_name = "number_value";
972       break;
973     }
974     case DataPiece::TYPE_STRING: {
975       struct_field_name = "string_value";
976       break;
977     }
978     case DataPiece::TYPE_BOOL: {
979       struct_field_name = "bool_value";
980       break;
981     }
982     case DataPiece::TYPE_NULL: {
983       struct_field_name = "null_value";
984       break;
985     }
986     default: {
987       return Status(util::error::INVALID_ARGUMENT,
988                     "Invalid struct data type. Only number, string, boolean or "
989                     "null values are supported.");
990     }
991   }
992   ow->ProtoWriter::RenderDataPiece(struct_field_name, data);
993   return Status();
994 }
995 
RenderTimestamp(ProtoStreamObjectWriter * ow,const DataPiece & data)996 Status ProtoStreamObjectWriter::RenderTimestamp(ProtoStreamObjectWriter* ow,
997                                                 const DataPiece& data) {
998   if (data.type() == DataPiece::TYPE_NULL) return Status();
999   if (data.type() != DataPiece::TYPE_STRING) {
1000     return Status(util::error::INVALID_ARGUMENT,
1001                   StrCat("Invalid data type for timestamp, value is ",
1002                                data.ValueAsStringOrDefault("")));
1003   }
1004 
1005   StringPiece value(data.str());
1006 
1007   int64 seconds;
1008   int32 nanos;
1009   if (!::google::protobuf::internal::ParseTime(value.ToString(), &seconds,
1010                                                &nanos)) {
1011     return Status(INVALID_ARGUMENT, StrCat("Invalid time format: ", value));
1012   }
1013 
1014 
1015   ow->ProtoWriter::RenderDataPiece("seconds", DataPiece(seconds));
1016   ow->ProtoWriter::RenderDataPiece("nanos", DataPiece(nanos));
1017   return Status();
1018 }
1019 
RenderOneFieldPath(ProtoStreamObjectWriter * ow,StringPiece path)1020 static inline util::Status RenderOneFieldPath(ProtoStreamObjectWriter* ow,
1021                                                 StringPiece path) {
1022   ow->ProtoWriter::RenderDataPiece(
1023       "paths", DataPiece(ConvertFieldMaskPath(path, &ToSnakeCase), true));
1024   return Status();
1025 }
1026 
RenderFieldMask(ProtoStreamObjectWriter * ow,const DataPiece & data)1027 Status ProtoStreamObjectWriter::RenderFieldMask(ProtoStreamObjectWriter* ow,
1028                                                 const DataPiece& data) {
1029   if (data.type() == DataPiece::TYPE_NULL) return Status();
1030   if (data.type() != DataPiece::TYPE_STRING) {
1031     return Status(util::error::INVALID_ARGUMENT,
1032                   StrCat("Invalid data type for field mask, value is ",
1033                                data.ValueAsStringOrDefault("")));
1034   }
1035 
1036   // TODO(tsun): figure out how to do proto descriptor based snake case
1037   // conversions as much as possible. Because ToSnakeCase sometimes returns the
1038   // wrong value.
1039   return DecodeCompactFieldMaskPaths(data.str(),
1040                                      std::bind(&RenderOneFieldPath, ow, _1));
1041 }
1042 
RenderDuration(ProtoStreamObjectWriter * ow,const DataPiece & data)1043 Status ProtoStreamObjectWriter::RenderDuration(ProtoStreamObjectWriter* ow,
1044                                                const DataPiece& data) {
1045   if (data.type() == DataPiece::TYPE_NULL) return Status();
1046   if (data.type() != DataPiece::TYPE_STRING) {
1047     return Status(util::error::INVALID_ARGUMENT,
1048                   StrCat("Invalid data type for duration, value is ",
1049                                data.ValueAsStringOrDefault("")));
1050   }
1051 
1052   StringPiece value(data.str());
1053 
1054   if (!HasSuffixString(value, "s")) {
1055     return Status(util::error::INVALID_ARGUMENT,
1056                   "Illegal duration format; duration must end with 's'");
1057   }
1058   value = value.substr(0, value.size() - 1);
1059   int sign = 1;
1060   if (HasPrefixString(value, "-")) {
1061     sign = -1;
1062     value = value.substr(1);
1063   }
1064 
1065   StringPiece s_secs, s_nanos;
1066   SplitSecondsAndNanos(value, &s_secs, &s_nanos);
1067   uint64 unsigned_seconds;
1068   if (!safe_strtou64(s_secs, &unsigned_seconds)) {
1069     return Status(util::error::INVALID_ARGUMENT,
1070                   "Invalid duration format, failed to parse seconds");
1071   }
1072 
1073   int32 nanos = 0;
1074   Status nanos_status = GetNanosFromStringPiece(
1075       s_nanos, "Invalid duration format, failed to parse nano seconds",
1076       "Duration value exceeds limits", &nanos);
1077   if (!nanos_status.ok()) {
1078     return nanos_status;
1079   }
1080   nanos = sign * nanos;
1081 
1082   int64 seconds = sign * unsigned_seconds;
1083   if (seconds > kDurationMaxSeconds || seconds < kDurationMinSeconds ||
1084       nanos <= -kNanosPerSecond || nanos >= kNanosPerSecond) {
1085     return Status(util::error::INVALID_ARGUMENT,
1086                   "Duration value exceeds limits");
1087   }
1088 
1089   ow->ProtoWriter::RenderDataPiece("seconds", DataPiece(seconds));
1090   ow->ProtoWriter::RenderDataPiece("nanos", DataPiece(nanos));
1091   return Status();
1092 }
1093 
RenderWrapperType(ProtoStreamObjectWriter * ow,const DataPiece & data)1094 Status ProtoStreamObjectWriter::RenderWrapperType(ProtoStreamObjectWriter* ow,
1095                                                   const DataPiece& data) {
1096   if (data.type() == DataPiece::TYPE_NULL) return Status();
1097   ow->ProtoWriter::RenderDataPiece("value", data);
1098   return Status();
1099 }
1100 
RenderDataPiece(StringPiece name,const DataPiece & data)1101 ProtoStreamObjectWriter* ProtoStreamObjectWriter::RenderDataPiece(
1102     StringPiece name, const DataPiece& data) {
1103   Status status;
1104   if (invalid_depth() > 0) return this;
1105 
1106   if (current_ == nullptr) {
1107     const TypeRenderer* type_renderer =
1108         FindTypeRenderer(GetFullTypeWithUrl(master_type_.name()));
1109     if (type_renderer == nullptr) {
1110       InvalidName(name, "Root element must be a message.");
1111       return this;
1112     }
1113     // Render the special type.
1114     // "<name>": {
1115     //   ... Render special type ...
1116     // }
1117     ProtoWriter::StartObject(name);
1118     status = (*type_renderer)(this, data);
1119     if (!status.ok()) {
1120       InvalidValue(master_type_.name(),
1121                    StrCat("Field '", name, "', ", status.message()));
1122     }
1123     ProtoWriter::EndObject();
1124     return this;
1125   }
1126 
1127   if (current_->IsAny()) {
1128     current_->any()->RenderDataPiece(name, data);
1129     return this;
1130   }
1131 
1132   const google::protobuf::Field* field = nullptr;
1133   if (current_->IsMap()) {
1134     if (!ValidMapKey(name)) return this;
1135 
1136     field = Lookup("value");
1137     if (field == nullptr) {
1138       GOOGLE_LOG(DFATAL) << "Map does not have a value field.";
1139       return this;
1140     }
1141 
1142     if (options_.ignore_null_value_map_entry) {
1143       // If we are rendering explicit null values and the backend proto field is
1144       // not of the google.protobuf.NullType type, interpret null as absence.
1145       if (data.type() == DataPiece::TYPE_NULL &&
1146           field->type_url() != kStructNullValueTypeUrl) {
1147         return this;
1148       }
1149     }
1150 
1151     // Render an item in repeated map list.
1152     // { "key": "<name>", "value":
1153     Push("", Item::MESSAGE, false, false);
1154     ProtoWriter::RenderDataPiece("key",
1155                                  DataPiece(name, use_strict_base64_decoding()));
1156 
1157     const TypeRenderer* type_renderer = FindTypeRenderer(field->type_url());
1158     if (type_renderer != nullptr) {
1159       // Map's value type is a special type. Render it like a message:
1160       // "value": {
1161       //   ... Render special type ...
1162       // }
1163       Push("value", Item::MESSAGE, true, false);
1164       status = (*type_renderer)(this, data);
1165       if (!status.ok()) {
1166         InvalidValue(field->type_url(),
1167                      StrCat("Field '", name, "', ", status.message()));
1168       }
1169       Pop();
1170       return this;
1171     }
1172 
1173     // If we are rendering explicit null values and the backend proto field is
1174     // not of the google.protobuf.NullType type, we do nothing.
1175     if (data.type() == DataPiece::TYPE_NULL &&
1176         field->type_url() != kStructNullValueTypeUrl) {
1177       Pop();
1178       return this;
1179     }
1180 
1181     // Render the map value as a primitive type.
1182     ProtoWriter::RenderDataPiece("value", data);
1183     Pop();
1184     return this;
1185   }
1186 
1187   field = Lookup(name);
1188   if (field == nullptr) return this;
1189 
1190   // Check if the field is of special type. Render it accordingly if so.
1191   const TypeRenderer* type_renderer = FindTypeRenderer(field->type_url());
1192   if (type_renderer != nullptr) {
1193     // Pass through null value only for google.protobuf.Value. For other
1194     // types we ignore null value just like for regular field types.
1195     if (data.type() != DataPiece::TYPE_NULL ||
1196         field->type_url() == kStructValueTypeUrl) {
1197       Push(name, Item::MESSAGE, false, false);
1198       status = (*type_renderer)(this, data);
1199       if (!status.ok()) {
1200         InvalidValue(field->type_url(),
1201                      StrCat("Field '", name, "', ", status.message()));
1202       }
1203       Pop();
1204     }
1205     return this;
1206   }
1207 
1208   // If we are rendering explicit null values and the backend proto field is
1209   // not of the google.protobuf.NullType type, we do nothing.
1210   if (data.type() == DataPiece::TYPE_NULL &&
1211       field->type_url() != kStructNullValueTypeUrl) {
1212     return this;
1213   }
1214 
1215   ProtoWriter::RenderDataPiece(name, data);
1216   return this;
1217 }
1218 
1219 // Map of functions that are responsible for rendering well known type
1220 // represented by the key.
1221 std::unordered_map<std::string, ProtoStreamObjectWriter::TypeRenderer>*
1222     ProtoStreamObjectWriter::renderers_ = nullptr;
1223 PROTOBUF_NAMESPACE_ID::internal::once_flag writer_renderers_init_;
1224 
InitRendererMap()1225 void ProtoStreamObjectWriter::InitRendererMap() {
1226   renderers_ = new std::unordered_map<std::string,
1227                                       ProtoStreamObjectWriter::TypeRenderer>();
1228   (*renderers_)["type.googleapis.com/google.protobuf.Timestamp"] =
1229       &ProtoStreamObjectWriter::RenderTimestamp;
1230   (*renderers_)["type.googleapis.com/google.protobuf.Duration"] =
1231       &ProtoStreamObjectWriter::RenderDuration;
1232   (*renderers_)["type.googleapis.com/google.protobuf.FieldMask"] =
1233       &ProtoStreamObjectWriter::RenderFieldMask;
1234   (*renderers_)["type.googleapis.com/google.protobuf.Double"] =
1235       &ProtoStreamObjectWriter::RenderWrapperType;
1236   (*renderers_)["type.googleapis.com/google.protobuf.Float"] =
1237       &ProtoStreamObjectWriter::RenderWrapperType;
1238   (*renderers_)["type.googleapis.com/google.protobuf.Int64"] =
1239       &ProtoStreamObjectWriter::RenderWrapperType;
1240   (*renderers_)["type.googleapis.com/google.protobuf.UInt64"] =
1241       &ProtoStreamObjectWriter::RenderWrapperType;
1242   (*renderers_)["type.googleapis.com/google.protobuf.Int32"] =
1243       &ProtoStreamObjectWriter::RenderWrapperType;
1244   (*renderers_)["type.googleapis.com/google.protobuf.UInt32"] =
1245       &ProtoStreamObjectWriter::RenderWrapperType;
1246   (*renderers_)["type.googleapis.com/google.protobuf.Bool"] =
1247       &ProtoStreamObjectWriter::RenderWrapperType;
1248   (*renderers_)["type.googleapis.com/google.protobuf.String"] =
1249       &ProtoStreamObjectWriter::RenderWrapperType;
1250   (*renderers_)["type.googleapis.com/google.protobuf.Bytes"] =
1251       &ProtoStreamObjectWriter::RenderWrapperType;
1252   (*renderers_)["type.googleapis.com/google.protobuf.DoubleValue"] =
1253       &ProtoStreamObjectWriter::RenderWrapperType;
1254   (*renderers_)["type.googleapis.com/google.protobuf.FloatValue"] =
1255       &ProtoStreamObjectWriter::RenderWrapperType;
1256   (*renderers_)["type.googleapis.com/google.protobuf.Int64Value"] =
1257       &ProtoStreamObjectWriter::RenderWrapperType;
1258   (*renderers_)["type.googleapis.com/google.protobuf.UInt64Value"] =
1259       &ProtoStreamObjectWriter::RenderWrapperType;
1260   (*renderers_)["type.googleapis.com/google.protobuf.Int32Value"] =
1261       &ProtoStreamObjectWriter::RenderWrapperType;
1262   (*renderers_)["type.googleapis.com/google.protobuf.UInt32Value"] =
1263       &ProtoStreamObjectWriter::RenderWrapperType;
1264   (*renderers_)["type.googleapis.com/google.protobuf.BoolValue"] =
1265       &ProtoStreamObjectWriter::RenderWrapperType;
1266   (*renderers_)["type.googleapis.com/google.protobuf.StringValue"] =
1267       &ProtoStreamObjectWriter::RenderWrapperType;
1268   (*renderers_)["type.googleapis.com/google.protobuf.BytesValue"] =
1269       &ProtoStreamObjectWriter::RenderWrapperType;
1270   (*renderers_)["type.googleapis.com/google.protobuf.Value"] =
1271       &ProtoStreamObjectWriter::RenderStructValue;
1272   ::google::protobuf::internal::OnShutdown(&DeleteRendererMap);
1273 }
1274 
DeleteRendererMap()1275 void ProtoStreamObjectWriter::DeleteRendererMap() {
1276   delete ProtoStreamObjectWriter::renderers_;
1277   renderers_ = nullptr;
1278 }
1279 
1280 ProtoStreamObjectWriter::TypeRenderer*
FindTypeRenderer(const std::string & type_url)1281 ProtoStreamObjectWriter::FindTypeRenderer(const std::string& type_url) {
1282   PROTOBUF_NAMESPACE_ID::internal::call_once(writer_renderers_init_,
1283                                              InitRendererMap);
1284   return FindOrNull(*renderers_, type_url);
1285 }
1286 
ValidMapKey(StringPiece unnormalized_name)1287 bool ProtoStreamObjectWriter::ValidMapKey(StringPiece unnormalized_name) {
1288   if (current_ == nullptr) return true;
1289 
1290   if (!current_->InsertMapKeyIfNotPresent(unnormalized_name)) {
1291     listener()->InvalidName(
1292         location(), unnormalized_name,
1293         StrCat("Repeated map key: '", unnormalized_name,
1294                      "' is already set."));
1295     return false;
1296   }
1297 
1298   return true;
1299 }
1300 
Push(StringPiece name,Item::ItemType item_type,bool is_placeholder,bool is_list)1301 void ProtoStreamObjectWriter::Push(
1302     StringPiece name, Item::ItemType item_type, bool is_placeholder,
1303     bool is_list) {
1304   is_list ? ProtoWriter::StartList(name) : ProtoWriter::StartObject(name);
1305 
1306   // invalid_depth == 0 means it is a successful StartObject or StartList.
1307   if (invalid_depth() == 0)
1308     current_.reset(
1309         new Item(current_.release(), item_type, is_placeholder, is_list));
1310 }
1311 
Pop()1312 void ProtoStreamObjectWriter::Pop() {
1313   // Pop all placeholder items sending StartObject or StartList events to
1314   // ProtoWriter according to is_list value.
1315   while (current_ != nullptr && current_->is_placeholder()) {
1316     PopOneElement();
1317   }
1318   if (current_ != nullptr) {
1319     PopOneElement();
1320   }
1321 }
1322 
PopOneElement()1323 void ProtoStreamObjectWriter::PopOneElement() {
1324   current_->is_list() ? ProtoWriter::EndList() : ProtoWriter::EndObject();
1325   current_.reset(current_->pop<Item>());
1326 }
1327 
IsMap(const google::protobuf::Field & field)1328 bool ProtoStreamObjectWriter::IsMap(const google::protobuf::Field& field) {
1329   if (field.type_url().empty() ||
1330       field.kind() != google::protobuf::Field::TYPE_MESSAGE ||
1331       field.cardinality() != google::protobuf::Field::CARDINALITY_REPEATED) {
1332     return false;
1333   }
1334   const google::protobuf::Type* field_type =
1335       typeinfo()->GetTypeByTypeUrl(field.type_url());
1336 
1337   return converter::IsMap(field, *field_type);
1338 }
1339 
IsAny(const google::protobuf::Field & field)1340 bool ProtoStreamObjectWriter::IsAny(const google::protobuf::Field& field) {
1341   return GetTypeWithoutUrl(field.type_url()) == kAnyType;
1342 }
1343 
IsStruct(const google::protobuf::Field & field)1344 bool ProtoStreamObjectWriter::IsStruct(const google::protobuf::Field& field) {
1345   return GetTypeWithoutUrl(field.type_url()) == kStructType;
1346 }
1347 
IsStructValue(const google::protobuf::Field & field)1348 bool ProtoStreamObjectWriter::IsStructValue(
1349     const google::protobuf::Field& field) {
1350   return GetTypeWithoutUrl(field.type_url()) == kStructValueType;
1351 }
1352 
IsStructListValue(const google::protobuf::Field & field)1353 bool ProtoStreamObjectWriter::IsStructListValue(
1354     const google::protobuf::Field& field) {
1355   return GetTypeWithoutUrl(field.type_url()) == kStructListValueType;
1356 }
1357 
1358 }  // namespace converter
1359 }  // namespace util
1360 }  // namespace protobuf
1361 }  // namespace google
1362