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