Back to home page

EIC code displayed by LXR

 
 

    


Warning, file /include/google/protobuf/message_lite.h was not indexed or was modified since last indexation (in which case cross-reference links may be missing, inaccurate or erroneous).

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 // This is only intended to be extended by protoc created gencode or types
0017 // defined in the Protobuf runtime. It is not intended or supported for
0018 // application code to extend this class, and any protected methods may be
0019 // removed without being it being considered a breaking change as long as the
0020 // corresponding gencode does not use it.
0021 
0022 #ifndef GOOGLE_PROTOBUF_MESSAGE_LITE_H__
0023 #define GOOGLE_PROTOBUF_MESSAGE_LITE_H__
0024 
0025 #include <climits>
0026 #include <cstddef>
0027 #include <cstdint>
0028 #include <cstring>
0029 #include <iosfwd>
0030 #include <memory>
0031 #include <string>
0032 #include <type_traits>
0033 #include <utility>
0034 
0035 #include "absl/base/attributes.h"
0036 #include "absl/log/absl_check.h"
0037 #include "absl/numeric/bits.h"
0038 #include "absl/strings/cord.h"
0039 #include "absl/strings/string_view.h"
0040 #include "google/protobuf/arena.h"
0041 #include "google/protobuf/internal_visibility.h"
0042 #include "google/protobuf/io/coded_stream.h"
0043 #include "google/protobuf/metadata_lite.h"
0044 #include "google/protobuf/port.h"
0045 
0046 
0047 // clang-format off
0048 #include "google/protobuf/port_def.inc"
0049 // clang-format on
0050 
0051 #ifdef SWIG
0052 #error "You cannot SWIG proto headers"
0053 #endif
0054 
0055 namespace google {
0056 namespace protobuf {
0057 
0058 template <typename T>
0059 class RepeatedPtrField;
0060 
0061 class FastReflectionMessageMutator;
0062 class FastReflectionStringSetter;
0063 class Reflection;
0064 class Descriptor;
0065 class AssignDescriptorsHelper;
0066 class MessageLite;
0067 
0068 namespace io {
0069 
0070 class CodedInputStream;
0071 class CodedOutputStream;
0072 class ZeroCopyInputStream;
0073 class ZeroCopyOutputStream;
0074 
0075 }  // namespace io
0076 
0077 namespace compiler {
0078 namespace cpp {
0079 class MessageTableTester;
0080 }  // namespace cpp
0081 }  // namespace compiler
0082 
0083 namespace internal {
0084 
0085 namespace v2 {
0086 class TableDriven;
0087 class TableDrivenMessage;
0088 class TableDrivenParse;
0089 }  // namespace v2
0090 
0091 class MessageCreator {
0092  public:
0093   using Func = void* (*)(const void*, void*, Arena*);
0094 
0095   // Use -1/0/1 to be able to use <0, ==0, >0
0096   enum Tag : int8_t {
0097     kFunc = -1,
0098     kZeroInit = 0,
0099     kMemcpy = 1,
0100   };
0101 
0102   constexpr MessageCreator()
0103       : allocation_size_(), tag_(), alignment_(), arena_bits_(uintptr_t{}) {}
0104 
0105   static constexpr MessageCreator ZeroInit(uint32_t allocation_size,
0106                                            uint8_t alignment,
0107                                            uintptr_t arena_bits = 0) {
0108     MessageCreator out;
0109     out.allocation_size_ = allocation_size;
0110     out.tag_ = kZeroInit;
0111     out.alignment_ = alignment;
0112     out.arena_bits_ = arena_bits;
0113     return out;
0114   }
0115   static constexpr MessageCreator CopyInit(uint32_t allocation_size,
0116                                            uint8_t alignment,
0117                                            uintptr_t arena_bits = 0) {
0118     MessageCreator out;
0119     out.allocation_size_ = allocation_size;
0120     out.tag_ = kMemcpy;
0121     out.alignment_ = alignment;
0122     out.arena_bits_ = arena_bits;
0123     return out;
0124   }
0125   constexpr MessageCreator(Func func, uint32_t allocation_size,
0126                            uint8_t alignment)
0127       : allocation_size_(allocation_size),
0128         tag_(kFunc),
0129         alignment_(alignment),
0130         func_(func) {}
0131 
0132   // Template for testing.
0133   template <typename MessageLite>
0134   MessageLite* New(const MessageLite* prototype_for_func,
0135                    const MessageLite* prototype_for_copy, Arena* arena) const;
0136 
0137   template <typename MessageLite>
0138   MessageLite* PlacementNew(const MessageLite* prototype_for_func,
0139                             const MessageLite* prototype_for_copy, void* mem,
0140                             Arena* arena) const;
0141 
0142   Tag tag() const { return tag_; }
0143 
0144   uint32_t allocation_size() const { return allocation_size_; }
0145 
0146   uint8_t alignment() const { return alignment_; }
0147 
0148   uintptr_t arena_bits() const {
0149     ABSL_DCHECK_NE(+tag(), +kFunc);
0150     return arena_bits_;
0151   }
0152 
0153  private:
0154   uint32_t allocation_size_;
0155   Tag tag_;
0156   uint8_t alignment_;
0157   union {
0158     Func func_;
0159     uintptr_t arena_bits_;
0160   };
0161 };
0162 
0163 // Allow easy change to regular int on platforms where the atomic might have a
0164 // perf impact.
0165 //
0166 // CachedSize is like std::atomic<int> but with some important changes:
0167 //
0168 // 1) CachedSize uses Get / Set rather than load / store.
0169 // 2) CachedSize always uses relaxed ordering.
0170 // 3) CachedSize is assignable and copy-constructible.
0171 // 4) CachedSize has a constexpr default constructor, and a constexpr
0172 //    constructor that takes an int argument.
0173 // 5) If the compiler supports the __atomic_load_n / __atomic_store_n builtins,
0174 //    then CachedSize is trivially copyable.
0175 //
0176 // Developed at https://godbolt.org/z/vYcx7zYs1 ; supports gcc, clang, MSVC.
0177 class PROTOBUF_EXPORT CachedSize {
0178  private:
0179   using Scalar = int;
0180 
0181  public:
0182   constexpr CachedSize() noexcept : atom_(Scalar{}) {}
0183   // NOLINTNEXTLINE(google-explicit-constructor)
0184   constexpr CachedSize(Scalar desired) noexcept : atom_(desired) {}
0185 
0186 #ifdef PROTOBUF_BUILTIN_ATOMIC
0187   constexpr CachedSize(const CachedSize& other) = default;
0188 
0189   Scalar Get() const noexcept {
0190     return __atomic_load_n(&atom_, __ATOMIC_RELAXED);
0191   }
0192 
0193   void Set(Scalar desired) const noexcept {
0194     // Avoid writing the value when it is zero. This prevents writing to global
0195     // default instances, which might be in readonly memory.
0196     if (ABSL_PREDICT_FALSE(desired == 0)) {
0197       if (Get() == 0) return;
0198     }
0199     __atomic_store_n(&atom_, desired, __ATOMIC_RELAXED);
0200   }
0201 
0202   void SetNonZero(Scalar desired) const noexcept {
0203     ABSL_DCHECK_NE(desired, 0);
0204     __atomic_store_n(&atom_, desired, __ATOMIC_RELAXED);
0205   }
0206 
0207   void SetNoDefaultInstance(Scalar desired) const noexcept {
0208     __atomic_store_n(&atom_, desired, __ATOMIC_RELAXED);
0209   }
0210 #else
0211   CachedSize(const CachedSize& other) noexcept : atom_(other.Get()) {}
0212   CachedSize& operator=(const CachedSize& other) noexcept {
0213     Set(other.Get());
0214     return *this;
0215   }
0216 
0217   Scalar Get() const noexcept {  //
0218     return atom_.load(std::memory_order_relaxed);
0219   }
0220 
0221   void Set(Scalar desired) const noexcept {
0222     // Avoid writing the value when it is zero. This prevents writing to global
0223     // default instances, which might be in readonly memory.
0224     if (ABSL_PREDICT_FALSE(desired == 0)) {
0225       if (Get() == 0) return;
0226     }
0227     atom_.store(desired, std::memory_order_relaxed);
0228   }
0229 
0230   void SetNonZero(Scalar desired) const noexcept {
0231     ABSL_DCHECK_NE(desired, 0);
0232     atom_.store(desired, std::memory_order_relaxed);
0233   }
0234 
0235   void SetNoDefaultInstance(Scalar desired) const noexcept {
0236     atom_.store(desired, std::memory_order_relaxed);
0237   }
0238 #endif
0239 
0240  private:
0241 #ifdef PROTOBUF_BUILTIN_ATOMIC
0242   mutable Scalar atom_;
0243 #else
0244   mutable std::atomic<Scalar> atom_;
0245 #endif
0246 };
0247 
0248 struct ClassData;
0249 
0250 // Returns the ClassData for the given message.
0251 //
0252 // This function is used to get the ClassData for a message without having to
0253 // know the type of the message. This is useful for when the message is a
0254 // generated message.
0255 template <typename Type>
0256 const ClassData* GetClassData(const Type& msg);
0257 
0258 template <const auto* kDefault, const auto* kClassData>
0259 struct GeneratedMessageTraitsT {
0260   static constexpr const void* default_instance() { return kDefault; }
0261   static constexpr const auto* class_data() { return kClassData->base(); }
0262   static constexpr auto StrongPointer() { return default_instance(); }
0263 };
0264 
0265 template <typename T>
0266 struct FallbackMessageTraits {
0267   static const void* default_instance() { return &T::default_instance(); }
0268   static constexpr const auto* class_data() {
0269     // Force the abstract branch of `GetClassData()` to avoid endless recursion.
0270     return GetClassData<MessageLite>(T::default_instance());
0271   }
0272   // We can't make a constexpr pointer to the default, so use a function pointer
0273   // instead.
0274   static constexpr auto StrongPointer() { return &T::default_instance; }
0275 };
0276 
0277 template <const uint32_t* kValidationData>
0278 struct EnumTraitsT {
0279   static constexpr const uint32_t* validation_data() { return kValidationData; }
0280 };
0281 
0282 // Traits for messages and enums.
0283 // We use a class scope variable template, which can be specialized with a
0284 // different type in a non-defining declaration.
0285 // We need non-defining declarations because we might have duplicates of the
0286 // same trait specification on each dependent coming from different .proto.h
0287 // files.
0288 struct MessageTraitsImpl {
0289   template <typename T>
0290   static FallbackMessageTraits<T> value;
0291 };
0292 template <typename T>
0293 using MessageTraits = decltype(MessageTraitsImpl::value<T>);
0294 
0295 struct EnumTraitsImpl {
0296   struct Undefined;
0297   template <typename T>
0298   static Undefined value;
0299 };
0300 template <typename T>
0301 using EnumTraits = decltype(EnumTraitsImpl::value<T>);
0302 
0303 class SwapFieldHelper;
0304 
0305 // See parse_context.h for explanation
0306 class ParseContext;
0307 
0308 struct DescriptorTable;
0309 class DescriptorPoolExtensionFinder;
0310 class ExtensionSet;
0311 class LazyField;
0312 class RepeatedPtrFieldBase;
0313 class TcParser;
0314 struct TcParseTableBase;
0315 class WireFormatLite;
0316 class WeakFieldMap;
0317 class RustMapHelper;
0318 
0319 
0320 // We compute sizes as size_t but cache them as int.  This function converts a
0321 // computed size to a cached size.  Since we don't proceed with serialization
0322 // if the total size was > INT_MAX, it is not important what this function
0323 // returns for inputs > INT_MAX.  However this case should not error or
0324 // ABSL_CHECK-fail, because the full size_t resolution is still returned from
0325 // ByteSizeLong() and checked against INT_MAX; we can catch the overflow
0326 // there.
0327 inline int ToCachedSize(size_t size) { return static_cast<int>(size); }
0328 
0329 // We mainly calculate sizes in terms of size_t, but some functions that
0330 // compute sizes return "int".  These int sizes are expected to always be
0331 // positive. This function is more efficient than casting an int to size_t
0332 // directly on 64-bit platforms because it avoids making the compiler emit a
0333 // sign extending instruction, which we don't want and don't want to pay for.
0334 inline size_t FromIntSize(int size) {
0335   // Convert to unsigned before widening so sign extension is not necessary.
0336   return static_cast<unsigned int>(size);
0337 }
0338 
0339 // For cases where a legacy function returns an integer size.  We ABSL_DCHECK()
0340 // that the conversion will fit within an integer; if this is false then we
0341 // are losing information.
0342 inline int ToIntSize(size_t size) {
0343   ABSL_DCHECK_LE(size, static_cast<size_t>(INT_MAX));
0344   return static_cast<int>(size);
0345 }
0346 
0347 
0348 PROTOBUF_EXPORT inline const std::string& GetEmptyStringAlreadyInited() {
0349   return fixed_address_empty_string.get();
0350 }
0351 
0352 struct ClassDataFull;
0353 
0354 // Note: The order of arguments in the functions is chosen so that it has
0355 // the same ABI as the member function that calls them. Eg the `this`
0356 // pointer becomes the first argument in the free function.
0357 //
0358 // Future work:
0359 // We could save more data by omitting any optional pointer that would
0360 // otherwise be null. We can have some metadata in ClassData telling us if we
0361 // have them and their offset.
0362 
0363 struct PROTOBUF_EXPORT ClassData {
0364   const MessageLite* prototype;
0365   const internal::TcParseTableBase* tc_table;
0366   void (*on_demand_register_arena_dtor)(MessageLite& msg, Arena& arena);
0367   bool (*is_initialized)(const MessageLite&);
0368   void (*merge_to_from)(MessageLite& to, const MessageLite& from_msg);
0369   internal::MessageCreator message_creator;
0370 #if defined(PROTOBUF_CUSTOM_VTABLE)
0371   void (*destroy_message)(MessageLite& msg);
0372   void (MessageLite::*clear)();
0373   size_t (*byte_size_long)(const MessageLite&);
0374   uint8_t* (*serialize)(const MessageLite& msg, uint8_t* ptr,
0375                         io::EpsCopyOutputStream* stream);
0376 #endif  // PROTOBUF_CUSTOM_VTABLE
0377 
0378   // Offset of the CachedSize member.
0379   uint32_t cached_size_offset;
0380   // LITE objects (ie !descriptor_methods) collocate their name as a
0381   // char[] just beyond the ClassData.
0382   bool is_lite;
0383   bool is_dynamic = false;
0384 
0385   // In normal mode we have the small constructor to avoid the cost in
0386   // codegen.
0387 #if !defined(PROTOBUF_CUSTOM_VTABLE)
0388   constexpr ClassData(
0389       const MessageLite* prototype, const internal::TcParseTableBase* tc_table,
0390       void (*on_demand_register_arena_dtor)(MessageLite&, Arena&),
0391       bool (*is_initialized)(const MessageLite&),
0392       void (*merge_to_from)(MessageLite& to, const MessageLite& from_msg),
0393       internal::MessageCreator message_creator, uint32_t cached_size_offset,
0394       bool is_lite
0395       )
0396       : prototype(prototype),
0397         tc_table(tc_table),
0398         on_demand_register_arena_dtor(on_demand_register_arena_dtor),
0399         is_initialized(is_initialized),
0400         merge_to_from(merge_to_from),
0401         message_creator(message_creator),
0402         cached_size_offset(cached_size_offset),
0403         is_lite(is_lite)
0404   {
0405   }
0406 #endif  // !PROTOBUF_CUSTOM_VTABLE
0407 
0408   // But we always provide the full constructor even in normal mode to make
0409   // helper code simpler.
0410   constexpr ClassData(
0411       const MessageLite* prototype, const internal::TcParseTableBase* tc_table,
0412       void (*on_demand_register_arena_dtor)(MessageLite&, Arena&),
0413       bool (*is_initialized)(const MessageLite&),
0414       void (*merge_to_from)(MessageLite& to, const MessageLite& from_msg),
0415       internal::MessageCreator message_creator,
0416       [[maybe_unused]] void (*destroy_message)(MessageLite& msg),  //
0417       [[maybe_unused]] void (MessageLite::*clear)(),
0418       [[maybe_unused]] size_t (*byte_size_long)(const MessageLite&),
0419       [[maybe_unused]] uint8_t* (*serialize)(const MessageLite& msg,
0420                                              uint8_t* ptr,
0421                                              io::EpsCopyOutputStream* stream),
0422       uint32_t cached_size_offset, bool is_lite
0423       )
0424       : prototype(prototype),
0425         tc_table(tc_table),
0426         on_demand_register_arena_dtor(on_demand_register_arena_dtor),
0427         is_initialized(is_initialized),
0428         merge_to_from(merge_to_from),
0429         message_creator(message_creator),
0430 #if defined(PROTOBUF_CUSTOM_VTABLE)
0431         destroy_message(destroy_message),
0432         clear(clear),
0433         byte_size_long(byte_size_long),
0434         serialize(serialize),
0435 #endif  // PROTOBUF_CUSTOM_VTABLE
0436         cached_size_offset(cached_size_offset),
0437         is_lite(is_lite)
0438   {
0439   }
0440 
0441   const ClassDataFull& full() const;
0442 
0443   MessageLite* New(Arena* arena) const {
0444     return message_creator.New(prototype, prototype, arena);
0445   }
0446 
0447   MessageLite* PlacementNew(void* mem, Arena* arena) const {
0448     return message_creator.PlacementNew(prototype, prototype, mem, arena);
0449   }
0450 
0451   uint32_t allocation_size() const { return message_creator.allocation_size(); }
0452 
0453   uint8_t alignment() const { return message_creator.alignment(); }
0454 };
0455 
0456 template <size_t N>
0457 struct ClassDataLite {
0458   ClassData header;
0459   const char type_name[N];
0460 
0461   constexpr const ClassData* base() const { return &header; }
0462 };
0463 
0464 // We use a secondary vtable for descriptor based methods. This way ClassData
0465 // does not grow with the number of descriptor methods. This avoids extra
0466 // costs in MessageLite.
0467 struct PROTOBUF_EXPORT DescriptorMethods {
0468   absl::string_view (*get_type_name)(const ClassData* data);
0469   std::string (*initialization_error_string)(const MessageLite&);
0470   const internal::TcParseTableBase* (*get_tc_table)(const MessageLite&);
0471   size_t (*space_used_long)(const MessageLite&);
0472   std::string (*debug_string)(const MessageLite&);
0473 };
0474 
0475 struct PROTOBUF_EXPORT ClassDataFull : ClassData {
0476   constexpr ClassDataFull(ClassData base,
0477                           const DescriptorMethods* descriptor_methods,
0478                           const internal::DescriptorTable* descriptor_table,
0479                           void (*get_metadata_tracker)())
0480       : ClassData(base),
0481         descriptor_methods(descriptor_methods),
0482         descriptor_table(descriptor_table),
0483         reflection(),
0484         descriptor(),
0485         get_metadata_tracker(get_metadata_tracker) {}
0486 
0487   constexpr const ClassData* base() const { return this; }
0488 
0489   const DescriptorMethods* descriptor_methods;
0490 
0491   // Codegen types will provide a DescriptorTable to do lazy
0492   // registration/initialization of the reflection objects.
0493   // Other types, like DynamicMessage, keep the table as null but eagerly
0494   // populate `reflection`/`descriptor` fields.
0495   const internal::DescriptorTable* descriptor_table;
0496   // Accesses are protected by the once_flag in `descriptor_table`. When the
0497   // table is null these are populated from the beginning and need to
0498   // protection.
0499   mutable const Reflection* reflection;
0500   mutable const Descriptor* descriptor;
0501 
0502   // When an access tracker is installed, this function notifies the tracker
0503   // that GetMetadata was called.
0504   void (*get_metadata_tracker)();
0505 };
0506 
0507 inline const ClassDataFull& ClassData::full() const {
0508   ABSL_DCHECK(!is_lite);
0509   return *static_cast<const ClassDataFull*>(this);
0510 }
0511 
0512 }  // namespace internal
0513 
0514 // Interface to light weight protocol messages.
0515 //
0516 // This interface is implemented by all protocol message objects.  Non-lite
0517 // messages additionally implement the Message interface, which is a
0518 // subclass of MessageLite.  Use MessageLite instead when you only need
0519 // the subset of features which it supports -- namely, nothing that uses
0520 // descriptors or reflection.  You can instruct the protocol compiler
0521 // to generate classes which implement only MessageLite, not the full
0522 // Message interface, by adding the following line to the .proto file:
0523 //
0524 //   option optimize_for = LITE_RUNTIME;
0525 //
0526 // This is particularly useful on resource-constrained systems where
0527 // the full protocol buffers runtime library is too big.
0528 //
0529 // Note that on non-constrained systems (e.g. servers) when you need
0530 // to link in lots of protocol definitions, a better way to reduce
0531 // total code footprint is to use optimize_for = CODE_SIZE.  This
0532 // will make the generated code smaller while still supporting all the
0533 // same features (at the expense of speed).  optimize_for = LITE_RUNTIME
0534 // is best when you only have a small number of message types linked
0535 // into your binary, in which case the size of the protocol buffers
0536 // runtime itself is the biggest problem.
0537 //
0538 // Users must not derive from this class. Only the protocol compiler and
0539 // the internal library are allowed to create subclasses.
0540 class PROTOBUF_EXPORT MessageLite {
0541  public:
0542   MessageLite(const MessageLite&) = delete;
0543   MessageLite& operator=(const MessageLite&) = delete;
0544   PROTOBUF_VIRTUAL ~MessageLite() = default;
0545 
0546   // Basic Operations ------------------------------------------------
0547 
0548   // Get the name of this message type, e.g. "foo.bar.BazProto".
0549   absl::string_view GetTypeName() const;
0550 
0551   // Construct a new instance of the same type.  Ownership is passed to the
0552   // caller.
0553   MessageLite* New() const { return New(nullptr); }
0554 
0555   // Construct a new instance on the arena. Ownership is passed to the caller
0556   // if arena is a nullptr.
0557   MessageLite* New(Arena* arena) const;
0558 
0559   // Returns the arena, if any, that directly owns this message and its internal
0560   // memory (Arena::Own is different in that the arena doesn't directly own the
0561   // internal memory). This method is used in proto's implementation for
0562   // swapping, moving and setting allocated, for deciding whether the ownership
0563   // of this message or its internal memory could be changed.
0564   Arena* GetArena() const { return _internal_metadata_.arena(); }
0565 
0566   // Clear all fields of the message and set them to their default values.
0567   // Clear() assumes that any memory allocated to hold parts of the message
0568   // will likely be needed again, so the memory used may not be freed.
0569   // To ensure that all memory used by a Message is freed, you must delete it.
0570 #if defined(PROTOBUF_CUSTOM_VTABLE)
0571   void Clear() { (this->*_class_data_->clear)(); }
0572 #else
0573   virtual void Clear() = 0;
0574 #endif  // PROTOBUF_CUSTOM_VTABLE
0575 
0576   // Quickly check if all required fields have values set.
0577   bool IsInitialized() const;
0578 
0579   // This is not implemented for Lite messages -- it just returns "(cannot
0580   // determine missing fields for lite message)".  However, it is implemented
0581   // for full messages.  See message.h.
0582   std::string InitializationErrorString() const;
0583 
0584   // If |other| is the exact same class as this, calls MergeFrom(). Otherwise,
0585   // results are undefined (probably crash).
0586   void CheckTypeAndMergeFrom(const MessageLite& other);
0587 
0588   // These methods return a human-readable summary of the message. Note that
0589   // since the MessageLite interface does not support reflection, there is very
0590   // little information that these methods can provide. They are shadowed by
0591   // methods of the same name on the Message interface which provide much more
0592   // information. The methods here are intended primarily to facilitate code
0593   // reuse for logic that needs to interoperate with both full and lite protos.
0594   //
0595   // The format of the returned string is subject to change, so please do not
0596   // assume it will remain stable over time.
0597   std::string DebugString() const;
0598   std::string ShortDebugString() const { return DebugString(); }
0599   // MessageLite::DebugString is already Utf8 Safe. This is to add compatibility
0600   // with Message.
0601   std::string Utf8DebugString() const { return DebugString(); }
0602 
0603   // Implementation of the `AbslStringify` interface. This adds `DebugString()`
0604   // to the sink. Do not rely on exact format.
0605   template <typename Sink>
0606   friend void AbslStringify(Sink& sink, const google::protobuf::MessageLite& msg) {
0607     sink.Append(msg.DebugString());
0608   }
0609 
0610   // Parsing ---------------------------------------------------------
0611   // Methods for parsing in protocol buffer format.  Most of these are
0612   // just simple wrappers around MergeFromCodedStream().  Clear() will be
0613   // called before merging the input.
0614 
0615   // Fill the message with a protocol buffer parsed from the given input
0616   // stream. Returns false on a read error or if the input is in the wrong
0617   // format.  A successful return does not indicate the entire input is
0618   // consumed, ensure you call ConsumedEntireMessage() to check that if
0619   // applicable.
0620   ABSL_ATTRIBUTE_REINITIALIZES bool ParseFromCodedStream(
0621       io::CodedInputStream* input);
0622   // Like ParseFromCodedStream(), but accepts messages that are missing
0623   // required fields.
0624   ABSL_ATTRIBUTE_REINITIALIZES bool ParsePartialFromCodedStream(
0625       io::CodedInputStream* input);
0626   // Read a protocol buffer from the given zero-copy input stream.  If
0627   // successful, the entire input will be consumed.
0628   ABSL_ATTRIBUTE_REINITIALIZES bool ParseFromZeroCopyStream(
0629       io::ZeroCopyInputStream* input);
0630   // Like ParseFromZeroCopyStream(), but accepts messages that are missing
0631   // required fields.
0632   ABSL_ATTRIBUTE_REINITIALIZES bool ParsePartialFromZeroCopyStream(
0633       io::ZeroCopyInputStream* input);
0634   // Parse a protocol buffer from a file descriptor.  If successful, the entire
0635   // input will be consumed.
0636   ABSL_ATTRIBUTE_REINITIALIZES bool ParseFromFileDescriptor(
0637       int file_descriptor);
0638   // Like ParseFromFileDescriptor(), but accepts messages that are missing
0639   // required fields.
0640   ABSL_ATTRIBUTE_REINITIALIZES bool ParsePartialFromFileDescriptor(
0641       int file_descriptor);
0642   // Parse a protocol buffer from a C++ istream.  If successful, the entire
0643   // input will be consumed.
0644   ABSL_ATTRIBUTE_REINITIALIZES bool ParseFromIstream(std::istream* input);
0645   // Like ParseFromIstream(), but accepts messages that are missing
0646   // required fields.
0647   ABSL_ATTRIBUTE_REINITIALIZES bool ParsePartialFromIstream(
0648       std::istream* input);
0649   // Read a protocol buffer from the given zero-copy input stream, expecting
0650   // the message to be exactly "size" bytes long.  If successful, exactly
0651   // this many bytes will have been consumed from the input.
0652   bool MergePartialFromBoundedZeroCopyStream(io::ZeroCopyInputStream* input,
0653                                              int size);
0654   // Like ParseFromBoundedZeroCopyStream(), but accepts messages that are
0655   // missing required fields.
0656   bool MergeFromBoundedZeroCopyStream(io::ZeroCopyInputStream* input, int size);
0657   ABSL_ATTRIBUTE_REINITIALIZES bool ParseFromBoundedZeroCopyStream(
0658       io::ZeroCopyInputStream* input, int size);
0659   // Like ParseFromBoundedZeroCopyStream(), but accepts messages that are
0660   // missing required fields.
0661   ABSL_ATTRIBUTE_REINITIALIZES bool ParsePartialFromBoundedZeroCopyStream(
0662       io::ZeroCopyInputStream* input, int size);
0663   // Parses a protocol buffer contained in a string or Cord. Returns true on
0664   // success. This function takes a string in the (non-human-readable) binary
0665   // wire format, matching the encoding output by
0666   // MessageLite::SerializeToString(). If you'd like to convert a human-readable
0667   // string into a protocol buffer object, see
0668   // google::protobuf::TextFormat::ParseFromString().
0669   ABSL_ATTRIBUTE_REINITIALIZES bool ParseFromString(absl::string_view data);
0670   ABSL_ATTRIBUTE_REINITIALIZES bool ParseFromString(const absl::Cord& data);
0671   // Like ParseFromString(), but accepts messages that are missing
0672   // required fields.
0673   ABSL_ATTRIBUTE_REINITIALIZES bool ParsePartialFromString(
0674       absl::string_view data);
0675   ABSL_ATTRIBUTE_REINITIALIZES bool ParsePartialFromString(
0676       const absl::Cord& data);
0677   // Parse a protocol buffer contained in an array of bytes.
0678   ABSL_ATTRIBUTE_REINITIALIZES bool ParseFromArray(const void* data, int size);
0679   // Like ParseFromArray(), but accepts messages that are missing
0680   // required fields.
0681   ABSL_ATTRIBUTE_REINITIALIZES bool ParsePartialFromArray(const void* data,
0682                                                           int size);
0683 
0684 
0685   // Reads a protocol buffer from the stream and merges it into this
0686   // Message.  Singular fields read from the what is
0687   // already in the Message and repeated fields are appended to those
0688   // already present.
0689   //
0690   // It is the responsibility of the caller to call input->LastTagWas()
0691   // (for groups) or input->ConsumedEntireMessage() (for non-groups) after
0692   // this returns to verify that the message's end was delimited correctly.
0693   //
0694   // ParseFromCodedStream() is implemented as Clear() followed by
0695   // MergeFromCodedStream().
0696   bool MergeFromCodedStream(io::CodedInputStream* input);
0697 
0698   // Like MergeFromCodedStream(), but succeeds even if required fields are
0699   // missing in the input.
0700   //
0701   // MergeFromCodedStream() is just implemented as MergePartialFromCodedStream()
0702   // followed by IsInitialized().
0703   bool MergePartialFromCodedStream(io::CodedInputStream* input);
0704 
0705   // Merge a protocol buffer contained in a string.
0706   bool MergeFromString(absl::string_view data);
0707   bool MergeFromString(const absl::Cord& data);
0708 
0709   // Like MergeFromString(), but accepts messages that are missing required
0710   // fields.
0711   bool MergePartialFromString(absl::string_view data);
0712   bool MergePartialFromString(const absl::Cord& data);
0713 
0714   // Serialization ---------------------------------------------------
0715   // Methods for serializing in protocol buffer format.  Most of these
0716   // are just simple wrappers around ByteSize() and SerializeWithCachedSizes().
0717 
0718   // Write a protocol buffer of this message to the given output.  Returns
0719   // false on a write error.  If the message is missing required fields,
0720   // this may ABSL_CHECK-fail.
0721   bool SerializeToCodedStream(io::CodedOutputStream* output) const;
0722   // Like SerializeToCodedStream(), but allows missing required fields.
0723   bool SerializePartialToCodedStream(io::CodedOutputStream* output) const;
0724   // Write the message to the given zero-copy output stream.  All required
0725   // fields must be set.
0726   bool SerializeToZeroCopyStream(io::ZeroCopyOutputStream* output) const;
0727   // Like SerializeToZeroCopyStream(), but allows missing required fields.
0728   bool SerializePartialToZeroCopyStream(io::ZeroCopyOutputStream* output) const;
0729   // Serialize the message and store it in the given string.  All required
0730   // fields must be set.
0731   bool SerializeToString(std::string* output) const;
0732   // Serialize the message and store it in the given Cord.  All required
0733   // fields must be set.
0734   bool SerializeToString(absl::Cord* output) const;
0735   // Like SerializeToString(), but allows missing required fields.
0736   bool SerializePartialToString(std::string* output) const;
0737   bool SerializePartialToString(absl::Cord* output) const;
0738   // Serialize the message and store it in the given byte array.  All required
0739   // fields must be set.
0740   bool SerializeToArray(void* data, int size) const;
0741   // Like SerializeToArray(), but allows missing required fields.
0742   bool SerializePartialToArray(void* data, int size) const;
0743 
0744   // Make a string encoding the message. Is equivalent to calling
0745   // SerializeToString() on a string and using that.  Returns the empty
0746   // string if SerializeToString() would have returned an error.
0747   // Note: If you intend to generate many such strings, you may
0748   // reduce heap fragmentation by instead re-using the same string
0749   // object with calls to SerializeToString().
0750   std::string SerializeAsString() const;
0751   // Like SerializeAsString(), but allows missing required fields.
0752   std::string SerializePartialAsString() const;
0753 
0754   // Serialize the message and write it to the given file descriptor.  All
0755   // required fields must be set.
0756   bool SerializeToFileDescriptor(int file_descriptor) const;
0757   // Like SerializeToFileDescriptor(), but allows missing required fields.
0758   bool SerializePartialToFileDescriptor(int file_descriptor) const;
0759   // Serialize the message and write it to the given C++ ostream.  All
0760   // required fields must be set.
0761   bool SerializeToOstream(std::ostream* output) const;
0762   // Like SerializeToOstream(), but allows missing required fields.
0763   bool SerializePartialToOstream(std::ostream* output) const;
0764 
0765   // Like SerializeToString(), but appends to the data to the string's
0766   // existing contents.  All required fields must be set.
0767   bool AppendToString(std::string* output) const;
0768   bool AppendToString(absl::Cord* output) const;
0769   // Like AppendToString(), but allows missing required fields.
0770   bool AppendPartialToString(std::string* output) const;
0771   bool AppendPartialToString(absl::Cord* output) const;
0772 
0773   // Reads a protocol buffer from a Cord and merges it into this message.
0774   PROTOBUF_DEPRECATE_AND_INLINE() bool MergeFromCord(const absl::Cord& data) {
0775     return MergeFromString(data);
0776   }
0777   // Like MergeFromCord(), but accepts messages that are missing
0778   // required fields.
0779   PROTOBUF_DEPRECATE_AND_INLINE()
0780   bool MergePartialFromCord(const absl::Cord& data) {
0781     return MergePartialFromString(data);
0782   }
0783   // Parse a protocol buffer contained in a Cord.
0784   PROTOBUF_DEPRECATE_AND_INLINE()
0785   ABSL_ATTRIBUTE_REINITIALIZES bool ParseFromCord(const absl::Cord& data) {
0786     return ParseFromString(data);
0787   }
0788   // Like ParseFromCord(), but accepts messages that are missing
0789   // required fields.
0790   PROTOBUF_DEPRECATE_AND_INLINE()
0791   ABSL_ATTRIBUTE_REINITIALIZES
0792   bool ParsePartialFromCord(const absl::Cord& data) {
0793     return ParsePartialFromString(data);
0794   }
0795 
0796   // Serialize the message and store it in the given Cord.  All required
0797   // fields must be set.
0798   PROTOBUF_DEPRECATE_AND_INLINE()
0799   bool SerializeToCord(absl::Cord* output) const {
0800     return SerializeToString(output);
0801   }
0802   // Like SerializeToCord(), but allows missing required fields.
0803   PROTOBUF_DEPRECATE_AND_INLINE()
0804   bool SerializePartialToCord(absl::Cord* output) const {
0805     return SerializePartialToString(output);
0806   }
0807 
0808   // Make a Cord encoding the message. Is equivalent to calling
0809   // SerializeToCord() on a Cord and using that.  Returns an empty
0810   // Cord if SerializeToCord() would have returned an error.
0811   absl::Cord SerializeAsCord() const;
0812   // Like SerializeAsCord(), but allows missing required fields.
0813   absl::Cord SerializePartialAsCord() const;
0814 
0815   // Like SerializeToCord(), but appends to the data to the Cord's existing
0816   // contents.  All required fields must be set.
0817   PROTOBUF_DEPRECATE_AND_INLINE() bool AppendToCord(absl::Cord* output) const {
0818     return AppendToString(output);
0819   }
0820   // Like AppendToCord(), but allows missing required fields.
0821   PROTOBUF_DEPRECATE_AND_INLINE()
0822   bool AppendPartialToCord(absl::Cord* output) const {
0823     return AppendPartialToString(output);
0824   }
0825 
0826   // Computes the serialized size of the message.  This recursively calls
0827   // ByteSizeLong() on all embedded messages.
0828   //
0829   // ByteSizeLong() is generally linear in the number of fields defined for the
0830   // proto.
0831 #if defined(PROTOBUF_CUSTOM_VTABLE)
0832   size_t ByteSizeLong() const { return _class_data_->byte_size_long(*this); }
0833 #else
0834   virtual size_t ByteSizeLong() const = 0;
0835 #endif  // PROTOBUF_CUSTOM_VTABLE
0836 
0837 
0838   // Legacy ByteSize() API.
0839   [[deprecated("Please use ByteSizeLong() instead")]] int ByteSize() const {
0840     return internal::ToIntSize(ByteSizeLong());
0841   }
0842 
0843   // Serializes the message without recomputing the size.  The message must not
0844   // have changed since the last call to ByteSize(), and the value returned by
0845   // ByteSize must be non-negative.  Otherwise the results are undefined.
0846   void SerializeWithCachedSizes(io::CodedOutputStream* output) const {
0847     output->SetCur(_InternalSerialize(output->Cur(), output->EpsCopy()));
0848   }
0849 
0850   // Functions below here are not part of the public interface.  It isn't
0851   // enforced, but they should be treated as private, and will be private
0852   // at some future time.  Unfortunately the implementation of the "friend"
0853   // keyword in GCC is broken at the moment, but we expect it will be fixed.
0854 
0855   // Like SerializeWithCachedSizes, but writes directly to *target, returning
0856   // a pointer to the byte immediately after the last byte written.  "target"
0857   // must point at a byte array of at least ByteSize() bytes.  Whether to use
0858   // deterministic serialization, e.g., maps in sorted order, is determined by
0859   // CodedOutputStream::IsDefaultSerializationDeterministic().
0860   uint8_t* SerializeWithCachedSizesToArray(uint8_t* target) const;
0861 
0862   // Returns the result of the last call to ByteSize().  An embedded message's
0863   // size is needed both to serialize it (only true for length-prefixed
0864   // submessages) and to compute the outer message's size.  Caching
0865   // the size avoids computing it multiple times.
0866   // Note that the submessage size is unnecessary when using
0867   // group encoding / delimited since we have SGROUP/EGROUP bounds.
0868   //
0869   // ByteSize() does not automatically use the cached size when available
0870   // because this would require invalidating it every time the message was
0871   // modified, which would be too hard and expensive.  (E.g. if a deeply-nested
0872   // sub-message is changed, all of its parents' cached sizes would need to be
0873   // invalidated, which is too much work for an otherwise inlined setter
0874   // method.)
0875 #if defined(PROTOBUF_CUSTOM_VTABLE)
0876   int GetCachedSize() const { return AccessCachedSize().Get(); }
0877 #else
0878   int GetCachedSize() const;
0879 #endif
0880 
0881   const char* _InternalParse(const char* ptr, internal::ParseContext* ctx);
0882 
0883   void OnDemandRegisterArenaDtor(Arena* arena);
0884 
0885  protected:
0886   // Message implementations require access to internally visible API.
0887   static constexpr internal::InternalVisibility internal_visibility() {
0888     return internal::InternalVisibility{};
0889   }
0890 
0891   template <typename T>
0892   PROTOBUF_ALWAYS_INLINE static T* DefaultConstruct(Arena* arena) {
0893     return static_cast<T*>(Arena::DefaultConstruct<T>(arena));
0894   }
0895 
0896   template <typename T>
0897   static void* NewImpl(const void*, void* mem, Arena* arena) {
0898     return ::new (mem) T(arena);
0899   }
0900   template <typename T>
0901   static constexpr internal::MessageCreator GetNewImpl() {
0902     if constexpr (internal::EnableCustomNewFor<T>()) {
0903       return T::InternalNewImpl_();
0904     } else {
0905       return internal::MessageCreator(&T::PlacementNew_, sizeof(T), alignof(T));
0906     }
0907   }
0908 
0909 #if defined(PROTOBUF_CUSTOM_VTABLE)
0910   template <typename T>
0911   static constexpr auto GetClearImpl() {
0912     return static_cast<void (MessageLite::*)()>(&T::Clear);
0913   }
0914 #else   // PROTOBUF_CUSTOM_VTABLE
0915   // When custom vtables are off we avoid instantiating the functions because we
0916   // will not use them anyway. Less work for the compiler.
0917   template <typename T>
0918   using GetClearImpl = std::nullptr_t;
0919 #endif  // PROTOBUF_CUSTOM_VTABLE
0920 
0921   template <typename T>
0922   PROTOBUF_ALWAYS_INLINE static T* CopyConstruct(Arena* arena, const T& from) {
0923     return static_cast<T*>(Arena::CopyConstruct<T>(arena, &from));
0924   }
0925 
0926   // As above, but for fields that use base class type. Eg foreign weak fields.
0927   static MessageLite* CopyConstruct(Arena* arena, const MessageLite& from);
0928 
0929   PROTOBUF_ALWAYS_INLINE static Message* CopyConstruct(Arena* arena,
0930                                                        const Message& from) {
0931     return reinterpret_cast<Message*>(
0932         CopyConstruct(arena, reinterpret_cast<const MessageLite&>(from)));
0933   }
0934 
0935   const internal::TcParseTableBase* GetTcParseTable() const {
0936     auto* data = GetClassData();
0937     ABSL_DCHECK(data != nullptr);
0938 
0939     auto* tc_table = data->tc_table;
0940     if (ABSL_PREDICT_FALSE(tc_table == nullptr)) {
0941       ABSL_DCHECK(!data->is_lite);
0942       return data->full().descriptor_methods->get_tc_table(*this);
0943     }
0944     return tc_table;
0945   }
0946 
0947 
0948 #if defined(PROTOBUF_CUSTOM_VTABLE)
0949   explicit constexpr MessageLite(const internal::ClassData* data)
0950       : _class_data_(data) {}
0951   explicit MessageLite(Arena* arena, const internal::ClassData* data)
0952       : _internal_metadata_(arena), _class_data_(data) {}
0953 #else   // PROTOBUF_CUSTOM_VTABLE
0954   constexpr MessageLite() {}
0955   explicit MessageLite(Arena* arena) : _internal_metadata_(arena) {}
0956   explicit constexpr MessageLite(const internal::ClassData*) {}
0957   explicit MessageLite(Arena* arena, const internal::ClassData*)
0958       : _internal_metadata_(arena) {}
0959 #endif  // PROTOBUF_CUSTOM_VTABLE
0960 
0961   // GetClassData() returns a pointer to a ClassData struct which
0962   // exists in global memory and is unique to each subclass.  This uniqueness
0963   // property is used in order to quickly determine whether two messages are
0964   // of the same type.
0965   //
0966   // This is a work in progress. There are still some types (eg MapEntry) that
0967   // return a default table instead of a unique one.
0968 #if defined(PROTOBUF_CUSTOM_VTABLE)
0969   const internal::ClassData* GetClassData() const {
0970     ::absl::PrefetchToLocalCache(_class_data_);
0971     return _class_data_;
0972   }
0973 #else   // PROTOBUF_CUSTOM_VTABLE
0974   virtual const internal::ClassData* GetClassData() const = 0;
0975 #endif  // PROTOBUF_CUSTOM_VTABLE
0976 
0977   internal::InternalMetadata _internal_metadata_;
0978 #if defined(PROTOBUF_CUSTOM_VTABLE)
0979   const internal::ClassData* _class_data_;
0980 #endif  // PROTOBUF_CUSTOM_VTABLE
0981 
0982   // Return the cached size object as described by
0983   // ClassData::cached_size_offset.
0984   const internal::CachedSize& AccessCachedSize() const {
0985     return *reinterpret_cast<const internal::CachedSize*>(
0986         reinterpret_cast<const char*>(this) +
0987         GetClassData()->cached_size_offset);
0988   }
0989 
0990   void VerifyHasBitConsistency() const;
0991 
0992  public:
0993   enum ParseFlags {
0994     // Merge vs. Parse:
0995     // Merge: overwrites scalar fields but appends to repeated fields in the
0996     //        destination; other fields in the destination remain untouched.
0997     // Parse: clears all fields in the destination before calling Merge.
0998     kMerge = 0,
0999     kParse = 1,
1000     // Default behaviour vs. Partial:
1001     // Default: a missing required field is deemed as parsing failure.
1002     // Partial: parse or merge will not give an error if input is missing
1003     //          required fields.
1004     kMergePartial = 2,
1005     kParsePartial = 3,
1006     // Default behaviour vs. Aliasing:
1007     // Default:  when merging, pointer is followed and expanded (deep-copy).
1008     // Aliasing: when merging, the destination message is allowed to retain
1009     //           pointers to the original structure (shallow-copy). This mostly
1010     //           is intended for use with STRING_PIECE.
1011     // NOTE: STRING_PIECE is not recommended for new usage. Prefer Cords.
1012     kMergeWithAliasing = 4,
1013     kParseWithAliasing = 5,
1014     kMergePartialWithAliasing = 6,
1015     kParsePartialWithAliasing = 7
1016   };
1017 
1018   template <ParseFlags flags, typename T>
1019   bool ParseFrom(const T& input);
1020 
1021   // Fast path when conditions match (ie. non-deterministic)
1022   //  uint8_t* _InternalSerialize(uint8_t* ptr) const;
1023 #if defined(PROTOBUF_CUSTOM_VTABLE)
1024   uint8_t* _InternalSerialize(uint8_t* ptr,
1025                               io::EpsCopyOutputStream* stream) const {
1026     return _class_data_->serialize(*this, ptr, stream);
1027   }
1028 #else   // PROTOBUF_CUSTOM_VTABLE
1029   virtual uint8_t* _InternalSerialize(
1030       uint8_t* ptr, io::EpsCopyOutputStream* stream) const = 0;
1031 #endif  // PROTOBUF_CUSTOM_VTABLE
1032 
1033   // Identical to IsInitialized() except that it logs an error message.
1034   bool IsInitializedWithErrors() const {
1035     if (IsInitialized()) return true;
1036     LogInitializationErrorMessage();
1037     return false;
1038   }
1039 
1040 #if defined(PROTOBUF_CUSTOM_VTABLE)
1041   void operator delete(MessageLite* msg, std::destroying_delete_t) {
1042     msg->DeleteInstance();
1043   }
1044 #endif
1045 
1046  private:
1047   friend class FastReflectionMessageMutator;
1048   friend class AssignDescriptorsHelper;
1049   friend class FastReflectionStringSetter;
1050   friend class Message;
1051   friend class Reflection;
1052   friend class TypeId;
1053   friend class compiler::cpp::MessageTableTester;
1054   friend class internal::DescriptorPoolExtensionFinder;
1055   friend class internal::ExtensionSet;
1056   friend class internal::LazyField;
1057   friend class internal::SwapFieldHelper;
1058   friend class internal::TcParser;
1059   friend struct internal::TcParseTableBase;
1060   friend class internal::UntypedMapBase;
1061   friend class internal::WeakFieldMap;
1062   friend class internal::WireFormatLite;
1063   friend class internal::RustMapHelper;
1064   friend class internal::v2::TableDriven;
1065   friend class internal::v2::TableDrivenMessage;
1066   friend class internal::v2::TableDrivenParse;
1067   friend class internal::MessageCreator;
1068   friend class internal::RepeatedPtrFieldBase;
1069   template <typename Type>
1070   friend class internal::GenericTypeHandler;
1071   template <typename Type>
1072   friend class Arena::InternalHelper;
1073   template <typename Type>
1074   friend struct FallbackMessageTraits;
1075 
1076   template <typename Type>
1077   friend const internal::ClassData* internal::GetClassData(const Type& msg);
1078 
1079   static bool CheckFieldPresence(const internal::ParseContext& ctx,
1080                                  const MessageLite& msg,
1081                                  MessageLite::ParseFlags parse_flags);
1082 
1083   void LogInitializationErrorMessage() const;
1084 
1085   // Merges the contents of `other` into `this`. This is faster than
1086   // `CheckTypeAndMergeFrom()` and should be preferred by friended internal
1087   // callers that have the right `ClassData` handy.
1088   // REQUIRES: Both `this` and `other` are the exact same class as represented
1089   // by `data`. If there is a mismatch, CHECK-fails in debug builds or causes UB
1090   // in release builds (probably a crash).
1091   void MergeFromWithClassData(const MessageLite& other,
1092                               const internal::ClassData* data);
1093 
1094   bool MergeFromImpl(io::CodedInputStream* input, ParseFlags parse_flags);
1095 
1096   // Runs the destructor for this instance.
1097   void DestroyInstance();
1098   // Runs the destructor for this instance and deletes the memory via
1099   // `operator delete`
1100   void DeleteInstance();
1101 
1102   // For tests that need to inspect private _oneof_case_. It is the callers
1103   // responsibility to ensure T has the right member.
1104   template <typename T>
1105   static uint32_t GetOneofCaseOffsetForTesting() {
1106     return offsetof(T, _impl_._oneof_case_);
1107   }
1108 };
1109 
1110 // A `std::type_info` equivalent for protobuf message types.
1111 // This class is preferred over using `typeid` for a few reasons:
1112 //  - It works with RTTI disabled.
1113 //  - It works for `DynamicMessage` types.
1114 //  - It works in custom vtable mode.
1115 //
1116 // Usage:
1117 //  - Instead of `typeid(Type)` use `TypeId::Get<Type>()`
1118 //  - Instead of `typeid(expr)` use `TypeId::Get(expr)`
1119 //
1120 // Supports all relationals including <=>, and supports hashing via
1121 // `absl::Hash`.
1122 class TypeId {
1123  public:
1124   static TypeId Get(const MessageLite& msg) {
1125     return TypeId(msg.GetClassData());
1126   }
1127 
1128   template <typename T>
1129   static TypeId Get() {
1130     return TypeId(internal::MessageTraits<T>::class_data());
1131   }
1132 
1133   // Name of the message type.
1134   // Equivalent to `.GetTypeName()` on the message.
1135   absl::string_view name() const;
1136 
1137   friend constexpr bool operator==(TypeId a, TypeId b) {
1138     return a.data_ == b.data_;
1139   }
1140   friend constexpr bool operator!=(TypeId a, TypeId b) { return !(a == b); }
1141   friend constexpr bool operator<(TypeId a, TypeId b) {
1142     return a.data_ < b.data_;
1143   }
1144   friend constexpr bool operator>(TypeId a, TypeId b) {
1145     return a.data_ > b.data_;
1146   }
1147   friend constexpr bool operator<=(TypeId a, TypeId b) {
1148     return a.data_ <= b.data_;
1149   }
1150   friend constexpr bool operator>=(TypeId a, TypeId b) {
1151     return a.data_ >= b.data_;
1152   }
1153 
1154 #if defined(__cpp_impl_three_way_comparison) && \
1155     __cpp_impl_three_way_comparison >= 201907L
1156   friend constexpr auto operator<=>(TypeId a, TypeId b) {
1157     return a.data_ <=> b.data_;
1158   }
1159 #endif
1160 
1161   template <typename H>
1162   friend H AbslHashValue(H state, TypeId id) {
1163     return H::combine(std::move(state), id.data_);
1164   }
1165 
1166  private:
1167   constexpr explicit TypeId(const internal::ClassData* data) : data_(data) {}
1168 
1169   const internal::ClassData* data_;
1170 };
1171 
1172 namespace internal {
1173 
1174 // The point of this function being a template is that for a concrete message
1175 // `Type`, the otherwise virtual `GetClassData()` call is resolved and inlined
1176 // at compile time (via `MessageTraits`).
1177 template <typename T>
1178 PROTOBUF_NDEBUG_INLINE const ClassData* GetClassData(const T& msg) {
1179   static_assert(std::is_base_of_v<MessageLite, T>);
1180   if constexpr (std::is_same_v<T, MessageLite> || std::is_same_v<Message, T>) {
1181     return msg.GetClassData();
1182   } else {
1183     return MessageTraits<T>::class_data();
1184   }
1185 }
1186 
1187 template <bool alias>
1188 bool MergeFromImpl(absl::string_view input, MessageLite* msg,
1189                    const internal::TcParseTableBase* tc_table,
1190                    MessageLite::ParseFlags parse_flags);
1191 extern template PROTOBUF_EXPORT_TEMPLATE_DECLARE bool MergeFromImpl<false>(
1192     absl::string_view input, MessageLite* msg,
1193     const internal::TcParseTableBase* tc_table,
1194     MessageLite::ParseFlags parse_flags);
1195 extern template PROTOBUF_EXPORT_TEMPLATE_DECLARE bool MergeFromImpl<true>(
1196     absl::string_view input, MessageLite* msg,
1197     const internal::TcParseTableBase* tc_table,
1198     MessageLite::ParseFlags parse_flags);
1199 
1200 template <bool alias>
1201 bool MergeFromImpl(io::ZeroCopyInputStream* input, MessageLite* msg,
1202                    const internal::TcParseTableBase* tc_table,
1203                    MessageLite::ParseFlags parse_flags);
1204 extern template PROTOBUF_EXPORT_TEMPLATE_DECLARE bool MergeFromImpl<false>(
1205     io::ZeroCopyInputStream* input, MessageLite* msg,
1206     const internal::TcParseTableBase* tc_table,
1207     MessageLite::ParseFlags parse_flags);
1208 extern template PROTOBUF_EXPORT_TEMPLATE_DECLARE bool MergeFromImpl<true>(
1209     io::ZeroCopyInputStream* input, MessageLite* msg,
1210     const internal::TcParseTableBase* tc_table,
1211     MessageLite::ParseFlags parse_flags);
1212 
1213 struct BoundedZCIS {
1214   io::ZeroCopyInputStream* zcis;
1215   int limit;
1216 };
1217 
1218 template <bool alias>
1219 bool MergeFromImpl(BoundedZCIS input, MessageLite* msg,
1220                    const internal::TcParseTableBase* tc_table,
1221                    MessageLite::ParseFlags parse_flags);
1222 extern template PROTOBUF_EXPORT_TEMPLATE_DECLARE bool MergeFromImpl<false>(
1223     BoundedZCIS input, MessageLite* msg,
1224     const internal::TcParseTableBase* tc_table,
1225     MessageLite::ParseFlags parse_flags);
1226 extern template PROTOBUF_EXPORT_TEMPLATE_DECLARE bool MergeFromImpl<true>(
1227     BoundedZCIS input, MessageLite* msg,
1228     const internal::TcParseTableBase* tc_table,
1229     MessageLite::ParseFlags parse_flags);
1230 
1231 template <typename T>
1232 struct SourceWrapper;
1233 
1234 template <bool alias, typename T>
1235 bool MergeFromImpl(const SourceWrapper<T>& input, MessageLite* msg,
1236                    const internal::TcParseTableBase* tc_table,
1237                    MessageLite::ParseFlags parse_flags) {
1238   return input.template MergeInto<alias>(msg, tc_table, parse_flags);
1239 }
1240 
1241 }  // namespace internal
1242 
1243 template <MessageLite::ParseFlags flags, typename T>
1244 bool MessageLite::ParseFrom(const T& input) {
1245   if (flags & kParse) Clear();
1246   constexpr bool alias = (flags & kMergeWithAliasing) != 0;
1247   const internal::TcParseTableBase* tc_table;
1248   PROTOBUF_ALWAYS_INLINE_CALL tc_table = GetTcParseTable();
1249   return internal::MergeFromImpl<alias>(input, this, tc_table, flags);
1250 }
1251 
1252 // ===================================================================
1253 // Shutdown support.
1254 
1255 
1256 // Shut down the entire protocol buffers library, deleting all static-duration
1257 // objects allocated by the library or by generated .pb.cc files.
1258 //
1259 // There are two reasons you might want to call this:
1260 // * You use a draconian definition of "memory leak" in which you expect
1261 //   every single malloc() to have a corresponding free(), even for objects
1262 //   which live until program exit.
1263 // * You are writing a dynamically-loaded library which needs to clean up
1264 //   after itself when the library is unloaded.
1265 //
1266 // It is safe to call this multiple times.  However, it is not safe to use
1267 // any other part of the protocol buffers library after
1268 // ShutdownProtobufLibrary() has been called. Furthermore this call is not
1269 // thread safe, user needs to synchronize multiple calls.
1270 PROTOBUF_EXPORT void ShutdownProtobufLibrary();
1271 
1272 namespace internal {
1273 
1274 // Register a function to be called when ShutdownProtocolBuffers() is called.
1275 PROTOBUF_EXPORT void OnShutdown(void (*func)());
1276 // Run an arbitrary function on an arg
1277 PROTOBUF_EXPORT void OnShutdownRun(void (*f)(const void*), const void* arg);
1278 
1279 template <typename T>
1280 T* OnShutdownDelete(T* p) {
1281   OnShutdownRun([](const void* pp) { delete static_cast<const T*>(pp); }, p);
1282   return p;
1283 }
1284 
1285 template <typename MessageLite>
1286 PROTOBUF_ALWAYS_INLINE MessageLite* MessageCreator::PlacementNew(
1287     const MessageLite* prototype_for_func,
1288     const MessageLite* prototype_for_copy, void* mem, Arena* arena) const {
1289   ABSL_DCHECK_EQ(reinterpret_cast<uintptr_t>(mem) % alignment_, 0u);
1290   const Tag as_tag = tag();
1291   static_assert(kFunc < 0 && !(kZeroInit < 0) && !(kMemcpy < 0),
1292                 "Only kFunc must be the only negative value");
1293   if (ABSL_PREDICT_FALSE(static_cast<int8_t>(as_tag) < 0)) {
1294     PROTOBUF_DEBUG_COUNTER("MessageCreator.Func").Inc();
1295     return static_cast<MessageLite*>(func_(prototype_for_func, mem, arena));
1296   }
1297 
1298   char* dst = static_cast<char*>(mem);
1299   const size_t size = allocation_size_;
1300   const char* src = reinterpret_cast<const char*>(prototype_for_copy);
1301 
1302   // These are a bit more efficient than calling normal memset/memcpy because:
1303   //  - We know the minimum size is 16. We have a fallback for when it is not.
1304   //  - We can "underflow" the buffer because those are the MessageLite bytes
1305   //    we will set later.
1306   if (as_tag == kZeroInit) {
1307     // Make sure the input is really all zeros.
1308     ABSL_DCHECK(std::all_of(src + sizeof(MessageLite), src + size,
1309                             [](auto c) { return c == 0; }));
1310 
1311     if (sizeof(MessageLite) != 16) {
1312       memset(dst, 0, size);
1313     } else if (size <= 32) {
1314       memset(dst + size - 16, 0, 16);
1315     } else if (size <= 64) {
1316       memset(dst + 16, 0, 16);
1317       memset(dst + size - 32, 0, 32);
1318     } else {
1319       for (size_t offset = 16; offset + 64 < size; offset += 64) {
1320         absl::PrefetchToLocalCacheForWrite(dst + offset + 64);
1321         memset(dst + offset, 0, 64);
1322       }
1323       memset(dst + size - 64, 0, 64);
1324     }
1325   } else {
1326     ABSL_DCHECK_EQ(+as_tag, +kMemcpy);
1327 
1328     if (sizeof(MessageLite) != 16) {
1329       memcpy(dst, src, size);
1330     } else if (size <= 32) {
1331       memcpy(dst + size - 16, src + size - 16, 16);
1332     } else if (size <= 64) {
1333       memcpy(dst + 16, src + 16, 16);
1334       memcpy(dst + size - 32, src + size - 32, 32);
1335     } else {
1336       for (size_t offset = 16; offset + 64 < size; offset += 64) {
1337         absl::PrefetchToLocalCache(src + offset + 64);
1338         absl::PrefetchToLocalCacheForWrite(dst + offset + 64);
1339         memcpy(dst + offset, src + offset, 64);
1340       }
1341       memcpy(dst + size - 64, src + size - 64, 64);
1342     }
1343   }
1344 
1345   if (arena_bits() != 0) {
1346     if (as_tag == kZeroInit) {
1347       PROTOBUF_DEBUG_COUNTER("MessageCreator.ZeroArena").Inc();
1348     } else {
1349       PROTOBUF_DEBUG_COUNTER("MessageCreator.McpyArena").Inc();
1350     }
1351   } else {
1352     if (as_tag == kZeroInit) {
1353       PROTOBUF_DEBUG_COUNTER("MessageCreator.Zero").Inc();
1354     } else {
1355       PROTOBUF_DEBUG_COUNTER("MessageCreator.Mcpy").Inc();
1356     }
1357   }
1358 
1359   if (internal::PerformDebugChecks() || arena != nullptr) {
1360     if (uintptr_t offsets = arena_bits()) {
1361       do {
1362         const size_t offset = absl::countr_zero(offsets) * sizeof(Arena*);
1363         ABSL_DCHECK_LE(offset + sizeof(Arena*), size);
1364         // Verify we are overwriting a null pointer. If we are not, there is a
1365         // bug somewhere.
1366         ABSL_DCHECK_EQ(*reinterpret_cast<Arena**>(dst + offset), nullptr);
1367         memcpy(dst + offset, &arena, sizeof(arena));
1368         offsets &= offsets - 1;
1369       } while (offsets != 0);
1370     }
1371   }
1372 
1373   // The second memcpy overwrites part of the first, but the compiler should
1374   // avoid the double-write. It's easier than trying to avoid the overlap.
1375   memcpy(dst, static_cast<const void*>(prototype_for_copy),
1376          sizeof(MessageLite));
1377   memcpy(dst + PROTOBUF_FIELD_OFFSET(MessageLite, _internal_metadata_), &arena,
1378          sizeof(arena));
1379   return Launder(reinterpret_cast<MessageLite*>(mem));
1380 }
1381 
1382 template <typename MessageLite>
1383 PROTOBUF_ALWAYS_INLINE MessageLite* MessageCreator::New(
1384     const MessageLite* prototype_for_func,
1385     const MessageLite* prototype_for_copy, Arena* arena) const {
1386   return PlacementNew(prototype_for_func, prototype_for_copy,
1387                       arena != nullptr
1388                           ? arena->AllocateAligned(allocation_size_)
1389                           : ::operator new(allocation_size_),
1390                       arena);
1391 }
1392 
1393 }  // namespace internal
1394 
1395 std::string ShortFormat(const MessageLite& message_lite);
1396 std::string Utf8Format(const MessageLite& message_lite);
1397 
1398 // Cast functions for message pointer/references.
1399 // This is the supported API to cast from a Message/MessageLite to derived
1400 // types. These work even when RTTI is disabled on message types.
1401 //
1402 // The template parameter is simplified and the return type is inferred from the
1403 // input. Eg just `DynamicCastMessage<Foo>(x)` instead of
1404 // `DynamicCastMessage<const Foo*>(x)`.
1405 //
1406 // `DynamicCastMessage` is similar to `dynamic_cast`, returns `nullptr` when the
1407 // input is not an instance of `T`. The overloads that take a reference will
1408 // throw std::bad_cast on mismatch, or terminate if compiled without exceptions.
1409 //
1410 // `DownCastMessage` is a lightweight function for downcasting base
1411 // `MessageLite` pointer to derived type, where it only does type checking if
1412 // !NDEBUG. It should only be used when the caller is certain that the input
1413 // message is of instance `T`.
1414 template <typename T>
1415 const T* DynamicCastMessage(const MessageLite* from) {
1416   static_assert(std::is_base_of<MessageLite, T>::value, "");
1417 
1418   // We might avoid the call to T::GetClassData() altogether if T were to
1419   // expose the class data pointer.
1420   if (from == nullptr || TypeId::Get<T>() != TypeId::Get(*from)) {
1421     return nullptr;
1422   }
1423 
1424   return static_cast<const T*>(from);
1425 }
1426 
1427 template <typename T>
1428 T* DynamicCastMessage(MessageLite* from) {
1429   return const_cast<T*>(
1430       DynamicCastMessage<T>(static_cast<const MessageLite*>(from)));
1431 }
1432 
1433 namespace internal {
1434 [[noreturn]] PROTOBUF_EXPORT void FailDynamicCast(const MessageLite& from,
1435                                                   const MessageLite& to);
1436 }  // namespace internal
1437 
1438 template <typename T>
1439 const T& DynamicCastMessage(const MessageLite& from) {
1440   const T* destination_message = DynamicCastMessage<T>(&from);
1441   if (ABSL_PREDICT_FALSE(destination_message == nullptr)) {
1442     // If exceptions are enabled, throw.
1443     // Otherwise, log a fatal error.
1444 #if defined(ABSL_HAVE_EXCEPTIONS)
1445     throw std::bad_cast();
1446 #endif
1447     // Move the logging into an out-of-line function to reduce bloat in the
1448     // caller.
1449     internal::FailDynamicCast(from, T::default_instance());
1450   }
1451   return *destination_message;
1452 }
1453 
1454 template <typename T>
1455 T& DynamicCastMessage(MessageLite& from) {
1456   return const_cast<T&>(
1457       DynamicCastMessage<T>(static_cast<const MessageLite&>(from)));
1458 }
1459 
1460 template <typename T>
1461 const T* DownCastMessage(const MessageLite* from) {
1462   internal::StrongReferenceToType<T>();
1463   ABSL_DCHECK(DynamicCastMessage<T>(from) == from)
1464       << "Cannot downcast " << from->GetTypeName() << " to "
1465       << T::default_instance().GetTypeName();
1466   return static_cast<const T*>(from);
1467 }
1468 
1469 template <typename T>
1470 T* DownCastMessage(MessageLite* from) {
1471   return const_cast<T*>(
1472       DownCastMessage<T>(static_cast<const MessageLite*>(from)));
1473 }
1474 
1475 template <typename T>
1476 const T& DownCastMessage(const MessageLite& from) {
1477   return *DownCastMessage<T>(&from);
1478 }
1479 
1480 template <typename T>
1481 T& DownCastMessage(MessageLite& from) {
1482   return *DownCastMessage<T>(&from);
1483 }
1484 
1485 template <>
1486 inline const MessageLite* DynamicCastMessage(const MessageLite* from) {
1487   return from;
1488 }
1489 template <>
1490 inline const MessageLite* DownCastMessage(const MessageLite* from) {
1491   return from;
1492 }
1493 
1494 // Deprecated names for the cast functions.
1495 // Prefer the ones above.
1496 template <typename T>
1497 PROTOBUF_DEPRECATE_AND_INLINE()
1498 const T* DynamicCastToGenerated(const MessageLite* from) {
1499   return DynamicCastMessage<T>(from);
1500 }
1501 
1502 template <typename T>
1503 PROTOBUF_DEPRECATE_AND_INLINE()
1504 T* DynamicCastToGenerated(MessageLite* from) {
1505   return DynamicCastMessage<T>(from);
1506 }
1507 
1508 template <typename T>
1509 PROTOBUF_DEPRECATE_AND_INLINE()
1510 const T& DynamicCastToGenerated(const MessageLite& from) {
1511   return DynamicCastMessage<T>(from);
1512 }
1513 
1514 template <typename T>
1515 PROTOBUF_DEPRECATE_AND_INLINE()
1516 T& DynamicCastToGenerated(MessageLite& from) {
1517   return DynamicCastMessage<T>(from);
1518 }
1519 
1520 template <typename T>
1521 PROTOBUF_DEPRECATE_AND_INLINE()
1522 const T* DownCastToGenerated(const MessageLite* from) {
1523   return DownCastMessage<T>(from);
1524 }
1525 
1526 template <typename T>
1527 PROTOBUF_DEPRECATE_AND_INLINE()
1528 T* DownCastToGenerated(MessageLite* from) {
1529   return DownCastMessage<T>(from);
1530 }
1531 
1532 template <typename T>
1533 PROTOBUF_DEPRECATE_AND_INLINE()
1534 const T& DownCastToGenerated(const MessageLite& from) {
1535   return DownCastMessage<T>(from);
1536 }
1537 
1538 template <typename T>
1539 PROTOBUF_DEPRECATE_AND_INLINE()
1540 T& DownCastToGenerated(MessageLite& from) {
1541   return DownCastMessage<T>(from);
1542 }
1543 
1544 // Overloads for `std::shared_ptr` to substitute `std::dynamic_pointer_cast`
1545 template <typename T>
1546 std::shared_ptr<T> DynamicCastMessage(std::shared_ptr<MessageLite> ptr) {
1547   if (auto* res = DynamicCastMessage<T>(ptr.get())) {
1548     // Use aliasing constructor to keep the same control block.
1549     return std::shared_ptr<T>(std::move(ptr), res);
1550   } else {
1551     return nullptr;
1552   }
1553 }
1554 
1555 template <typename T>
1556 std::shared_ptr<const T> DynamicCastMessage(
1557     std::shared_ptr<const MessageLite> ptr) {
1558   if (auto* res = DynamicCastMessage<T>(ptr.get())) {
1559     // Use aliasing constructor to keep the same control block.
1560     return std::shared_ptr<const T>(std::move(ptr), res);
1561   } else {
1562     return nullptr;
1563   }
1564 }
1565 
1566 }  // namespace protobuf
1567 }  // namespace google
1568 
1569 #include "google/protobuf/port_undef.inc"
1570 
1571 #endif  // GOOGLE_PROTOBUF_MESSAGE_LITE_H__