PageRenderTime 26ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/src/google/protobuf/wire_format.h

http://protobuf.googlecode.com/
C Header | 308 lines | 135 code | 46 blank | 127 comment | 2 complexity | f3c8c56da3df870ee54d7636d3f53251 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. // Protocol Buffers - Google's data interchange format
  2. // Copyright 2008 Google Inc. All rights reserved.
  3. // http://code.google.com/p/protobuf/
  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. // Author: kenton@google.com (Kenton Varda)
  31. // atenasio@google.com (Chris Atenasio) (ZigZag transform)
  32. // Based on original Protocol Buffers design by
  33. // Sanjay Ghemawat, Jeff Dean, and others.
  34. //
  35. // This header is logically internal, but is made public because it is used
  36. // from protocol-compiler-generated code, which may reside in other components.
  37. #ifndef GOOGLE_PROTOBUF_WIRE_FORMAT_H__
  38. #define GOOGLE_PROTOBUF_WIRE_FORMAT_H__
  39. #include <string>
  40. #include <google/protobuf/stubs/common.h>
  41. #include <google/protobuf/descriptor.pb.h>
  42. #include <google/protobuf/descriptor.h>
  43. #include <google/protobuf/message.h>
  44. #include <google/protobuf/wire_format_lite.h>
  45. // Do UTF-8 validation on string type in Debug build only
  46. #ifndef NDEBUG
  47. #define GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED
  48. #endif
  49. namespace google {
  50. namespace protobuf {
  51. namespace io {
  52. class CodedInputStream; // coded_stream.h
  53. class CodedOutputStream; // coded_stream.h
  54. }
  55. class UnknownFieldSet; // unknown_field_set.h
  56. }
  57. namespace protobuf {
  58. namespace internal {
  59. // This class is for internal use by the protocol buffer library and by
  60. // protocol-complier-generated message classes. It must not be called
  61. // directly by clients.
  62. //
  63. // This class contains code for implementing the binary protocol buffer
  64. // wire format via reflection. The WireFormatLite class implements the
  65. // non-reflection based routines.
  66. //
  67. // This class is really a namespace that contains only static methods
  68. class LIBPROTOBUF_EXPORT WireFormat {
  69. public:
  70. // Given a field return its WireType
  71. static inline WireFormatLite::WireType WireTypeForField(
  72. const FieldDescriptor* field);
  73. // Given a FieldSescriptor::Type return its WireType
  74. static inline WireFormatLite::WireType WireTypeForFieldType(
  75. FieldDescriptor::Type type);
  76. // Compute the byte size of a tag. For groups, this includes both the start
  77. // and end tags.
  78. static inline int TagSize(int field_number, FieldDescriptor::Type type);
  79. // These procedures can be used to implement the methods of Message which
  80. // handle parsing and serialization of the protocol buffer wire format
  81. // using only the Reflection interface. When you ask the protocol
  82. // compiler to optimize for code size rather than speed, it will implement
  83. // those methods in terms of these procedures. Of course, these are much
  84. // slower than the specialized implementations which the protocol compiler
  85. // generates when told to optimize for speed.
  86. // Read a message in protocol buffer wire format.
  87. //
  88. // This procedure reads either to the end of the input stream or through
  89. // a WIRETYPE_END_GROUP tag ending the message, whichever comes first.
  90. // It returns false if the input is invalid.
  91. //
  92. // Required fields are NOT checked by this method. You must call
  93. // IsInitialized() on the resulting message yourself.
  94. static bool ParseAndMergePartial(io::CodedInputStream* input,
  95. Message* message);
  96. // Serialize a message in protocol buffer wire format.
  97. //
  98. // Any embedded messages within the message must have their correct sizes
  99. // cached. However, the top-level message need not; its size is passed as
  100. // a parameter to this procedure.
  101. //
  102. // These return false iff the underlying stream returns a write error.
  103. static void SerializeWithCachedSizes(
  104. const Message& message,
  105. int size, io::CodedOutputStream* output);
  106. // Implements Message::ByteSize() via reflection. WARNING: The result
  107. // of this method is *not* cached anywhere. However, all embedded messages
  108. // will have their ByteSize() methods called, so their sizes will be cached.
  109. // Therefore, calling this method is sufficient to allow you to call
  110. // WireFormat::SerializeWithCachedSizes() on the same object.
  111. static int ByteSize(const Message& message);
  112. // -----------------------------------------------------------------
  113. // Helpers for dealing with unknown fields
  114. // Skips a field value of the given WireType. The input should start
  115. // positioned immediately after the tag. If unknown_fields is non-NULL,
  116. // the contents of the field will be added to it.
  117. static bool SkipField(io::CodedInputStream* input, uint32 tag,
  118. UnknownFieldSet* unknown_fields);
  119. // Reads and ignores a message from the input. If unknown_fields is non-NULL,
  120. // the contents will be added to it.
  121. static bool SkipMessage(io::CodedInputStream* input,
  122. UnknownFieldSet* unknown_fields);
  123. // Write the contents of an UnknownFieldSet to the output.
  124. static void SerializeUnknownFields(const UnknownFieldSet& unknown_fields,
  125. io::CodedOutputStream* output);
  126. // Same as above, except writing directly to the provided buffer.
  127. // Requires that the buffer have sufficient capacity for
  128. // ComputeUnknownFieldsSize(unknown_fields).
  129. //
  130. // Returns a pointer past the last written byte.
  131. static uint8* SerializeUnknownFieldsToArray(
  132. const UnknownFieldSet& unknown_fields,
  133. uint8* target);
  134. // Same thing except for messages that have the message_set_wire_format
  135. // option.
  136. static void SerializeUnknownMessageSetItems(
  137. const UnknownFieldSet& unknown_fields,
  138. io::CodedOutputStream* output);
  139. // Same as above, except writing directly to the provided buffer.
  140. // Requires that the buffer have sufficient capacity for
  141. // ComputeUnknownMessageSetItemsSize(unknown_fields).
  142. //
  143. // Returns a pointer past the last written byte.
  144. static uint8* SerializeUnknownMessageSetItemsToArray(
  145. const UnknownFieldSet& unknown_fields,
  146. uint8* target);
  147. // Compute the size of the UnknownFieldSet on the wire.
  148. static int ComputeUnknownFieldsSize(const UnknownFieldSet& unknown_fields);
  149. // Same thing except for messages that have the message_set_wire_format
  150. // option.
  151. static int ComputeUnknownMessageSetItemsSize(
  152. const UnknownFieldSet& unknown_fields);
  153. // Helper functions for encoding and decoding tags. (Inlined below and in
  154. // _inl.h)
  155. //
  156. // This is different from MakeTag(field->number(), field->type()) in the case
  157. // of packed repeated fields.
  158. static uint32 MakeTag(const FieldDescriptor* field);
  159. // Parse a single field. The input should start out positioned immidately
  160. // after the tag.
  161. static bool ParseAndMergeField(
  162. uint32 tag,
  163. const FieldDescriptor* field, // May be NULL for unknown
  164. Message* message,
  165. io::CodedInputStream* input);
  166. // Serialize a single field.
  167. static void SerializeFieldWithCachedSizes(
  168. const FieldDescriptor* field, // Cannot be NULL
  169. const Message& message,
  170. io::CodedOutputStream* output);
  171. // Compute size of a single field. If the field is a message type, this
  172. // will call ByteSize() for the embedded message, insuring that it caches
  173. // its size.
  174. static int FieldByteSize(
  175. const FieldDescriptor* field, // Cannot be NULL
  176. const Message& message);
  177. // Parse/serialize a MessageSet::Item group. Used with messages that use
  178. // opion message_set_wire_format = true.
  179. static bool ParseAndMergeMessageSetItem(
  180. io::CodedInputStream* input,
  181. Message* message);
  182. static void SerializeMessageSetItemWithCachedSizes(
  183. const FieldDescriptor* field,
  184. const Message& message,
  185. io::CodedOutputStream* output);
  186. static int MessageSetItemByteSize(
  187. const FieldDescriptor* field,
  188. const Message& message);
  189. // Computes the byte size of a field, excluding tags. For packed fields, it
  190. // only includes the size of the raw data, and not the size of the total
  191. // length, but for other length-delimited types, the size of the length is
  192. // included.
  193. static int FieldDataOnlyByteSize(
  194. const FieldDescriptor* field, // Cannot be NULL
  195. const Message& message);
  196. enum Operation {
  197. PARSE,
  198. SERIALIZE,
  199. };
  200. // Verifies that a string field is valid UTF8, logging an error if not.
  201. static void VerifyUTF8String(const char* data, int size, Operation op);
  202. private:
  203. // Verifies that a string field is valid UTF8, logging an error if not.
  204. static void VerifyUTF8StringFallback(
  205. const char* data,
  206. int size,
  207. Operation op);
  208. GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(WireFormat);
  209. };
  210. // Subclass of FieldSkipper which saves skipped fields to an UnknownFieldSet.
  211. class LIBPROTOBUF_EXPORT UnknownFieldSetFieldSkipper : public FieldSkipper {
  212. public:
  213. UnknownFieldSetFieldSkipper(UnknownFieldSet* unknown_fields)
  214. : unknown_fields_(unknown_fields) {}
  215. virtual ~UnknownFieldSetFieldSkipper() {}
  216. // implements FieldSkipper -----------------------------------------
  217. virtual bool SkipField(io::CodedInputStream* input, uint32 tag);
  218. virtual bool SkipMessage(io::CodedInputStream* input);
  219. virtual void SkipUnknownEnum(int field_number, int value);
  220. protected:
  221. UnknownFieldSet* unknown_fields_;
  222. };
  223. // inline methods ====================================================
  224. inline WireFormatLite::WireType WireFormat::WireTypeForField(
  225. const FieldDescriptor* field) {
  226. if (field->options().packed()) {
  227. return WireFormatLite::WIRETYPE_LENGTH_DELIMITED;
  228. } else {
  229. return WireTypeForFieldType(field->type());
  230. }
  231. }
  232. inline WireFormatLite::WireType WireFormat::WireTypeForFieldType(
  233. FieldDescriptor::Type type) {
  234. // Some compilers don't like enum -> enum casts, so we implicit_cast to
  235. // int first.
  236. return WireFormatLite::WireTypeForFieldType(
  237. static_cast<WireFormatLite::FieldType>(
  238. implicit_cast<int>(type)));
  239. }
  240. inline uint32 WireFormat::MakeTag(const FieldDescriptor* field) {
  241. return WireFormatLite::MakeTag(field->number(), WireTypeForField(field));
  242. }
  243. inline int WireFormat::TagSize(int field_number, FieldDescriptor::Type type) {
  244. // Some compilers don't like enum -> enum casts, so we implicit_cast to
  245. // int first.
  246. return WireFormatLite::TagSize(field_number,
  247. static_cast<WireFormatLite::FieldType>(
  248. implicit_cast<int>(type)));
  249. }
  250. inline void WireFormat::VerifyUTF8String(const char* data, int size,
  251. WireFormat::Operation op) {
  252. #ifdef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED
  253. WireFormat::VerifyUTF8StringFallback(data, size, op);
  254. #else
  255. // Avoid the compiler warning about unsued variables.
  256. (void)data; (void)size; (void)op;
  257. #endif
  258. }
  259. } // namespace internal
  260. } // namespace protobuf
  261. } // namespace google
  262. #endif // GOOGLE_PROTOBUF_WIRE_FORMAT_H__