Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-01-31 10:12:23

0001 // Protocol Buffers - Google's data interchange format
0002 // Copyright 2008 Google Inc.  All rights reserved.
0003 //
0004 // Use of this source code is governed by a BSD-style
0005 // license that can be found in the LICENSE file or at
0006 // https://developers.google.com/open-source/licenses/bsd
0007 
0008 // Authors: wink@google.com (Wink Saville),
0009 //          kenton@google.com (Kenton Varda)
0010 //  Based on original Protocol Buffers design by
0011 //  Sanjay Ghemawat, Jeff Dean, and others.
0012 //
0013 // Defines MessageLite, the abstract interface implemented by all (lite
0014 // and non-lite) protocol message objects.
0015 
0016 #ifndef GOOGLE_PROTOBUF_MESSAGE_LITE_H__
0017 #define GOOGLE_PROTOBUF_MESSAGE_LITE_H__
0018 
0019 #include <climits>
0020 #include <cstddef>
0021 #include <cstdint>
0022 #include <iosfwd>
0023 #include <string>
0024 #include <type_traits>
0025 
0026 #include "absl/base/attributes.h"
0027 #include "absl/log/absl_check.h"
0028 #include "absl/strings/cord.h"
0029 #include "absl/strings/string_view.h"
0030 #include "google/protobuf/arena.h"
0031 #include "google/protobuf/explicitly_constructed.h"
0032 #include "google/protobuf/internal_visibility.h"
0033 #include "google/protobuf/io/coded_stream.h"
0034 #include "google/protobuf/metadata_lite.h"
0035 #include "google/protobuf/port.h"
0036 
0037 
0038 // clang-format off
0039 #include "google/protobuf/port_def.inc"
0040 // clang-format on
0041 
0042 #ifdef SWIG
0043 #error "You cannot SWIG proto headers"
0044 #endif
0045 
0046 namespace google {
0047 namespace protobuf {
0048 
0049 template <typename T>
0050 class RepeatedPtrField;
0051 
0052 class FastReflectionMessageMutator;
0053 class FastReflectionStringSetter;
0054 class Reflection;
0055 class Descriptor;
0056 class AssignDescriptorsHelper;
0057 class MessageLite;
0058 
0059 namespace io {
0060 
0061 class CodedInputStream;
0062 class CodedOutputStream;
0063 class ZeroCopyInputStream;
0064 class ZeroCopyOutputStream;
0065 
0066 }  // namespace io
0067 namespace internal {
0068 
0069 // Allow easy change to regular int on platforms where the atomic might have a
0070 // perf impact.
0071 //
0072 // CachedSize is like std::atomic<int> but with some important changes:
0073 //
0074 // 1) CachedSize uses Get / Set rather than load / store.
0075 // 2) CachedSize always uses relaxed ordering.
0076 // 3) CachedSize is assignable and copy-constructible.
0077 // 4) CachedSize has a constexpr default constructor, and a constexpr
0078 //    constructor that takes an int argument.
0079 // 5) If the compiler supports the __atomic_load_n / __atomic_store_n builtins,
0080 //    then CachedSize is trivially copyable.
0081 //
0082 // Developed at https://godbolt.org/z/vYcx7zYs1 ; supports gcc, clang, MSVC.
0083 class PROTOBUF_EXPORT CachedSize {
0084  private:
0085   using Scalar = int;
0086 
0087  public:
0088   constexpr CachedSize() noexcept : atom_(Scalar{}) {}
0089   // NOLINTNEXTLINE(google-explicit-constructor)
0090   constexpr CachedSize(Scalar desired) noexcept : atom_(desired) {}
0091 #if PROTOBUF_BUILTIN_ATOMIC
0092   constexpr CachedSize(const CachedSize& other) = default;
0093 
0094   Scalar Get() const noexcept {
0095     return __atomic_load_n(&atom_, __ATOMIC_RELAXED);
0096   }
0097 
0098   void Set(Scalar desired) noexcept {
0099     __atomic_store_n(&atom_, desired, __ATOMIC_RELAXED);
0100   }
0101 #else
0102   CachedSize(const CachedSize& other) noexcept : atom_(other.Get()) {}
0103   CachedSize& operator=(const CachedSize& other) noexcept {
0104     Set(other.Get());
0105     return *this;
0106   }
0107 
0108   Scalar Get() const noexcept {  //
0109     return atom_.load(std::memory_order_relaxed);
0110   }
0111 
0112   void Set(Scalar desired) noexcept {
0113     atom_.store(desired, std::memory_order_relaxed);
0114   }
0115 #endif
0116 
0117  private:
0118 #if PROTOBUF_BUILTIN_ATOMIC
0119   Scalar atom_;
0120 #else
0121   std::atomic<Scalar> atom_;
0122 #endif
0123 };
0124 
0125 // For MessageLite to friend.
0126 auto GetClassData(const MessageLite& msg);
0127 
0128 class SwapFieldHelper;
0129 
0130 // See parse_context.h for explanation
0131 class ParseContext;
0132 
0133 struct DescriptorTable;
0134 class DescriptorPoolExtensionFinder;
0135 class ExtensionSet;
0136 class LazyField;
0137 class RepeatedPtrFieldBase;
0138 class TcParser;
0139 struct TcParseTableBase;
0140 class WireFormatLite;
0141 class WeakFieldMap;
0142 
0143 template <typename Type>
0144 class GenericTypeHandler;  // defined in repeated_field.h
0145 
0146 // We compute sizes as size_t but cache them as int.  This function converts a
0147 // computed size to a cached size.  Since we don't proceed with serialization
0148 // if the total size was > INT_MAX, it is not important what this function
0149 // returns for inputs > INT_MAX.  However this case should not error or
0150 // ABSL_CHECK-fail, because the full size_t resolution is still returned from
0151 // ByteSizeLong() and checked against INT_MAX; we can catch the overflow
0152 // there.
0153 inline int ToCachedSize(size_t size) { return static_cast<int>(size); }
0154 
0155 // We mainly calculate sizes in terms of size_t, but some functions that
0156 // compute sizes return "int".  These int sizes are expected to always be
0157 // positive. This function is more efficient than casting an int to size_t
0158 // directly on 64-bit platforms because it avoids making the compiler emit a
0159 // sign extending instruction, which we don't want and don't want to pay for.
0160 inline size_t FromIntSize(int size) {
0161   // Convert to unsigned before widening so sign extension is not necessary.
0162   return static_cast<unsigned int>(size);
0163 }
0164 
0165 // For cases where a legacy function returns an integer size.  We ABSL_DCHECK()
0166 // that the conversion will fit within an integer; if this is false then we
0167 // are losing information.
0168 inline int ToIntSize(size_t size) {
0169   ABSL_DCHECK_LE(size, static_cast<size_t>(INT_MAX));
0170   return static_cast<int>(size);
0171 }
0172 
0173 // Default empty string object. Don't use this directly. Instead, call
0174 // GetEmptyString() to get the reference. This empty string is aligned with a
0175 // minimum alignment of 8 bytes to match the requirement of ArenaStringPtr.
0176 PROTOBUF_EXPORT extern ExplicitlyConstructedArenaString
0177     fixed_address_empty_string;
0178 
0179 
0180 PROTOBUF_EXPORT constexpr const std::string& GetEmptyStringAlreadyInited() {
0181   return fixed_address_empty_string.get();
0182 }
0183 
0184 PROTOBUF_EXPORT size_t StringSpaceUsedExcludingSelfLong(const std::string& str);
0185 
0186 }  // namespace internal
0187 
0188 // Interface to light weight protocol messages.
0189 //
0190 // This interface is implemented by all protocol message objects.  Non-lite
0191 // messages additionally implement the Message interface, which is a
0192 // subclass of MessageLite.  Use MessageLite instead when you only need
0193 // the subset of features which it supports -- namely, nothing that uses
0194 // descriptors or reflection.  You can instruct the protocol compiler
0195 // to generate classes which implement only MessageLite, not the full
0196 // Message interface, by adding the following line to the .proto file:
0197 //
0198 //   option optimize_for = LITE_RUNTIME;
0199 //
0200 // This is particularly useful on resource-constrained systems where
0201 // the full protocol buffers runtime library is too big.
0202 //
0203 // Note that on non-constrained systems (e.g. servers) when you need
0204 // to link in lots of protocol definitions, a better way to reduce
0205 // total code footprint is to use optimize_for = CODE_SIZE.  This
0206 // will make the generated code smaller while still supporting all the
0207 // same features (at the expense of speed).  optimize_for = LITE_RUNTIME
0208 // is best when you only have a small number of message types linked
0209 // into your binary, in which case the size of the protocol buffers
0210 // runtime itself is the biggest problem.
0211 //
0212 // Users must not derive from this class. Only the protocol compiler and
0213 // the internal library are allowed to create subclasses.
0214 class PROTOBUF_EXPORT MessageLite {
0215  public:
0216   MessageLite(const MessageLite&) = delete;
0217   MessageLite& operator=(const MessageLite&) = delete;
0218   PROTOBUF_VIRTUAL ~MessageLite() = default;
0219 
0220   // Basic Operations ------------------------------------------------
0221 
0222   // Get the name of this message type, e.g. "foo.bar.BazProto".
0223   std::string GetTypeName() const;
0224 
0225   // Construct a new instance of the same type.  Ownership is passed to the
0226   // caller.
0227   MessageLite* New() const { return New(nullptr); }
0228 
0229   // Construct a new instance on the arena. Ownership is passed to the caller
0230   // if arena is a nullptr.
0231 #if defined(PROTOBUF_CUSTOM_VTABLE)
0232   MessageLite* New(Arena* arena) const;
0233 #else
0234   virtual MessageLite* New(Arena* arena) const = 0;
0235 #endif  // PROTOBUF_CUSTOM_VTABLE
0236 
0237   // Returns the arena, if any, that directly owns this message and its internal
0238   // memory (Arena::Own is different in that the arena doesn't directly own the
0239   // internal memory). This method is used in proto's implementation for
0240   // swapping, moving and setting allocated, for deciding whether the ownership
0241   // of this message or its internal memory could be changed.
0242   Arena* GetArena() const { return _internal_metadata_.arena(); }
0243 
0244   // Clear all fields of the message and set them to their default values.
0245   // Clear() assumes that any memory allocated to hold parts of the message
0246   // will likely be needed again, so the memory used may not be freed.
0247   // To ensure that all memory used by a Message is freed, you must delete it.
0248 #if defined(PROTOBUF_CUSTOM_VTABLE)
0249   void Clear();
0250 #else
0251   virtual void Clear() = 0;
0252 #endif  // PROTOBUF_CUSTOM_VTABLE
0253 
0254   // Quickly check if all required fields have values set.
0255   bool IsInitialized() const;
0256 
0257   // This is not implemented for Lite messages -- it just returns "(cannot
0258   // determine missing fields for lite message)".  However, it is implemented
0259   // for full messages.  See message.h.
0260   std::string InitializationErrorString() const;
0261 
0262   // If |other| is the exact same class as this, calls MergeFrom(). Otherwise,
0263   // results are undefined (probably crash).
0264   void CheckTypeAndMergeFrom(const MessageLite& other);
0265 
0266   // These methods return a human-readable summary of the message. Note that
0267   // since the MessageLite interface does not support reflection, there is very
0268   // little information that these methods can provide. They are shadowed by
0269   // methods of the same name on the Message interface which provide much more
0270   // information. The methods here are intended primarily to facilitate code
0271   // reuse for logic that needs to interoperate with both full and lite protos.
0272   //
0273   // The format of the returned string is subject to change, so please do not
0274   // assume it will remain stable over time.
0275   std::string DebugString() const;
0276   std::string ShortDebugString() const { return DebugString(); }
0277   // MessageLite::DebugString is already Utf8 Safe. This is to add compatibility
0278   // with Message.
0279   std::string Utf8DebugString() const { return DebugString(); }
0280 
0281   // Implementation of the `AbslStringify` interface. This adds `DebugString()`
0282   // to the sink. Do not rely on exact format.
0283   template <typename Sink>
0284   friend void AbslStringify(Sink& sink, const google::protobuf::MessageLite& msg) {
0285     sink.Append(msg.DebugString());
0286   }
0287 
0288   // Parsing ---------------------------------------------------------
0289   // Methods for parsing in protocol buffer format.  Most of these are
0290   // just simple wrappers around MergeFromCodedStream().  Clear() will be
0291   // called before merging the input.
0292 
0293   // Fill the message with a protocol buffer parsed from the given input
0294   // stream. Returns false on a read error or if the input is in the wrong
0295   // format.  A successful return does not indicate the entire input is
0296   // consumed, ensure you call ConsumedEntireMessage() to check that if
0297   // applicable.
0298   ABSL_ATTRIBUTE_REINITIALIZES bool ParseFromCodedStream(
0299       io::CodedInputStream* input);
0300   // Like ParseFromCodedStream(), but accepts messages that are missing
0301   // required fields.
0302   ABSL_ATTRIBUTE_REINITIALIZES bool ParsePartialFromCodedStream(
0303       io::CodedInputStream* input);
0304   // Read a protocol buffer from the given zero-copy input stream.  If
0305   // successful, the entire input will be consumed.
0306   ABSL_ATTRIBUTE_REINITIALIZES bool ParseFromZeroCopyStream(
0307       io::ZeroCopyInputStream* input);
0308   // Like ParseFromZeroCopyStream(), but accepts messages that are missing
0309   // required fields.
0310   ABSL_ATTRIBUTE_REINITIALIZES bool ParsePartialFromZeroCopyStream(
0311       io::ZeroCopyInputStream* input);
0312   // Parse a protocol buffer from a file descriptor.  If successful, the entire
0313   // input will be consumed.
0314   ABSL_ATTRIBUTE_REINITIALIZES bool ParseFromFileDescriptor(
0315       int file_descriptor);
0316   // Like ParseFromFileDescriptor(), but accepts messages that are missing
0317   // required fields.
0318   ABSL_ATTRIBUTE_REINITIALIZES bool ParsePartialFromFileDescriptor(
0319       int file_descriptor);
0320   // Parse a protocol buffer from a C++ istream.  If successful, the entire
0321   // input will be consumed.
0322   ABSL_ATTRIBUTE_REINITIALIZES bool ParseFromIstream(std::istream* input);
0323   // Like ParseFromIstream(), but accepts messages that are missing
0324   // required fields.
0325   ABSL_ATTRIBUTE_REINITIALIZES bool ParsePartialFromIstream(
0326       std::istream* input);
0327   // Read a protocol buffer from the given zero-copy input stream, expecting
0328   // the message to be exactly "size" bytes long.  If successful, exactly
0329   // this many bytes will have been consumed from the input.
0330   bool MergePartialFromBoundedZeroCopyStream(io::ZeroCopyInputStream* input,
0331                                              int size);
0332   // Like ParseFromBoundedZeroCopyStream(), but accepts messages that are
0333   // missing required fields.
0334   bool MergeFromBoundedZeroCopyStream(io::ZeroCopyInputStream* input, int size);
0335   ABSL_ATTRIBUTE_REINITIALIZES bool ParseFromBoundedZeroCopyStream(
0336       io::ZeroCopyInputStream* input, int size);
0337   // Like ParseFromBoundedZeroCopyStream(), but accepts messages that are
0338   // missing required fields.
0339   ABSL_ATTRIBUTE_REINITIALIZES bool ParsePartialFromBoundedZeroCopyStream(
0340       io::ZeroCopyInputStream* input, int size);
0341   // Parses a protocol buffer contained in a string. Returns true on success.
0342   // This function takes a string in the (non-human-readable) binary wire
0343   // format, matching the encoding output by MessageLite::SerializeToString().
0344   // If you'd like to convert a human-readable string into a protocol buffer
0345   // object, see google::protobuf::TextFormat::ParseFromString().
0346   ABSL_ATTRIBUTE_REINITIALIZES bool ParseFromString(absl::string_view data);
0347   // Like ParseFromString(), but accepts messages that are missing
0348   // required fields.
0349   ABSL_ATTRIBUTE_REINITIALIZES bool ParsePartialFromString(
0350       absl::string_view data);
0351   // Parse a protocol buffer contained in an array of bytes.
0352   ABSL_ATTRIBUTE_REINITIALIZES bool ParseFromArray(const void* data, int size);
0353   // Like ParseFromArray(), but accepts messages that are missing
0354   // required fields.
0355   ABSL_ATTRIBUTE_REINITIALIZES bool ParsePartialFromArray(const void* data,
0356                                                           int size);
0357 
0358 
0359   // Reads a protocol buffer from the stream and merges it into this
0360   // Message.  Singular fields read from the what is
0361   // already in the Message and repeated fields are appended to those
0362   // already present.
0363   //
0364   // It is the responsibility of the caller to call input->LastTagWas()
0365   // (for groups) or input->ConsumedEntireMessage() (for non-groups) after
0366   // this returns to verify that the message's end was delimited correctly.
0367   //
0368   // ParseFromCodedStream() is implemented as Clear() followed by
0369   // MergeFromCodedStream().
0370   bool MergeFromCodedStream(io::CodedInputStream* input);
0371 
0372   // Like MergeFromCodedStream(), but succeeds even if required fields are
0373   // missing in the input.
0374   //
0375   // MergeFromCodedStream() is just implemented as MergePartialFromCodedStream()
0376   // followed by IsInitialized().
0377   bool MergePartialFromCodedStream(io::CodedInputStream* input);
0378 
0379   // Merge a protocol buffer contained in a string.
0380   bool MergeFromString(absl::string_view data);
0381 
0382 
0383   // Serialization ---------------------------------------------------
0384   // Methods for serializing in protocol buffer format.  Most of these
0385   // are just simple wrappers around ByteSize() and SerializeWithCachedSizes().
0386 
0387   // Write a protocol buffer of this message to the given output.  Returns
0388   // false on a write error.  If the message is missing required fields,
0389   // this may ABSL_CHECK-fail.
0390   bool SerializeToCodedStream(io::CodedOutputStream* output) const;
0391   // Like SerializeToCodedStream(), but allows missing required fields.
0392   bool SerializePartialToCodedStream(io::CodedOutputStream* output) const;
0393   // Write the message to the given zero-copy output stream.  All required
0394   // fields must be set.
0395   bool SerializeToZeroCopyStream(io::ZeroCopyOutputStream* output) const;
0396   // Like SerializeToZeroCopyStream(), but allows missing required fields.
0397   bool SerializePartialToZeroCopyStream(io::ZeroCopyOutputStream* output) const;
0398   // Serialize the message and store it in the given string.  All required
0399   // fields must be set.
0400   bool SerializeToString(std::string* output) const;
0401   // Like SerializeToString(), but allows missing required fields.
0402   bool SerializePartialToString(std::string* output) const;
0403   // Serialize the message and store it in the given byte array.  All required
0404   // fields must be set.
0405   bool SerializeToArray(void* data, int size) const;
0406   // Like SerializeToArray(), but allows missing required fields.
0407   bool SerializePartialToArray(void* data, int size) const;
0408 
0409   // Make a string encoding the message. Is equivalent to calling
0410   // SerializeToString() on a string and using that.  Returns the empty
0411   // string if SerializeToString() would have returned an error.
0412   // Note: If you intend to generate many such strings, you may
0413   // reduce heap fragmentation by instead re-using the same string
0414   // object with calls to SerializeToString().
0415   std::string SerializeAsString() const;
0416   // Like SerializeAsString(), but allows missing required fields.
0417   std::string SerializePartialAsString() const;
0418 
0419   // Serialize the message and write it to the given file descriptor.  All
0420   // required fields must be set.
0421   bool SerializeToFileDescriptor(int file_descriptor) const;
0422   // Like SerializeToFileDescriptor(), but allows missing required fields.
0423   bool SerializePartialToFileDescriptor(int file_descriptor) const;
0424   // Serialize the message and write it to the given C++ ostream.  All
0425   // required fields must be set.
0426   bool SerializeToOstream(std::ostream* output) const;
0427   // Like SerializeToOstream(), but allows missing required fields.
0428   bool SerializePartialToOstream(std::ostream* output) const;
0429 
0430   // Like SerializeToString(), but appends to the data to the string's
0431   // existing contents.  All required fields must be set.
0432   bool AppendToString(std::string* output) const;
0433   // Like AppendToString(), but allows missing required fields.
0434   bool AppendPartialToString(std::string* output) const;
0435 
0436   // Reads a protocol buffer from a Cord and merges it into this message.
0437   bool MergeFromCord(const absl::Cord& cord);
0438   // Like MergeFromCord(), but accepts messages that are missing
0439   // required fields.
0440   bool MergePartialFromCord(const absl::Cord& cord);
0441   // Parse a protocol buffer contained in a Cord.
0442   ABSL_ATTRIBUTE_REINITIALIZES bool ParseFromCord(const absl::Cord& cord);
0443   // Like ParseFromCord(), but accepts messages that are missing
0444   // required fields.
0445   ABSL_ATTRIBUTE_REINITIALIZES bool ParsePartialFromCord(
0446       const absl::Cord& cord);
0447 
0448   // Serialize the message and store it in the given Cord.  All required
0449   // fields must be set.
0450   bool SerializeToCord(absl::Cord* output) const;
0451   // Like SerializeToCord(), but allows missing required fields.
0452   bool SerializePartialToCord(absl::Cord* output) const;
0453 
0454   // Make a Cord encoding the message. Is equivalent to calling
0455   // SerializeToCord() on a Cord and using that.  Returns an empty
0456   // Cord if SerializeToCord() would have returned an error.
0457   absl::Cord SerializeAsCord() const;
0458   // Like SerializeAsCord(), but allows missing required fields.
0459   absl::Cord SerializePartialAsCord() const;
0460 
0461   // Like SerializeToCord(), but appends to the data to the Cord's existing
0462   // contents.  All required fields must be set.
0463   bool AppendToCord(absl::Cord* output) const;
0464   // Like AppendToCord(), but allows missing required fields.
0465   bool AppendPartialToCord(absl::Cord* output) const;
0466 
0467   // Computes the serialized size of the message.  This recursively calls
0468   // ByteSizeLong() on all embedded messages.
0469   //
0470   // ByteSizeLong() is generally linear in the number of fields defined for the
0471   // proto.
0472 #if defined(PROTOBUF_CUSTOM_VTABLE)
0473   size_t ByteSizeLong() const;
0474 #else
0475   virtual size_t ByteSizeLong() const = 0;
0476 #endif  // PROTOBUF_CUSTOM_VTABLE
0477 
0478   // Legacy ByteSize() API.
0479   [[deprecated("Please use ByteSizeLong() instead")]] int ByteSize() const {
0480     return internal::ToIntSize(ByteSizeLong());
0481   }
0482 
0483   // Serializes the message without recomputing the size.  The message must not
0484   // have changed since the last call to ByteSize(), and the value returned by
0485   // ByteSize must be non-negative.  Otherwise the results are undefined.
0486   void SerializeWithCachedSizes(io::CodedOutputStream* output) const {
0487     output->SetCur(_InternalSerialize(output->Cur(), output->EpsCopy()));
0488   }
0489 
0490   // Functions below here are not part of the public interface.  It isn't
0491   // enforced, but they should be treated as private, and will be private
0492   // at some future time.  Unfortunately the implementation of the "friend"
0493   // keyword in GCC is broken at the moment, but we expect it will be fixed.
0494 
0495   // Like SerializeWithCachedSizes, but writes directly to *target, returning
0496   // a pointer to the byte immediately after the last byte written.  "target"
0497   // must point at a byte array of at least ByteSize() bytes.  Whether to use
0498   // deterministic serialization, e.g., maps in sorted order, is determined by
0499   // CodedOutputStream::IsDefaultSerializationDeterministic().
0500   uint8_t* SerializeWithCachedSizesToArray(uint8_t* target) const;
0501 
0502   // Returns the result of the last call to ByteSize().  An embedded message's
0503   // size is needed both to serialize it (only true for length-prefixed
0504   // submessages) and to compute the outer message's size.  Caching
0505   // the size avoids computing it multiple times.
0506   // Note that the submessage size is unnecessary when using
0507   // group encoding / delimited since we have SGROUP/EGROUP bounds.
0508   //
0509   // ByteSize() does not automatically use the cached size when available
0510   // because this would require invalidating it every time the message was
0511   // modified, which would be too hard and expensive.  (E.g. if a deeply-nested
0512   // sub-message is changed, all of its parents' cached sizes would need to be
0513   // invalidated, which is too much work for an otherwise inlined setter
0514   // method.)
0515   int GetCachedSize() const;
0516 
0517   const char* _InternalParse(const char* ptr, internal::ParseContext* ctx);
0518 
0519   void OnDemandRegisterArenaDtor(Arena* arena);
0520 
0521  protected:
0522   // Message implementations require access to internally visible API.
0523   static constexpr internal::InternalVisibility internal_visibility() {
0524     return internal::InternalVisibility{};
0525   }
0526 
0527   template <typename T>
0528   PROTOBUF_ALWAYS_INLINE static T* DefaultConstruct(Arena* arena) {
0529     return static_cast<T*>(Arena::DefaultConstruct<T>(arena));
0530   }
0531 
0532 #if defined(PROTOBUF_CUSTOM_VTABLE)
0533   template <typename T>
0534   static void* NewImpl(const void* prototype, Arena* arena) {
0535     return static_cast<const T*>(prototype)->New(arena);
0536   }
0537   template <typename T>
0538   static constexpr auto GetNewImpl() {
0539     return NewImpl<T>;
0540   }
0541 
0542   template <typename T>
0543   static void DeleteImpl(void* msg, bool free_memory) {
0544     static_cast<T*>(msg)->~T();
0545     if (free_memory) internal::SizedDelete(msg, sizeof(T));
0546   }
0547   template <typename T>
0548   static constexpr auto GetDeleteImpl() {
0549     return DeleteImpl<T>;
0550   }
0551 
0552   template <typename T>
0553   static void ClearImpl(MessageLite& msg) {
0554     return static_cast<T&>(msg).Clear();
0555   }
0556   template <typename T>
0557   static constexpr auto GetClearImpl() {
0558     return ClearImpl<T>;
0559   }
0560 #else   // PROTOBUF_CUSTOM_VTABLE
0561   // When custom vtables are off we avoid instantiating the functions because we
0562   // will not use them anyway. Less work for the compiler.
0563   template <typename T>
0564   using GetNewImpl = std::nullptr_t;
0565   template <typename T>
0566   using GetDeleteImpl = std::nullptr_t;
0567   template <typename T>
0568   using GetClearImpl = std::nullptr_t;
0569 #endif  // PROTOBUF_CUSTOM_VTABLE
0570 
0571   template <typename T>
0572   PROTOBUF_ALWAYS_INLINE static T* CopyConstruct(Arena* arena, const T& from) {
0573     return static_cast<T*>(Arena::CopyConstruct<T>(arena, &from));
0574   }
0575 
0576   const internal::TcParseTableBase* GetTcParseTable() const {
0577     auto* data = GetClassData();
0578     ABSL_DCHECK(data != nullptr);
0579 
0580     auto* tc_table = data->tc_table;
0581     if (ABSL_PREDICT_FALSE(tc_table == nullptr)) {
0582       ABSL_DCHECK(!data->is_lite);
0583       return data->full().descriptor_methods->get_tc_table(*this);
0584     }
0585     return tc_table;
0586   }
0587 
0588   // We use a secondary vtable for descriptor based methods. This way ClassData
0589   // does not grow with the number of descriptor methods. This avoids extra
0590   // costs in MessageLite.
0591   struct ClassData;
0592   struct ClassDataFull;
0593   struct DescriptorMethods {
0594     absl::string_view (*get_type_name)(const ClassData* data);
0595     std::string (*initialization_error_string)(const MessageLite&);
0596     const internal::TcParseTableBase* (*get_tc_table)(const MessageLite&);
0597     size_t (*space_used_long)(const MessageLite&);
0598     std::string (*debug_string)(const MessageLite&);
0599   };
0600 
0601   // Note: The order of arguments in the functions is chosen so that it has
0602   // the same ABI as the member function that calls them. Eg the `this`
0603   // pointer becomes the first argument in the free function.
0604   //
0605   // Future work:
0606   // We could save more data by omitting any optional pointer that would
0607   // otherwise be null. We can have some metadata in ClassData telling us if we
0608   // have them and their offset.
0609   using NewMessageF = void* (*)(const void* prototype, Arena* arena);
0610   using DeleteMessageF = void (*)(void* msg, bool free_memory);
0611   struct ClassData {
0612     const MessageLite* prototype;
0613     const internal::TcParseTableBase* tc_table;
0614     void (*on_demand_register_arena_dtor)(MessageLite& msg, Arena& arena);
0615     bool (*is_initialized)(const MessageLite&);
0616     void (*merge_to_from)(MessageLite& to, const MessageLite& from_msg);
0617 #if defined(PROTOBUF_CUSTOM_VTABLE)
0618     DeleteMessageF delete_message;
0619     NewMessageF new_message;
0620     void (*clear)(MessageLite&);
0621     size_t (*byte_size_long)(const MessageLite&);
0622     uint8_t* (*serialize)(const MessageLite& msg, uint8_t* ptr,
0623                           io::EpsCopyOutputStream* stream);
0624 #endif  // PROTOBUF_CUSTOM_VTABLE
0625 
0626     // Offset of the CachedSize member.
0627     uint32_t cached_size_offset;
0628     // LITE objects (ie !descriptor_methods) collocate their name as a
0629     // char[] just beyond the ClassData.
0630     bool is_lite;
0631     bool is_dynamic = false;
0632 
0633     // In normal mode we have the small constructor to avoid the cost in
0634     // codegen.
0635 #if !defined(PROTOBUF_CUSTOM_VTABLE)
0636     constexpr ClassData(const MessageLite* prototype,
0637                         const internal::TcParseTableBase* tc_table,
0638                         void (*on_demand_register_arena_dtor)(MessageLite&,
0639                                                               Arena&),
0640                         bool (*is_initialized)(const MessageLite&),
0641                         void (*merge_to_from)(MessageLite& to,
0642                                               const MessageLite& from_msg),
0643                         uint32_t cached_size_offset, bool is_lite)
0644         : prototype(prototype),
0645           tc_table(tc_table),
0646           on_demand_register_arena_dtor(on_demand_register_arena_dtor),
0647           is_initialized(is_initialized),
0648           merge_to_from(merge_to_from),
0649           cached_size_offset(cached_size_offset),
0650           is_lite(is_lite) {}
0651 #endif  // !PROTOBUF_CUSTOM_VTABLE
0652 
0653     // But we always provide the full constructor even in normal mode to make
0654     // helper code simpler.
0655     constexpr ClassData(
0656         const MessageLite* prototype,
0657         const internal::TcParseTableBase* tc_table,
0658         void (*on_demand_register_arena_dtor)(MessageLite&, Arena&),
0659         bool (*is_initialized)(const MessageLite&),
0660         void (*merge_to_from)(MessageLite& to, const MessageLite& from_msg),
0661         DeleteMessageF delete_message,  //
0662         NewMessageF new_message,        //
0663         void (*clear)(MessageLite&),
0664         size_t (*byte_size_long)(const MessageLite&),
0665         uint8_t* (*serialize)(const MessageLite& msg, uint8_t* ptr,
0666                               io::EpsCopyOutputStream* stream),
0667         uint32_t cached_size_offset, bool is_lite)
0668         : prototype(prototype),
0669           tc_table(tc_table),
0670           on_demand_register_arena_dtor(on_demand_register_arena_dtor),
0671           is_initialized(is_initialized),
0672           merge_to_from(merge_to_from),
0673 #if defined(PROTOBUF_CUSTOM_VTABLE)
0674           delete_message(delete_message),
0675           new_message(new_message),
0676           clear(clear),
0677           byte_size_long(byte_size_long),
0678           serialize(serialize),
0679 #endif  // PROTOBUF_CUSTOM_VTABLE
0680           cached_size_offset(cached_size_offset),
0681           is_lite(is_lite) {
0682     }
0683 
0684     const ClassDataFull& full() const {
0685       ABSL_DCHECK(!is_lite);
0686       return *static_cast<const ClassDataFull*>(this);
0687     }
0688   };
0689   template <size_t N>
0690   struct ClassDataLite {
0691     ClassData header;
0692     const char type_name[N];
0693 
0694     constexpr const ClassData* base() const { return &header; }
0695   };
0696   struct ClassDataFull : ClassData {
0697     constexpr ClassDataFull(ClassData base,
0698                             const DescriptorMethods* descriptor_methods,
0699                             const internal::DescriptorTable* descriptor_table,
0700                             void (*get_metadata_tracker)())
0701         : ClassData(base),
0702           descriptor_methods(descriptor_methods),
0703           descriptor_table(descriptor_table),
0704           reflection(),
0705           descriptor(),
0706           get_metadata_tracker(get_metadata_tracker) {}
0707 
0708     constexpr const ClassData* base() const { return this; }
0709 
0710     const DescriptorMethods* descriptor_methods;
0711 
0712     // Codegen types will provide a DescriptorTable to do lazy
0713     // registration/initialization of the reflection objects.
0714     // Other types, like DynamicMessage, keep the table as null but eagerly
0715     // populate `reflection`/`descriptor` fields.
0716     const internal::DescriptorTable* descriptor_table;
0717     // Accesses are protected by the once_flag in `descriptor_table`. When the
0718     // table is null these are populated from the beginning and need to
0719     // protection.
0720     mutable const Reflection* reflection;
0721     mutable const Descriptor* descriptor;
0722 
0723     // When an access tracker is installed, this function notifies the tracker
0724     // that GetMetadata was called.
0725     void (*get_metadata_tracker)();
0726   };
0727 
0728 #if defined(PROTOBUF_CUSTOM_VTABLE)
0729   explicit constexpr MessageLite(const ClassData* data) : _class_data_(data) {}
0730   explicit MessageLite(Arena* arena, const ClassData* data)
0731       : _internal_metadata_(arena), _class_data_(data) {}
0732 #else   // PROTOBUF_CUSTOM_VTABLE
0733   constexpr MessageLite() {}
0734   explicit MessageLite(Arena* arena) : _internal_metadata_(arena) {}
0735   explicit constexpr MessageLite(const ClassData*) {}
0736   explicit MessageLite(Arena* arena, const ClassData*)
0737       : _internal_metadata_(arena) {}
0738 #endif  // PROTOBUF_CUSTOM_VTABLE
0739 
0740   // GetClassData() returns a pointer to a ClassData struct which
0741   // exists in global memory and is unique to each subclass.  This uniqueness
0742   // property is used in order to quickly determine whether two messages are
0743   // of the same type.
0744   //
0745   // This is a work in progress. There are still some types (eg MapEntry) that
0746   // return a default table instead of a unique one.
0747 #if defined(PROTOBUF_CUSTOM_VTABLE)
0748   const ClassData* GetClassData() const {
0749     ::absl::PrefetchToLocalCache(_class_data_);
0750     return _class_data_;
0751   }
0752 #else   // PROTOBUF_CUSTOM_VTABLE
0753   virtual const ClassData* GetClassData() const = 0;
0754 #endif  // PROTOBUF_CUSTOM_VTABLE
0755 
0756   template <typename T>
0757   static auto GetClassDataGenerated() {
0758     static_assert(std::is_base_of<MessageLite, T>::value, "");
0759     // We could speed this up if needed by avoiding the function call.
0760     // In LTO this is likely inlined, so it might not matter.
0761     static_assert(
0762         std::is_same<const T&, decltype(T::default_instance())>::value, "");
0763     return T::default_instance().T::GetClassData();
0764   }
0765 
0766   internal::InternalMetadata _internal_metadata_;
0767 #if defined(PROTOBUF_CUSTOM_VTABLE)
0768   const ClassData* _class_data_;
0769 #endif  // PROTOBUF_CUSTOM_VTABLE
0770 
0771   // Return the cached size object as described by
0772   // ClassData::cached_size_offset.
0773   internal::CachedSize& AccessCachedSize() const;
0774 
0775  public:
0776   enum ParseFlags {
0777     kMerge = 0,
0778     kParse = 1,
0779     kMergePartial = 2,
0780     kParsePartial = 3,
0781     kMergeWithAliasing = 4,
0782     kParseWithAliasing = 5,
0783     kMergePartialWithAliasing = 6,
0784     kParsePartialWithAliasing = 7
0785   };
0786 
0787   template <ParseFlags flags, typename T>
0788   bool ParseFrom(const T& input);
0789 
0790   // Fast path when conditions match (ie. non-deterministic)
0791   //  uint8_t* _InternalSerialize(uint8_t* ptr) const;
0792 #if defined(PROTOBUF_CUSTOM_VTABLE)
0793   uint8_t* _InternalSerialize(uint8_t* ptr,
0794                               io::EpsCopyOutputStream* stream) const;
0795 #else   // PROTOBUF_CUSTOM_VTABLE
0796   virtual uint8_t* _InternalSerialize(
0797       uint8_t* ptr, io::EpsCopyOutputStream* stream) const = 0;
0798 #endif  // PROTOBUF_CUSTOM_VTABLE
0799 
0800   // Identical to IsInitialized() except that it logs an error message.
0801   bool IsInitializedWithErrors() const {
0802     if (IsInitialized()) return true;
0803     LogInitializationErrorMessage();
0804     return false;
0805   }
0806 
0807 #if defined(PROTOBUF_CUSTOM_VTABLE)
0808   void operator delete(MessageLite* msg, std::destroying_delete_t) {
0809     msg->DestroyInstance(true);
0810   }
0811 #endif
0812 
0813  private:
0814   friend class FastReflectionMessageMutator;
0815   friend class AssignDescriptorsHelper;
0816   friend class FastReflectionStringSetter;
0817   friend class Message;
0818   friend class Reflection;
0819   friend class TypeId;
0820   friend class internal::DescriptorPoolExtensionFinder;
0821   friend class internal::ExtensionSet;
0822   friend class internal::LazyField;
0823   friend class internal::SwapFieldHelper;
0824   friend class internal::TcParser;
0825   friend struct internal::TcParseTableBase;
0826   friend class internal::UntypedMapBase;
0827   friend class internal::WeakFieldMap;
0828   friend class internal::WireFormatLite;
0829 
0830   template <typename Type>
0831   friend class Arena::InternalHelper;
0832   template <typename Type>
0833   friend class internal::GenericTypeHandler;
0834 
0835   friend auto internal::GetClassData(const MessageLite& msg);
0836 
0837   void LogInitializationErrorMessage() const;
0838 
0839   bool MergeFromImpl(io::CodedInputStream* input, ParseFlags parse_flags);
0840 
0841   // Runs the destructor for this instance, and if `free_memory` is true,
0842   // also frees the memory.
0843   void DestroyInstance(bool free_memory);
0844 
0845   template <typename T, const void* ptr = T::_raw_default_instance_>
0846   static constexpr auto GetStrongPointerForTypeImpl(int) {
0847     return ptr;
0848   }
0849   template <typename T>
0850   static constexpr auto GetStrongPointerForTypeImpl(char) {
0851     return &T::default_instance;
0852   }
0853   // Return a pointer we can use to make a strong reference to a type.
0854   // Ideally, this is a pointer to the default instance.
0855   // If we can't get that, then we use a pointer to the `default_instance`
0856   // function. The latter always works but pins the function artificially into
0857   // the binary so we avoid it.
0858   template <typename T>
0859   static constexpr auto GetStrongPointerForType() {
0860     return GetStrongPointerForTypeImpl<T>(0);
0861   }
0862   template <typename T>
0863   friend void internal::StrongReferenceToType();
0864 };
0865 
0866 // A `std::type_info` equivalent for protobuf message types.
0867 // This class is preferred over using `typeid` for a few reasons:
0868 //  - It works with RTTI disabled.
0869 //  - It works for `DynamicMessage` types.
0870 //  - It works in custom vtable mode.
0871 //
0872 // Usage:
0873 //  - Instead of `typeid(Type)` use `TypeId::Get<Type>()`
0874 //  - Instead of `typeid(expr)` use `TypeId::Get(expr)`
0875 //
0876 // Supports all relationals including <=>, and supports hashing via
0877 // `absl::Hash`.
0878 class TypeId {
0879  public:
0880   static TypeId Get(const MessageLite& msg) {
0881     return TypeId(msg.GetClassData());
0882   }
0883 
0884   template <typename T>
0885   static TypeId Get() {
0886     return TypeId(MessageLite::GetClassDataGenerated<T>());
0887   }
0888 
0889   // Name of the message type.
0890   // Equivalent to `.GetTypeName()` on the message.
0891   absl::string_view name() const;
0892 
0893   friend constexpr bool operator==(TypeId a, TypeId b) {
0894     return a.data_ == b.data_;
0895   }
0896   friend constexpr bool operator!=(TypeId a, TypeId b) { return !(a == b); }
0897   friend constexpr bool operator<(TypeId a, TypeId b) {
0898     return a.data_ < b.data_;
0899   }
0900   friend constexpr bool operator>(TypeId a, TypeId b) {
0901     return a.data_ > b.data_;
0902   }
0903   friend constexpr bool operator<=(TypeId a, TypeId b) {
0904     return a.data_ <= b.data_;
0905   }
0906   friend constexpr bool operator>=(TypeId a, TypeId b) {
0907     return a.data_ >= b.data_;
0908   }
0909 
0910 #if defined(__cpp_impl_three_way_comparison) && \
0911     __cpp_impl_three_way_comparison >= 201907L
0912   friend constexpr auto operator<=>(TypeId a, TypeId b) {
0913     return a.data_ <=> b.data_;
0914   }
0915 #endif
0916 
0917   template <typename H>
0918   friend H AbslHashValue(H state, TypeId id) {
0919     return H::combine(std::move(state), id.data_);
0920   }
0921 
0922  private:
0923   constexpr explicit TypeId(const MessageLite::ClassData* data) : data_(data) {}
0924 
0925   const MessageLite::ClassData* data_;
0926 };
0927 
0928 namespace internal {
0929 
0930 inline auto GetClassData(const MessageLite& msg) { return msg.GetClassData(); }
0931 
0932 template <bool alias>
0933 bool MergeFromImpl(absl::string_view input, MessageLite* msg,
0934                    const internal::TcParseTableBase* tc_table,
0935                    MessageLite::ParseFlags parse_flags);
0936 extern template PROTOBUF_EXPORT_TEMPLATE_DECLARE bool MergeFromImpl<false>(
0937     absl::string_view input, MessageLite* msg,
0938     const internal::TcParseTableBase* tc_table,
0939     MessageLite::ParseFlags parse_flags);
0940 extern template PROTOBUF_EXPORT_TEMPLATE_DECLARE bool MergeFromImpl<true>(
0941     absl::string_view input, MessageLite* msg,
0942     const internal::TcParseTableBase* tc_table,
0943     MessageLite::ParseFlags parse_flags);
0944 
0945 template <bool alias>
0946 bool MergeFromImpl(io::ZeroCopyInputStream* input, MessageLite* msg,
0947                    const internal::TcParseTableBase* tc_table,
0948                    MessageLite::ParseFlags parse_flags);
0949 extern template PROTOBUF_EXPORT_TEMPLATE_DECLARE bool MergeFromImpl<false>(
0950     io::ZeroCopyInputStream* input, MessageLite* msg,
0951     const internal::TcParseTableBase* tc_table,
0952     MessageLite::ParseFlags parse_flags);
0953 extern template PROTOBUF_EXPORT_TEMPLATE_DECLARE bool MergeFromImpl<true>(
0954     io::ZeroCopyInputStream* input, MessageLite* msg,
0955     const internal::TcParseTableBase* tc_table,
0956     MessageLite::ParseFlags parse_flags);
0957 
0958 struct BoundedZCIS {
0959   io::ZeroCopyInputStream* zcis;
0960   int limit;
0961 };
0962 
0963 template <bool alias>
0964 bool MergeFromImpl(BoundedZCIS input, MessageLite* msg,
0965                    const internal::TcParseTableBase* tc_table,
0966                    MessageLite::ParseFlags parse_flags);
0967 extern template PROTOBUF_EXPORT_TEMPLATE_DECLARE bool MergeFromImpl<false>(
0968     BoundedZCIS input, MessageLite* msg,
0969     const internal::TcParseTableBase* tc_table,
0970     MessageLite::ParseFlags parse_flags);
0971 extern template PROTOBUF_EXPORT_TEMPLATE_DECLARE bool MergeFromImpl<true>(
0972     BoundedZCIS input, MessageLite* msg,
0973     const internal::TcParseTableBase* tc_table,
0974     MessageLite::ParseFlags parse_flags);
0975 
0976 template <typename T>
0977 struct SourceWrapper;
0978 
0979 template <bool alias, typename T>
0980 bool MergeFromImpl(const SourceWrapper<T>& input, MessageLite* msg,
0981                    const internal::TcParseTableBase* tc_table,
0982                    MessageLite::ParseFlags parse_flags) {
0983   return input.template MergeInto<alias>(msg, tc_table, parse_flags);
0984 }
0985 
0986 }  // namespace internal
0987 
0988 template <MessageLite::ParseFlags flags, typename T>
0989 bool MessageLite::ParseFrom(const T& input) {
0990   if (flags & kParse) Clear();
0991   constexpr bool alias = (flags & kMergeWithAliasing) != 0;
0992   const internal::TcParseTableBase* tc_table;
0993   PROTOBUF_ALWAYS_INLINE_CALL tc_table = GetTcParseTable();
0994   return internal::MergeFromImpl<alias>(input, this, tc_table, flags);
0995 }
0996 
0997 // ===================================================================
0998 // Shutdown support.
0999 
1000 
1001 // Shut down the entire protocol buffers library, deleting all static-duration
1002 // objects allocated by the library or by generated .pb.cc files.
1003 //
1004 // There are two reasons you might want to call this:
1005 // * You use a draconian definition of "memory leak" in which you expect
1006 //   every single malloc() to have a corresponding free(), even for objects
1007 //   which live until program exit.
1008 // * You are writing a dynamically-loaded library which needs to clean up
1009 //   after itself when the library is unloaded.
1010 //
1011 // It is safe to call this multiple times.  However, it is not safe to use
1012 // any other part of the protocol buffers library after
1013 // ShutdownProtobufLibrary() has been called. Furthermore this call is not
1014 // thread safe, user needs to synchronize multiple calls.
1015 PROTOBUF_EXPORT void ShutdownProtobufLibrary();
1016 
1017 namespace internal {
1018 
1019 // Register a function to be called when ShutdownProtocolBuffers() is called.
1020 PROTOBUF_EXPORT void OnShutdown(void (*func)());
1021 // Run an arbitrary function on an arg
1022 PROTOBUF_EXPORT void OnShutdownRun(void (*f)(const void*), const void* arg);
1023 
1024 template <typename T>
1025 T* OnShutdownDelete(T* p) {
1026   OnShutdownRun([](const void* pp) { delete static_cast<const T*>(pp); }, p);
1027   return p;
1028 }
1029 
1030 inline void AssertDownCast(const MessageLite& from, const MessageLite& to) {
1031   ABSL_DCHECK(TypeId::Get(from) == TypeId::Get(to))
1032       << "Cannot downcast " << from.GetTypeName() << " to " << to.GetTypeName();
1033 }
1034 
1035 }  // namespace internal
1036 
1037 std::string ShortFormat(const MessageLite& message_lite);
1038 std::string Utf8Format(const MessageLite& message_lite);
1039 
1040 // Cast functions for message pointer/references.
1041 // This is the supported API to cast from a Message/MessageLite to derived
1042 // types. These work even when RTTI is disabled on message types.
1043 //
1044 // The template parameter is simplified and the return type is inferred from the
1045 // input. Eg just `DynamicCastMessage<Foo>(x)` instead of
1046 // `DynamicCastMessage<const Foo*>(x)`.
1047 //
1048 // `DynamicCastMessage` is similar to `dynamic_cast`, returns `nullptr` when the
1049 // input is not an instance of `T`. The overloads that take a reference will
1050 // terminate on mismatch.
1051 //
1052 // `DownCastMessage` is a lightweight function for downcasting base
1053 // `MessageLite` pointer to derived type, where it only does type checking if
1054 // !NDEBUG. It should only be used when the caller is certain that the input
1055 // message is of instance `T`.
1056 template <typename T>
1057 const T* DynamicCastMessage(const MessageLite* from) {
1058   static_assert(std::is_base_of<MessageLite, T>::value, "");
1059 
1060   // We might avoid the call to T::GetClassData() altogether if T were to
1061   // expose the class data pointer.
1062   if (from == nullptr || TypeId::Get<T>() != TypeId::Get(*from)) {
1063     return nullptr;
1064   }
1065 
1066   return static_cast<const T*>(from);
1067 }
1068 
1069 template <typename T>
1070 T* DynamicCastMessage(MessageLite* from) {
1071   return const_cast<T*>(
1072       DynamicCastMessage<T>(static_cast<const MessageLite*>(from)));
1073 }
1074 
1075 namespace internal {
1076 [[noreturn]] PROTOBUF_EXPORT void FailDynamicCast(const MessageLite& from,
1077                                                   const MessageLite& to);
1078 }  // namespace internal
1079 
1080 template <typename T>
1081 const T& DynamicCastMessage(const MessageLite& from) {
1082   const T* destination_message = DynamicCastMessage<T>(&from);
1083   if (ABSL_PREDICT_FALSE(destination_message == nullptr)) {
1084     // Move the logging into an out-of-line function to reduce bloat in the
1085     // caller.
1086     internal::FailDynamicCast(from, T::default_instance());
1087   }
1088   return *destination_message;
1089 }
1090 
1091 template <typename T>
1092 T& DynamicCastMessage(MessageLite& from) {
1093   return const_cast<T&>(
1094       DynamicCastMessage<T>(static_cast<const MessageLite&>(from)));
1095 }
1096 
1097 template <typename T>
1098 const T* DownCastMessage(const MessageLite* from) {
1099   internal::StrongReferenceToType<T>();
1100   ABSL_DCHECK(DynamicCastMessage<T>(from) == from)
1101       << "Cannot downcast " << from->GetTypeName() << " to "
1102       << T::default_instance().GetTypeName();
1103   return static_cast<const T*>(from);
1104 }
1105 
1106 template <typename T>
1107 T* DownCastMessage(MessageLite* from) {
1108   return const_cast<T*>(
1109       DownCastMessage<T>(static_cast<const MessageLite*>(from)));
1110 }
1111 
1112 template <typename T>
1113 const T& DownCastMessage(const MessageLite& from) {
1114   return *DownCastMessage<T>(&from);
1115 }
1116 
1117 template <typename T>
1118 T& DownCastMessage(MessageLite& from) {
1119   return *DownCastMessage<T>(&from);
1120 }
1121 
1122 template <>
1123 inline const MessageLite* DynamicCastMessage(const MessageLite* from) {
1124   return from;
1125 }
1126 template <>
1127 inline const MessageLite* DownCastMessage(const MessageLite* from) {
1128   return from;
1129 }
1130 
1131 // Deprecated names for the cast functions.
1132 // Prefer the ones above.
1133 template <typename T>
1134 PROTOBUF_DEPRECATE_AND_INLINE()
1135 const T* DynamicCastToGenerated(const MessageLite* from) {
1136   return DynamicCastMessage<T>(from);
1137 }
1138 
1139 template <typename T>
1140 PROTOBUF_DEPRECATE_AND_INLINE()
1141 T* DynamicCastToGenerated(MessageLite* from) {
1142   return DynamicCastMessage<T>(from);
1143 }
1144 
1145 template <typename T>
1146 PROTOBUF_DEPRECATE_AND_INLINE()
1147 const T& DynamicCastToGenerated(const MessageLite& from) {
1148   return DynamicCastMessage<T>(from);
1149 }
1150 
1151 template <typename T>
1152 PROTOBUF_DEPRECATE_AND_INLINE()
1153 T& DynamicCastToGenerated(MessageLite& from) {
1154   return DynamicCastMessage<T>(from);
1155 }
1156 
1157 template <typename T>
1158 PROTOBUF_DEPRECATE_AND_INLINE()
1159 const T* DownCastToGenerated(const MessageLite* from) {
1160   return DownCastMessage<T>(from);
1161 }
1162 
1163 template <typename T>
1164 PROTOBUF_DEPRECATE_AND_INLINE()
1165 T* DownCastToGenerated(MessageLite* from) {
1166   return DownCastMessage<T>(from);
1167 }
1168 
1169 template <typename T>
1170 PROTOBUF_DEPRECATE_AND_INLINE()
1171 const T& DownCastToGenerated(const MessageLite& from) {
1172   return DownCastMessage<T>(from);
1173 }
1174 
1175 template <typename T>
1176 PROTOBUF_DEPRECATE_AND_INLINE()
1177 T& DownCastToGenerated(MessageLite& from) {
1178   return DownCastMessage<T>(from);
1179 }
1180 
1181 }  // namespace protobuf
1182 }  // namespace google
1183 
1184 #include "google/protobuf/port_undef.inc"
1185 
1186 #endif  // GOOGLE_PROTOBUF_MESSAGE_LITE_H__