message_lite.h 26 KB

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