You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

message_lite.h 26 kB

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