message_lite.h 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  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. // Authors: wink@google.com (Wink Saville),
  31. // kenton@google.com (Kenton Varda)
  32. // Based on original Protocol Buffers design by
  33. // Sanjay Ghemawat, Jeff Dean, and others.
  34. //
  35. // Defines MessageLite, the abstract interface implemented by all (lite
  36. // and non-lite) protocol message objects.
  37. #ifndef GOOGLE_PROTOBUF_MESSAGE_LITE_H__
  38. #define GOOGLE_PROTOBUF_MESSAGE_LITE_H__
  39. #include <climits>
  40. #include <string>
  41. #include <google/protobuf/stubs/common.h>
  42. #include <google/protobuf/stubs/logging.h>
  43. #include <google/protobuf/io/coded_stream.h>
  44. #include <google/protobuf/arena.h>
  45. #include <google/protobuf/metadata_lite.h>
  46. #include <google/protobuf/stubs/once.h>
  47. #include <google/protobuf/port.h>
  48. #include <google/protobuf/stubs/strutil.h>
  49. #include <google/protobuf/port_def.inc>
  50. #ifdef SWIG
  51. #error "You cannot SWIG proto headers"
  52. #endif
  53. namespace google {
  54. namespace protobuf {
  55. template <typename T>
  56. class RepeatedPtrField;
  57. class FastReflectionMessageMutator;
  58. class FastReflectionStringSetter;
  59. class Reflection;
  60. namespace io {
  61. class CodedInputStream;
  62. class CodedOutputStream;
  63. class ZeroCopyInputStream;
  64. class ZeroCopyOutputStream;
  65. } // namespace io
  66. namespace internal {
  67. class SwapFieldHelper;
  68. // Tag type used to invoke the constinit constructor overload of some classes.
  69. // Such constructors are internal implementation details of the library.
  70. struct ConstantInitialized {
  71. explicit ConstantInitialized() = default;
  72. };
  73. // See parse_context.h for explanation
  74. class ParseContext;
  75. class ExtensionSet;
  76. class LazyField;
  77. class RepeatedPtrFieldBase;
  78. class TcParserBase;
  79. class WireFormatLite;
  80. class WeakFieldMap;
  81. template <typename Type>
  82. class GenericTypeHandler; // defined in repeated_field.h
  83. // We compute sizes as size_t but cache them as int. This function converts a
  84. // computed size to a cached size. Since we don't proceed with serialization
  85. // if the total size was > INT_MAX, it is not important what this function
  86. // returns for inputs > INT_MAX. However this case should not error or
  87. // GOOGLE_CHECK-fail, because the full size_t resolution is still returned from
  88. // ByteSizeLong() and checked against INT_MAX; we can catch the overflow
  89. // there.
  90. inline int ToCachedSize(size_t size) { return static_cast<int>(size); }
  91. // We mainly calculate sizes in terms of size_t, but some functions that
  92. // compute sizes return "int". These int sizes are expected to always be
  93. // positive. This function is more efficient than casting an int to size_t
  94. // directly on 64-bit platforms because it avoids making the compiler emit a
  95. // sign extending instruction, which we don't want and don't want to pay for.
  96. inline size_t FromIntSize(int size) {
  97. // Convert to unsigned before widening so sign extension is not necessary.
  98. return static_cast<unsigned int>(size);
  99. }
  100. // For cases where a legacy function returns an integer size. We GOOGLE_DCHECK()
  101. // that the conversion will fit within an integer; if this is false then we
  102. // are losing information.
  103. inline int ToIntSize(size_t size) {
  104. GOOGLE_DCHECK_LE(size, static_cast<size_t>(INT_MAX));
  105. return static_cast<int>(size);
  106. }
  107. // This type wraps a variable whose constructor and destructor are explicitly
  108. // called. It is particularly useful for a global variable, without its
  109. // constructor and destructor run on start and end of the program lifetime.
  110. // This circumvents the initial construction order fiasco, while keeping
  111. // the address of the empty string a compile time constant.
  112. //
  113. // Pay special attention to the initialization state of the object.
  114. // 1. The object is "uninitialized" to begin with.
  115. // 2. Call Construct() or DefaultConstruct() only if the object is
  116. // uninitialized. After the call, the object becomes "initialized".
  117. // 3. Call get() and get_mutable() only if the object is initialized.
  118. // 4. Call Destruct() only if the object is initialized.
  119. // After the call, the object becomes uninitialized.
  120. template <typename T>
  121. class ExplicitlyConstructed {
  122. public:
  123. void DefaultConstruct() { new (&union_) T(); }
  124. template <typename... Args>
  125. void Construct(Args&&... args) {
  126. new (&union_) T(std::forward<Args>(args)...);
  127. }
  128. void Destruct() { get_mutable()->~T(); }
  129. constexpr const T& get() const { return reinterpret_cast<const T&>(union_); }
  130. T* get_mutable() { return reinterpret_cast<T*>(&union_); }
  131. private:
  132. // Prefer c++14 aligned_storage, but for compatibility this will do.
  133. union AlignedUnion {
  134. alignas(T) char space[sizeof(T)];
  135. int64 align_to_int64;
  136. void* align_to_ptr;
  137. } union_;
  138. };
  139. // Default empty string object. Don't use this directly. Instead, call
  140. // GetEmptyString() to get the reference.
  141. PROTOBUF_EXPORT extern ExplicitlyConstructed<std::string>
  142. fixed_address_empty_string;
  143. PROTOBUF_EXPORT constexpr const std::string& GetEmptyStringAlreadyInited() {
  144. return fixed_address_empty_string.get();
  145. }
  146. PROTOBUF_EXPORT size_t StringSpaceUsedExcludingSelfLong(const std::string& str);
  147. } // namespace internal
  148. // Interface to light weight protocol messages.
  149. //
  150. // This interface is implemented by all protocol message objects. Non-lite
  151. // messages additionally implement the Message interface, which is a
  152. // subclass of MessageLite. Use MessageLite instead when you only need
  153. // the subset of features which it supports -- namely, nothing that uses
  154. // descriptors or reflection. You can instruct the protocol compiler
  155. // to generate classes which implement only MessageLite, not the full
  156. // Message interface, by adding the following line to the .proto file:
  157. //
  158. // option optimize_for = LITE_RUNTIME;
  159. //
  160. // This is particularly useful on resource-constrained systems where
  161. // the full protocol buffers runtime library is too big.
  162. //
  163. // Note that on non-constrained systems (e.g. servers) when you need
  164. // to link in lots of protocol definitions, a better way to reduce
  165. // total code footprint is to use optimize_for = CODE_SIZE. This
  166. // will make the generated code smaller while still supporting all the
  167. // same features (at the expense of speed). optimize_for = LITE_RUNTIME
  168. // is best when you only have a small number of message types linked
  169. // into your binary, in which case the size of the protocol buffers
  170. // runtime itself is the biggest problem.
  171. //
  172. // Users must not derive from this class. Only the protocol compiler and
  173. // the internal library are allowed to create subclasses.
  174. class PROTOBUF_EXPORT MessageLite {
  175. public:
  176. constexpr MessageLite() {}
  177. virtual ~MessageLite() = default;
  178. // Basic Operations ------------------------------------------------
  179. // Get the name of this message type, e.g. "foo.bar.BazProto".
  180. virtual std::string GetTypeName() const = 0;
  181. // Construct a new instance of the same type. Ownership is passed to the
  182. // caller.
  183. virtual MessageLite* New() const = 0;
  184. // Construct a new instance on the arena. Ownership is passed to the caller
  185. // if arena is a NULL. Default implementation for backwards compatibility.
  186. virtual MessageLite* New(Arena* arena) const;
  187. // Same as GetOwningArena.
  188. Arena* GetArena() const { return GetOwningArena(); }
  189. // Get a pointer that may be equal to this message's arena, or may not be.
  190. // If the value returned by this method is equal to some arena pointer, then
  191. // this message is on that arena; however, if this message is on some arena,
  192. // this method may or may not return that arena's pointer. As a tradeoff,
  193. // this method may be more efficient than GetArena(). The intent is to allow
  194. // underlying representations that use e.g. tagged pointers to sometimes
  195. // store the arena pointer directly, and sometimes in a more indirect way,
  196. // and allow a fastpath comparison against the arena pointer when it's easy
  197. // to obtain.
  198. void* GetMaybeArenaPointer() const {
  199. return _internal_metadata_.raw_arena_ptr();
  200. }
  201. // Clear all fields of the message and set them to their default values.
  202. // Clear() avoids freeing memory, assuming that any memory allocated
  203. // to hold parts of the message will be needed again to hold the next
  204. // message. If you actually want to free the memory used by a Message,
  205. // you must delete it.
  206. virtual void Clear() = 0;
  207. // Quickly check if all required fields have values set.
  208. virtual bool IsInitialized() const = 0;
  209. // This is not implemented for Lite messages -- it just returns "(cannot
  210. // determine missing fields for lite message)". However, it is implemented
  211. // for full messages. See message.h.
  212. virtual std::string InitializationErrorString() const;
  213. // If |other| is the exact same class as this, calls MergeFrom(). Otherwise,
  214. // results are undefined (probably crash).
  215. virtual void CheckTypeAndMergeFrom(const MessageLite& other) = 0;
  216. // These methods return a human-readable summary of the message. Note that
  217. // since the MessageLite interface does not support reflection, there is very
  218. // little information that these methods can provide. They are shadowed by
  219. // methods of the same name on the Message interface which provide much more
  220. // information. The methods here are intended primarily to facilitate code
  221. // reuse for logic that needs to interoperate with both full and lite protos.
  222. //
  223. // The format of the returned string is subject to change, so please do not
  224. // assume it will remain stable over time.
  225. std::string DebugString() const;
  226. std::string ShortDebugString() const { return DebugString(); }
  227. // MessageLite::DebugString is already Utf8 Safe. This is to add compatibility
  228. // with Message.
  229. std::string Utf8DebugString() const { return DebugString(); }
  230. // Parsing ---------------------------------------------------------
  231. // Methods for parsing in protocol buffer format. Most of these are
  232. // just simple wrappers around MergeFromCodedStream(). Clear() will be
  233. // called before merging the input.
  234. // Fill the message with a protocol buffer parsed from the given input
  235. // stream. Returns false on a read error or if the input is in the wrong
  236. // format. A successful return does not indicate the entire input is
  237. // consumed, ensure you call ConsumedEntireMessage() to check that if
  238. // applicable.
  239. PROTOBUF_ATTRIBUTE_REINITIALIZES bool ParseFromCodedStream(
  240. io::CodedInputStream* input);
  241. // Like ParseFromCodedStream(), but accepts messages that are missing
  242. // required fields.
  243. PROTOBUF_ATTRIBUTE_REINITIALIZES bool ParsePartialFromCodedStream(
  244. io::CodedInputStream* input);
  245. // Read a protocol buffer from the given zero-copy input stream. If
  246. // successful, the entire input will be consumed.
  247. PROTOBUF_ATTRIBUTE_REINITIALIZES bool ParseFromZeroCopyStream(
  248. io::ZeroCopyInputStream* input);
  249. // Like ParseFromZeroCopyStream(), but accepts messages that are missing
  250. // required fields.
  251. PROTOBUF_ATTRIBUTE_REINITIALIZES bool ParsePartialFromZeroCopyStream(
  252. io::ZeroCopyInputStream* input);
  253. // Parse a protocol buffer from a file descriptor. If successful, the entire
  254. // input will be consumed.
  255. PROTOBUF_ATTRIBUTE_REINITIALIZES bool ParseFromFileDescriptor(
  256. int file_descriptor);
  257. // Like ParseFromFileDescriptor(), but accepts messages that are missing
  258. // required fields.
  259. PROTOBUF_ATTRIBUTE_REINITIALIZES bool ParsePartialFromFileDescriptor(
  260. int file_descriptor);
  261. // Parse a protocol buffer from a C++ istream. If successful, the entire
  262. // input will be consumed.
  263. PROTOBUF_ATTRIBUTE_REINITIALIZES bool ParseFromIstream(std::istream* input);
  264. // Like ParseFromIstream(), but accepts messages that are missing
  265. // required fields.
  266. PROTOBUF_ATTRIBUTE_REINITIALIZES bool ParsePartialFromIstream(
  267. std::istream* input);
  268. // Read a protocol buffer from the given zero-copy input stream, expecting
  269. // the message to be exactly "size" bytes long. If successful, exactly
  270. // this many bytes will have been consumed from the input.
  271. bool MergePartialFromBoundedZeroCopyStream(io::ZeroCopyInputStream* input,
  272. int size);
  273. // Like ParseFromBoundedZeroCopyStream(), but accepts messages that are
  274. // missing required fields.
  275. bool MergeFromBoundedZeroCopyStream(io::ZeroCopyInputStream* input, int size);
  276. PROTOBUF_ATTRIBUTE_REINITIALIZES bool ParseFromBoundedZeroCopyStream(
  277. io::ZeroCopyInputStream* input, int size);
  278. // Like ParseFromBoundedZeroCopyStream(), but accepts messages that are
  279. // missing required fields.
  280. PROTOBUF_ATTRIBUTE_REINITIALIZES bool ParsePartialFromBoundedZeroCopyStream(
  281. io::ZeroCopyInputStream* input, int size);
  282. // Parses a protocol buffer contained in a string. Returns true on success.
  283. // This function takes a string in the (non-human-readable) binary wire
  284. // format, matching the encoding output by MessageLite::SerializeToString().
  285. // If you'd like to convert a human-readable string into a protocol buffer
  286. // object, see google::protobuf::TextFormat::ParseFromString().
  287. PROTOBUF_ATTRIBUTE_REINITIALIZES bool ParseFromString(ConstStringParam data);
  288. // Like ParseFromString(), but accepts messages that are missing
  289. // required fields.
  290. PROTOBUF_ATTRIBUTE_REINITIALIZES bool ParsePartialFromString(
  291. ConstStringParam data);
  292. // Parse a protocol buffer contained in an array of bytes.
  293. PROTOBUF_ATTRIBUTE_REINITIALIZES bool ParseFromArray(const void* data,
  294. int size);
  295. // Like ParseFromArray(), but accepts messages that are missing
  296. // required fields.
  297. PROTOBUF_ATTRIBUTE_REINITIALIZES bool ParsePartialFromArray(const void* data,
  298. int size);
  299. // Reads a protocol buffer from the stream and merges it into this
  300. // Message. Singular fields read from the what is
  301. // already in the Message and repeated fields are appended to those
  302. // already present.
  303. //
  304. // It is the responsibility of the caller to call input->LastTagWas()
  305. // (for groups) or input->ConsumedEntireMessage() (for non-groups) after
  306. // this returns to verify that the message's end was delimited correctly.
  307. //
  308. // ParseFromCodedStream() is implemented as Clear() followed by
  309. // MergeFromCodedStream().
  310. bool MergeFromCodedStream(io::CodedInputStream* input);
  311. // Like MergeFromCodedStream(), but succeeds even if required fields are
  312. // missing in the input.
  313. //
  314. // MergeFromCodedStream() is just implemented as MergePartialFromCodedStream()
  315. // followed by IsInitialized().
  316. bool MergePartialFromCodedStream(io::CodedInputStream* input);
  317. // Merge a protocol buffer contained in a string.
  318. bool MergeFromString(ConstStringParam data);
  319. // Serialization ---------------------------------------------------
  320. // Methods for serializing in protocol buffer format. Most of these
  321. // are just simple wrappers around ByteSize() and SerializeWithCachedSizes().
  322. // Write a protocol buffer of this message to the given output. Returns
  323. // false on a write error. If the message is missing required fields,
  324. // this may GOOGLE_CHECK-fail.
  325. bool SerializeToCodedStream(io::CodedOutputStream* output) const;
  326. // Like SerializeToCodedStream(), but allows missing required fields.
  327. bool SerializePartialToCodedStream(io::CodedOutputStream* output) const;
  328. // Write the message to the given zero-copy output stream. All required
  329. // fields must be set.
  330. bool SerializeToZeroCopyStream(io::ZeroCopyOutputStream* output) const;
  331. // Like SerializeToZeroCopyStream(), but allows missing required fields.
  332. bool SerializePartialToZeroCopyStream(io::ZeroCopyOutputStream* output) const;
  333. // Serialize the message and store it in the given string. All required
  334. // fields must be set.
  335. bool SerializeToString(std::string* output) const;
  336. // Like SerializeToString(), but allows missing required fields.
  337. bool SerializePartialToString(std::string* output) const;
  338. // Serialize the message and store it in the given byte array. All required
  339. // fields must be set.
  340. bool SerializeToArray(void* data, int size) const;
  341. // Like SerializeToArray(), but allows missing required fields.
  342. bool SerializePartialToArray(void* data, int size) const;
  343. // Make a string encoding the message. Is equivalent to calling
  344. // SerializeToString() on a string and using that. Returns the empty
  345. // string if SerializeToString() would have returned an error.
  346. // Note: If you intend to generate many such strings, you may
  347. // reduce heap fragmentation by instead re-using the same string
  348. // object with calls to SerializeToString().
  349. std::string SerializeAsString() const;
  350. // Like SerializeAsString(), but allows missing required fields.
  351. std::string SerializePartialAsString() const;
  352. // Serialize the message and write it to the given file descriptor. All
  353. // required fields must be set.
  354. bool SerializeToFileDescriptor(int file_descriptor) const;
  355. // Like SerializeToFileDescriptor(), but allows missing required fields.
  356. bool SerializePartialToFileDescriptor(int file_descriptor) const;
  357. // Serialize the message and write it to the given C++ ostream. All
  358. // required fields must be set.
  359. bool SerializeToOstream(std::ostream* output) const;
  360. // Like SerializeToOstream(), but allows missing required fields.
  361. bool SerializePartialToOstream(std::ostream* output) const;
  362. // Like SerializeToString(), but appends to the data to the string's
  363. // existing contents. All required fields must be set.
  364. bool AppendToString(std::string* output) const;
  365. // Like AppendToString(), but allows missing required fields.
  366. bool AppendPartialToString(std::string* output) const;
  367. // Computes the serialized size of the message. This recursively calls
  368. // ByteSizeLong() on all embedded messages.
  369. //
  370. // ByteSizeLong() is generally linear in the number of fields defined for the
  371. // proto.
  372. virtual size_t ByteSizeLong() const = 0;
  373. // Legacy ByteSize() API.
  374. PROTOBUF_DEPRECATED_MSG("Please use ByteSizeLong() instead")
  375. int ByteSize() const { return internal::ToIntSize(ByteSizeLong()); }
  376. // Serializes the message without recomputing the size. The message must not
  377. // have changed since the last call to ByteSize(), and the value returned by
  378. // ByteSize must be non-negative. Otherwise the results are undefined.
  379. void SerializeWithCachedSizes(io::CodedOutputStream* output) const {
  380. output->SetCur(_InternalSerialize(output->Cur(), output->EpsCopy()));
  381. }
  382. // Functions below here are not part of the public interface. It isn't
  383. // enforced, but they should be treated as private, and will be private
  384. // at some future time. Unfortunately the implementation of the "friend"
  385. // keyword in GCC is broken at the moment, but we expect it will be fixed.
  386. // Like SerializeWithCachedSizes, but writes directly to *target, returning
  387. // a pointer to the byte immediately after the last byte written. "target"
  388. // must point at a byte array of at least ByteSize() bytes. Whether to use
  389. // deterministic serialization, e.g., maps in sorted order, is determined by
  390. // CodedOutputStream::IsDefaultSerializationDeterministic().
  391. uint8* SerializeWithCachedSizesToArray(uint8* target) const;
  392. // Returns the result of the last call to ByteSize(). An embedded message's
  393. // size is needed both to serialize it (because embedded messages are
  394. // length-delimited) and to compute the outer message's size. Caching
  395. // the size avoids computing it multiple times.
  396. //
  397. // ByteSize() does not automatically use the cached size when available
  398. // because this would require invalidating it every time the message was
  399. // modified, which would be too hard and expensive. (E.g. if a deeply-nested
  400. // sub-message is changed, all of its parents' cached sizes would need to be
  401. // invalidated, which is too much work for an otherwise inlined setter
  402. // method.)
  403. virtual int GetCachedSize() const = 0;
  404. virtual const char* _InternalParse(const char* /*ptr*/,
  405. internal::ParseContext* /*ctx*/) {
  406. return nullptr;
  407. }
  408. protected:
  409. template <typename T>
  410. static T* CreateMaybeMessage(Arena* arena) {
  411. return Arena::CreateMaybeMessage<T>(arena);
  412. }
  413. inline explicit MessageLite(Arena* arena, bool is_message_owned = false)
  414. : _internal_metadata_(arena, is_message_owned) {}
  415. // Returns the arena, if any, that directly owns this message and its internal
  416. // memory (Arena::Own is different in that the arena doesn't directly own the
  417. // internal memory). This method is used in proto's implementation for
  418. // swapping, moving and setting allocated, for deciding whether the ownership
  419. // of this message or its internal memory could be changed.
  420. Arena* GetOwningArena() const { return _internal_metadata_.owning_arena(); }
  421. // Returns the arena, used for allocating internal objects(e.g., child
  422. // messages, etc), or owning incoming objects (e.g., set allocated).
  423. Arena* GetArenaForAllocation() const { return _internal_metadata_.arena(); }
  424. internal::InternalMetadata _internal_metadata_;
  425. public:
  426. enum ParseFlags {
  427. kMerge = 0,
  428. kParse = 1,
  429. kMergePartial = 2,
  430. kParsePartial = 3,
  431. kMergeWithAliasing = 4,
  432. kParseWithAliasing = 5,
  433. kMergePartialWithAliasing = 6,
  434. kParsePartialWithAliasing = 7
  435. };
  436. template <ParseFlags flags, typename T>
  437. bool ParseFrom(const T& input);
  438. // Fast path when conditions match (ie. non-deterministic)
  439. // uint8* _InternalSerialize(uint8* ptr) const;
  440. virtual uint8* _InternalSerialize(uint8* ptr,
  441. io::EpsCopyOutputStream* stream) const = 0;
  442. // Identical to IsInitialized() except that it logs an error message.
  443. bool IsInitializedWithErrors() const {
  444. if (IsInitialized()) return true;
  445. LogInitializationErrorMessage();
  446. return false;
  447. }
  448. private:
  449. // TODO(gerbens) make this a pure abstract function
  450. virtual const void* InternalGetTable() const { return NULL; }
  451. friend class FastReflectionMessageMutator;
  452. friend class FastReflectionStringSetter;
  453. friend class Message;
  454. friend class Reflection;
  455. friend class internal::ExtensionSet;
  456. friend class internal::LazyField;
  457. friend class internal::SwapFieldHelper;
  458. friend class internal::TcParserBase;
  459. friend class internal::WeakFieldMap;
  460. friend class internal::WireFormatLite;
  461. template <typename Type>
  462. friend class Arena::InternalHelper;
  463. template <typename Type>
  464. friend class internal::GenericTypeHandler;
  465. void LogInitializationErrorMessage() const;
  466. bool MergeFromImpl(io::CodedInputStream* input, ParseFlags parse_flags);
  467. GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageLite);
  468. };
  469. namespace internal {
  470. template <bool alias>
  471. bool MergeFromImpl(StringPiece input, MessageLite* msg,
  472. MessageLite::ParseFlags parse_flags);
  473. extern template bool MergeFromImpl<false>(StringPiece input,
  474. MessageLite* msg,
  475. MessageLite::ParseFlags parse_flags);
  476. extern template bool MergeFromImpl<true>(StringPiece input,
  477. MessageLite* msg,
  478. MessageLite::ParseFlags parse_flags);
  479. template <bool alias>
  480. bool MergeFromImpl(io::ZeroCopyInputStream* input, MessageLite* msg,
  481. MessageLite::ParseFlags parse_flags);
  482. extern template bool MergeFromImpl<false>(io::ZeroCopyInputStream* input,
  483. MessageLite* msg,
  484. MessageLite::ParseFlags parse_flags);
  485. extern template bool MergeFromImpl<true>(io::ZeroCopyInputStream* input,
  486. MessageLite* msg,
  487. MessageLite::ParseFlags parse_flags);
  488. struct BoundedZCIS {
  489. io::ZeroCopyInputStream* zcis;
  490. int limit;
  491. };
  492. template <bool alias>
  493. bool MergeFromImpl(BoundedZCIS input, MessageLite* msg,
  494. MessageLite::ParseFlags parse_flags);
  495. extern template bool MergeFromImpl<false>(BoundedZCIS input, MessageLite* msg,
  496. MessageLite::ParseFlags parse_flags);
  497. extern template bool MergeFromImpl<true>(BoundedZCIS input, MessageLite* msg,
  498. MessageLite::ParseFlags parse_flags);
  499. template <typename T>
  500. struct SourceWrapper;
  501. template <bool alias, typename T>
  502. bool MergeFromImpl(const SourceWrapper<T>& input, MessageLite* msg,
  503. MessageLite::ParseFlags parse_flags) {
  504. return input.template MergeInto<alias>(msg, parse_flags);
  505. }
  506. } // namespace internal
  507. template <MessageLite::ParseFlags flags, typename T>
  508. bool MessageLite::ParseFrom(const T& input) {
  509. if (flags & kParse) Clear();
  510. constexpr bool alias = (flags & kMergeWithAliasing) != 0;
  511. return internal::MergeFromImpl<alias>(input, this, flags);
  512. }
  513. // ===================================================================
  514. // Shutdown support.
  515. // Shut down the entire protocol buffers library, deleting all static-duration
  516. // objects allocated by the library or by generated .pb.cc files.
  517. //
  518. // There are two reasons you might want to call this:
  519. // * You use a draconian definition of "memory leak" in which you expect
  520. // every single malloc() to have a corresponding free(), even for objects
  521. // which live until program exit.
  522. // * You are writing a dynamically-loaded library which needs to clean up
  523. // after itself when the library is unloaded.
  524. //
  525. // It is safe to call this multiple times. However, it is not safe to use
  526. // any other part of the protocol buffers library after
  527. // ShutdownProtobufLibrary() has been called. Furthermore this call is not
  528. // thread safe, user needs to synchronize multiple calls.
  529. PROTOBUF_EXPORT void ShutdownProtobufLibrary();
  530. namespace internal {
  531. // Register a function to be called when ShutdownProtocolBuffers() is called.
  532. PROTOBUF_EXPORT void OnShutdown(void (*func)());
  533. // Run an arbitrary function on an arg
  534. PROTOBUF_EXPORT void OnShutdownRun(void (*f)(const void*), const void* arg);
  535. template <typename T>
  536. T* OnShutdownDelete(T* p) {
  537. OnShutdownRun([](const void* pp) { delete static_cast<const T*>(pp); }, p);
  538. return p;
  539. }
  540. } // namespace internal
  541. } // namespace protobuf
  542. } // namespace google
  543. #include <google/protobuf/port_undef.inc>
  544. #endif // GOOGLE_PROTOBUF_MESSAGE_LITE_H__