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