protostream_objectsource.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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. #ifndef GOOGLE_PROTOBUF_UTIL_CONVERTER_PROTOSTREAM_OBJECTSOURCE_H__
  31. #define GOOGLE_PROTOBUF_UTIL_CONVERTER_PROTOSTREAM_OBJECTSOURCE_H__
  32. #include <functional>
  33. #include <string>
  34. #include <unordered_map>
  35. #include <google/protobuf/stubs/common.h>
  36. #include <google/protobuf/type.pb.h>
  37. #include <google/protobuf/util/internal/type_info.h>
  38. #include <google/protobuf/util/internal/object_source.h>
  39. #include <google/protobuf/util/internal/object_writer.h>
  40. #include <google/protobuf/util/type_resolver.h>
  41. #include <google/protobuf/stubs/strutil.h>
  42. #include <google/protobuf/stubs/hash.h>
  43. #include <google/protobuf/stubs/status.h>
  44. #include <google/protobuf/stubs/statusor.h>
  45. #include <google/protobuf/port_def.inc>
  46. namespace google {
  47. namespace protobuf {
  48. namespace util {
  49. namespace converter {
  50. class TypeInfo;
  51. // An ObjectSource that can parse a stream of bytes as a protocol buffer.
  52. // Its WriteTo() method can be given an ObjectWriter.
  53. // This implementation uses a google.protobuf.Type for tag and name lookup.
  54. // The field names are converted into lower camel-case when writing to the
  55. // ObjectWriter.
  56. //
  57. // Sample usage: (suppose input is: string proto)
  58. // ArrayInputStream arr_stream(proto.data(), proto.size());
  59. // CodedInputStream in_stream(&arr_stream);
  60. // ProtoStreamObjectSource os(&in_stream, /*ServiceTypeInfo*/ typeinfo,
  61. // <your message google::protobuf::Type>);
  62. //
  63. // Status status = os.WriteTo(<some ObjectWriter>);
  64. class PROTOBUF_EXPORT ProtoStreamObjectSource : public ObjectSource {
  65. public:
  66. ProtoStreamObjectSource(io::CodedInputStream* stream,
  67. TypeResolver* type_resolver,
  68. const google::protobuf::Type& type);
  69. ~ProtoStreamObjectSource() override;
  70. util::Status NamedWriteTo(StringPiece name,
  71. ObjectWriter* ow) const override;
  72. // Sets whether or not to use lowerCamelCase casing for enum values. If set to
  73. // false, enum values are output without any case conversions.
  74. //
  75. // For example, if we have an enum:
  76. // enum Type {
  77. // ACTION_AND_ADVENTURE = 1;
  78. // }
  79. // Type type = 20;
  80. //
  81. // And this option is set to true. Then the rendered "type" field will have
  82. // the string "actionAndAdventure".
  83. // {
  84. // ...
  85. // "type": "actionAndAdventure",
  86. // ...
  87. // }
  88. //
  89. // If set to false, the rendered "type" field will have the string
  90. // "ACTION_AND_ADVENTURE".
  91. // {
  92. // ...
  93. // "type": "ACTION_AND_ADVENTURE",
  94. // ...
  95. // }
  96. void set_use_lower_camel_for_enums(bool value) {
  97. use_lower_camel_for_enums_ = value;
  98. }
  99. // Sets whether to always output enums as ints, by default this is off, and
  100. // enums are rendered as strings.
  101. void set_use_ints_for_enums(bool value) { use_ints_for_enums_ = value; }
  102. // Sets whether to use original proto field names
  103. void set_preserve_proto_field_names(bool value) {
  104. preserve_proto_field_names_ = value;
  105. }
  106. // Sets the max recursion depth of proto message to be deserialized. Proto
  107. // messages over this depth will fail to be deserialized.
  108. // Default value is 64.
  109. void set_max_recursion_depth(int max_depth) {
  110. max_recursion_depth_ = max_depth;
  111. }
  112. protected:
  113. // Writes a proto2 Message to the ObjectWriter. When the given end_tag is
  114. // found this method will complete, allowing it to be used for parsing both
  115. // nested messages (end with 0) and nested groups (end with group end tag).
  116. // The include_start_and_end parameter allows this method to be called when
  117. // already inside of an object, and skip calling StartObject and EndObject.
  118. virtual util::Status WriteMessage(const google::protobuf::Type& type,
  119. StringPiece name,
  120. const uint32 end_tag,
  121. bool include_start_and_end,
  122. ObjectWriter* ow) const;
  123. // Renders a repeating field (packed or unpacked). Returns the next tag after
  124. // reading all sequential repeating elements. The caller should use this tag
  125. // before reading more tags from the stream.
  126. virtual util::StatusOr<uint32> RenderList(
  127. const google::protobuf::Field* field, StringPiece name,
  128. uint32 list_tag, ObjectWriter* ow) const;
  129. // Looks up a field and verify its consistency with wire type in tag.
  130. const google::protobuf::Field* FindAndVerifyField(
  131. const google::protobuf::Type& type, uint32 tag) const;
  132. // Renders a field value to the ObjectWriter.
  133. virtual util::Status RenderField(const google::protobuf::Field* field,
  134. StringPiece field_name,
  135. ObjectWriter* ow) const;
  136. // Reads field value according to Field spec in 'field' and returns the read
  137. // value as string. This only works for primitive datatypes (no message
  138. // types).
  139. const std::string ReadFieldValueAsString(
  140. const google::protobuf::Field& field) const;
  141. // Returns the input stream.
  142. io::CodedInputStream* stream() const { return stream_; }
  143. private:
  144. ProtoStreamObjectSource(io::CodedInputStream* stream,
  145. const TypeInfo* typeinfo,
  146. const google::protobuf::Type& type);
  147. // Function that renders a well known type with a modified behavior.
  148. typedef util::Status (*TypeRenderer)(const ProtoStreamObjectSource*,
  149. const google::protobuf::Type&,
  150. StringPiece, ObjectWriter*);
  151. // TODO(skarvaje): Mark these methods as non-const as they modify internal
  152. // state (stream_).
  153. //
  154. // Renders a NWP map.
  155. // Returns the next tag after reading all map entries. The caller should use
  156. // this tag before reading more tags from the stream.
  157. util::StatusOr<uint32> RenderMap(const google::protobuf::Field* field,
  158. StringPiece name, uint32 list_tag,
  159. ObjectWriter* ow) const;
  160. // Renders a packed repeating field. A packed field is stored as:
  161. // {tag length item1 item2 item3} instead of the less efficient
  162. // {tag item1 tag item2 tag item3}.
  163. util::Status RenderPacked(const google::protobuf::Field* field,
  164. ObjectWriter* ow) const;
  165. // Renders a google.protobuf.Timestamp value to ObjectWriter
  166. static util::Status RenderTimestamp(const ProtoStreamObjectSource* os,
  167. const google::protobuf::Type& type,
  168. StringPiece name,
  169. ObjectWriter* ow);
  170. // Renders a google.protobuf.Duration value to ObjectWriter
  171. static util::Status RenderDuration(const ProtoStreamObjectSource* os,
  172. const google::protobuf::Type& type,
  173. StringPiece name,
  174. ObjectWriter* ow);
  175. // Following RenderTYPE functions render well known types in
  176. // google/protobuf/wrappers.proto corresponding to TYPE.
  177. static util::Status RenderDouble(const ProtoStreamObjectSource* os,
  178. const google::protobuf::Type& type,
  179. StringPiece name, ObjectWriter* ow);
  180. static util::Status RenderFloat(const ProtoStreamObjectSource* os,
  181. const google::protobuf::Type& type,
  182. StringPiece name, ObjectWriter* ow);
  183. static util::Status RenderInt64(const ProtoStreamObjectSource* os,
  184. const google::protobuf::Type& type,
  185. StringPiece name, ObjectWriter* ow);
  186. static util::Status RenderUInt64(const ProtoStreamObjectSource* os,
  187. const google::protobuf::Type& type,
  188. StringPiece name, ObjectWriter* ow);
  189. static util::Status RenderInt32(const ProtoStreamObjectSource* os,
  190. const google::protobuf::Type& type,
  191. StringPiece name, ObjectWriter* ow);
  192. static util::Status RenderUInt32(const ProtoStreamObjectSource* os,
  193. const google::protobuf::Type& type,
  194. StringPiece name, ObjectWriter* ow);
  195. static util::Status RenderBool(const ProtoStreamObjectSource* os,
  196. const google::protobuf::Type& type,
  197. StringPiece name, ObjectWriter* ow);
  198. static util::Status RenderString(const ProtoStreamObjectSource* os,
  199. const google::protobuf::Type& type,
  200. StringPiece name, ObjectWriter* ow);
  201. static util::Status RenderBytes(const ProtoStreamObjectSource* os,
  202. const google::protobuf::Type& type,
  203. StringPiece name, ObjectWriter* ow);
  204. // Renders a google.protobuf.Struct to ObjectWriter.
  205. static util::Status RenderStruct(const ProtoStreamObjectSource* os,
  206. const google::protobuf::Type& type,
  207. StringPiece name, ObjectWriter* ow);
  208. // Helper to render google.protobuf.Struct's Value fields to ObjectWriter.
  209. static util::Status RenderStructValue(const ProtoStreamObjectSource* os,
  210. const google::protobuf::Type& type,
  211. StringPiece name,
  212. ObjectWriter* ow);
  213. // Helper to render google.protobuf.Struct's ListValue fields to ObjectWriter.
  214. static util::Status RenderStructListValue(
  215. const ProtoStreamObjectSource* os, const google::protobuf::Type& type,
  216. StringPiece name, ObjectWriter* ow);
  217. // Render the "Any" type.
  218. static util::Status RenderAny(const ProtoStreamObjectSource* os,
  219. const google::protobuf::Type& type,
  220. StringPiece name, ObjectWriter* ow);
  221. // Render the "FieldMask" type.
  222. static util::Status RenderFieldMask(const ProtoStreamObjectSource* os,
  223. const google::protobuf::Type& type,
  224. StringPiece name,
  225. ObjectWriter* ow);
  226. static std::unordered_map<std::string, TypeRenderer>* renderers_;
  227. static void InitRendererMap();
  228. static void DeleteRendererMap();
  229. static TypeRenderer* FindTypeRenderer(const std::string& type_url);
  230. // Same as above but renders all non-message field types. Callers don't call
  231. // this function directly. They just use RenderField.
  232. util::Status RenderNonMessageField(const google::protobuf::Field* field,
  233. StringPiece field_name,
  234. ObjectWriter* ow) const;
  235. // Utility function to detect proto maps. The 'field' MUST be repeated.
  236. bool IsMap(const google::protobuf::Field& field) const;
  237. // Utility to read int64 and int32 values from a message type in stream_.
  238. // Used for reading google.protobuf.Timestamp and Duration messages.
  239. std::pair<int64, int32> ReadSecondsAndNanos(
  240. const google::protobuf::Type& type) const;
  241. // Helper function to check recursion depth and increment it. It will return
  242. // Status::OK if the current depth is allowed. Otherwise an error is returned.
  243. // type_name and field_name are used for error reporting.
  244. util::Status IncrementRecursionDepth(StringPiece type_name,
  245. StringPiece field_name) const;
  246. // Input stream to read from. Ownership rests with the caller.
  247. mutable io::CodedInputStream* stream_;
  248. // Type information for all the types used in the descriptor. Used to find
  249. // google::protobuf::Type of nested messages/enums.
  250. const TypeInfo* typeinfo_;
  251. // Whether this class owns the typeinfo_ object. If true the typeinfo_ object
  252. // should be deleted in the destructor.
  253. bool own_typeinfo_;
  254. // google::protobuf::Type of the message source.
  255. const google::protobuf::Type& type_;
  256. // Whether to render enums using lowerCamelCase. Defaults to false.
  257. bool use_lower_camel_for_enums_;
  258. // Whether to render enums as ints always. Defaults to false.
  259. bool use_ints_for_enums_;
  260. // Whether to preserve proto field names
  261. bool preserve_proto_field_names_;
  262. // Tracks current recursion depth.
  263. mutable int recursion_depth_;
  264. // Maximum allowed recursion depth.
  265. int max_recursion_depth_;
  266. // Whether to render unknown fields.
  267. bool render_unknown_fields_;
  268. // Whether to render unknown enum values.
  269. bool render_unknown_enum_values_;
  270. // Whether to add trailing zeros for timestamp and duration.
  271. bool add_trailing_zeros_for_timestamp_and_duration_;
  272. // Whether output the empty object or not. If false, output JSON string like:
  273. // "'objectName' : {}". If true, then no outputs. This only happens when all
  274. // the fields of the message are filtered out by field mask.
  275. bool suppress_empty_object_;
  276. bool use_legacy_json_map_format_;
  277. GOOGLE_DISALLOW_IMPLICIT_CONSTRUCTORS(ProtoStreamObjectSource);
  278. };
  279. } // namespace converter
  280. } // namespace util
  281. } // namespace protobuf
  282. } // namespace google
  283. #include <google/protobuf/port_undef.inc>
  284. #endif // GOOGLE_PROTOBUF_UTIL_CONVERTER_PROTOSTREAM_OBJECTSOURCE_H__