Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-07-19 08:18:32

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 // Author: kenton@google.com (Kenton Varda)
0009 //  Based on original Protocol Buffers design by
0010 //  Sanjay Ghemawat, Jeff Dean, and others.
0011 //
0012 // This file contains the CodedInputStream and CodedOutputStream classes,
0013 // which wrap a ZeroCopyInputStream or ZeroCopyOutputStream, respectively,
0014 // and allow you to read or write individual pieces of data in various
0015 // formats.  In particular, these implement the varint encoding for
0016 // integers, a simple variable-length encoding in which smaller numbers
0017 // take fewer bytes.
0018 //
0019 // Typically these classes will only be used internally by the protocol
0020 // buffer library in order to encode and decode protocol buffers.  Clients
0021 // of the library only need to know about this class if they wish to write
0022 // custom message parsing or serialization procedures.
0023 //
0024 // CodedOutputStream example:
0025 //   // Write some data to "myfile".  First we write a 4-byte "magic number"
0026 //   // to identify the file type, then write a length-prefixed string.  The
0027 //   // string is composed of a varint giving the length followed by the raw
0028 //   // bytes.
0029 //   int fd = open("myfile", O_CREAT | O_WRONLY);
0030 //   ZeroCopyOutputStream* raw_output = new FileOutputStream(fd);
0031 //   CodedOutputStream* coded_output = new CodedOutputStream(raw_output);
0032 //
0033 //   int magic_number = 1234;
0034 //   char text[] = "Hello world!";
0035 //   coded_output->WriteLittleEndian32(magic_number);
0036 //   coded_output->WriteVarint32(strlen(text));
0037 //   coded_output->WriteRaw(text, strlen(text));
0038 //
0039 //   delete coded_output;
0040 //   delete raw_output;
0041 //   close(fd);
0042 //
0043 // CodedInputStream example:
0044 //   // Read a file created by the above code.
0045 //   int fd = open("myfile", O_RDONLY);
0046 //   ZeroCopyInputStream* raw_input = new FileInputStream(fd);
0047 //   CodedInputStream* coded_input = new CodedInputStream(raw_input);
0048 //
0049 //   coded_input->ReadLittleEndian32(&magic_number);
0050 //   if (magic_number != 1234) {
0051 //     cerr << "File not in expected format." << endl;
0052 //     return;
0053 //   }
0054 //
0055 //   uint32_t size;
0056 //   coded_input->ReadVarint32(&size);
0057 //
0058 //   char* text = new char[size + 1];
0059 //   coded_input->ReadRaw(buffer, size);
0060 //   text[size] = '\0';
0061 //
0062 //   delete coded_input;
0063 //   delete raw_input;
0064 //   close(fd);
0065 //
0066 //   cout << "Text is: " << text << endl;
0067 //   delete [] text;
0068 //
0069 // For those who are interested, varint encoding is defined as follows:
0070 //
0071 // The encoding operates on unsigned integers of up to 64 bits in length.
0072 // Each byte of the encoded value has the format:
0073 // * bits 0-6: Seven bits of the number being encoded.
0074 // * bit 7: Zero if this is the last byte in the encoding (in which
0075 //   case all remaining bits of the number are zero) or 1 if
0076 //   more bytes follow.
0077 // The first byte contains the least-significant 7 bits of the number, the
0078 // second byte (if present) contains the next-least-significant 7 bits,
0079 // and so on.  So, the binary number 1011000101011 would be encoded in two
0080 // bytes as "10101011 00101100".
0081 //
0082 // In theory, varint could be used to encode integers of any length.
0083 // However, for practicality we set a limit at 64 bits.  The maximum encoded
0084 // length of a number is thus 10 bytes.
0085 
0086 #ifndef GOOGLE_PROTOBUF_IO_CODED_STREAM_H__
0087 #define GOOGLE_PROTOBUF_IO_CODED_STREAM_H__
0088 
0089 #include <assert.h>
0090 
0091 #include <atomic>
0092 #include <climits>
0093 #include <cstddef>
0094 #include <cstdint>
0095 #include <cstring>
0096 #include <limits>
0097 #include <string>
0098 #include <type_traits>
0099 #include <utility>
0100 
0101 #include "absl/base/optimization.h"
0102 
0103 #if defined(_MSC_VER) && _MSC_VER >= 1300 && !defined(__INTEL_COMPILER)
0104 // If MSVC has "/RTCc" set, it will complain about truncating casts at
0105 // runtime.  This file contains some intentional truncating casts.
0106 #pragma runtime_checks("c", off)
0107 #endif
0108 
0109 #include "absl/log/absl_log.h"  // Replace with vlog_is_on.h after Abseil LTS 20240722
0110 
0111 #include "absl/log/absl_check.h"
0112 #include "absl/numeric/bits.h"
0113 #include "absl/strings/cord.h"
0114 #include "absl/strings/string_view.h"
0115 #include "google/protobuf/endian.h"
0116 
0117 // Must be included last.
0118 #include "google/protobuf/port_def.inc"
0119 
0120 namespace google {
0121 namespace protobuf {
0122 
0123 class DescriptorPool;
0124 class MessageFactory;
0125 class ZeroCopyCodedInputStream;
0126 
0127 namespace internal {
0128 void MapTestForceDeterministic();
0129 class EpsCopyByteStream;
0130 }  // namespace internal
0131 
0132 namespace io {
0133 
0134 // Defined in this file.
0135 class CodedInputStream;
0136 class CodedOutputStream;
0137 
0138 // Defined in other files.
0139 class ZeroCopyInputStream;   // zero_copy_stream.h
0140 class ZeroCopyOutputStream;  // zero_copy_stream.h
0141 
0142 // Class which reads and decodes binary data which is composed of varint-
0143 // encoded integers and fixed-width pieces.  Wraps a ZeroCopyInputStream.
0144 // Most users will not need to deal with CodedInputStream.
0145 //
0146 // Most methods of CodedInputStream that return a bool return false if an
0147 // underlying I/O error occurs or if the data is malformed.  Once such a
0148 // failure occurs, the CodedInputStream is broken and is no longer useful.
0149 // After a failure, callers also should assume writes to "out" args may have
0150 // occurred, though nothing useful can be determined from those writes.
0151 class PROTOBUF_EXPORT CodedInputStream {
0152  public:
0153   // Create a CodedInputStream that reads from the given ZeroCopyInputStream.
0154   explicit CodedInputStream(ZeroCopyInputStream* input);
0155 
0156   // Create a CodedInputStream that reads from the given flat array.  This is
0157   // faster than using an ArrayInputStream.  PushLimit(size) is implied by
0158   // this constructor.
0159   explicit CodedInputStream(const uint8_t* buffer, int size);
0160   CodedInputStream(const CodedInputStream&) = delete;
0161   CodedInputStream& operator=(const CodedInputStream&) = delete;
0162 
0163   // Destroy the CodedInputStream and position the underlying
0164   // ZeroCopyInputStream at the first unread byte.  If an error occurred while
0165   // reading (causing a method to return false), then the exact position of
0166   // the input stream may be anywhere between the last value that was read
0167   // successfully and the stream's byte limit.
0168   ~CodedInputStream();
0169 
0170   // Return true if this CodedInputStream reads from a flat array instead of
0171   // a ZeroCopyInputStream.
0172   inline bool IsFlat() const;
0173 
0174   // Skips a number of bytes.  Returns false if an underlying read error
0175   // occurs.
0176   inline bool Skip(int count);
0177 
0178   // Sets *data to point directly at the unread part of the CodedInputStream's
0179   // underlying buffer, and *size to the size of that buffer, but does not
0180   // advance the stream's current position.  This will always either produce
0181   // a non-empty buffer or return false.  If the caller consumes any of
0182   // this data, it should then call Skip() to skip over the consumed bytes.
0183   // This may be useful for implementing external fast parsing routines for
0184   // types of data not covered by the CodedInputStream interface.
0185   bool GetDirectBufferPointer(const void** data, int* size);
0186 
0187   // Like GetDirectBufferPointer, but this method is inlined, and does not
0188   // attempt to Refresh() if the buffer is currently empty.
0189   PROTOBUF_ALWAYS_INLINE
0190   void GetDirectBufferPointerInline(const void** data, int* size);
0191 
0192   // Read raw bytes, copying them into the given buffer.
0193   bool ReadRaw(void* buffer, int size);
0194 
0195   // Like ReadRaw, but reads into a string.
0196   bool ReadString(std::string* buffer, int size);
0197 
0198   // Like ReadString(), but reads to a Cord.
0199   bool ReadCord(absl::Cord* output, int size);
0200 
0201 
0202   // Read a 16-bit little-endian integer.
0203   bool ReadLittleEndian16(uint16_t* value);
0204   // Read a 32-bit little-endian integer.
0205   bool ReadLittleEndian32(uint32_t* value);
0206   // Read a 64-bit little-endian integer.
0207   bool ReadLittleEndian64(uint64_t* value);
0208 
0209   // These methods read from an externally provided buffer. The caller is
0210   // responsible for ensuring that the buffer has sufficient space.
0211   // Read a 16-bit little-endian integer.
0212   static const uint8_t* ReadLittleEndian16FromArray(const uint8_t* buffer,
0213                                                     uint16_t* value);
0214   // Read a 32-bit little-endian integer.
0215   static const uint8_t* ReadLittleEndian32FromArray(const uint8_t* buffer,
0216                                                     uint32_t* value);
0217   // Read a 64-bit little-endian integer.
0218   static const uint8_t* ReadLittleEndian64FromArray(const uint8_t* buffer,
0219                                                     uint64_t* value);
0220 
0221   // Read an unsigned integer with Varint encoding, truncating to 32 bits.
0222   // Reading a 32-bit value is equivalent to reading a 64-bit one and casting
0223   // it to uint32_t, but may be more efficient.
0224   bool ReadVarint32(uint32_t* value);
0225   // Read an unsigned integer with Varint encoding.
0226   bool ReadVarint64(uint64_t* value);
0227 
0228   // Reads a varint off the wire into an "int". This should be used for reading
0229   // sizes off the wire (sizes of strings, submessages, bytes fields, etc).
0230   //
0231   // The value from the wire is interpreted as unsigned.  If its value exceeds
0232   // the representable value of an integer on this platform, instead of
0233   // truncating we return false. Truncating (as performed by ReadVarint32()
0234   // above) is an acceptable approach for fields representing an integer, but
0235   // when we are parsing a size from the wire, truncating the value would result
0236   // in us misparsing the payload.
0237   bool ReadVarintSizeAsInt(int* value);
0238 
0239   // Read a tag.  This calls ReadVarint32() and returns the result, or returns
0240   // zero (which is not a valid tag) if ReadVarint32() fails.  Also, ReadTag
0241   // (but not ReadTagNoLastTag) updates the last tag value, which can be checked
0242   // with LastTagWas().
0243   //
0244   // Always inline because this is only called in one place per parse loop
0245   // but it is called for every iteration of said loop, so it should be fast.
0246   // GCC doesn't want to inline this by default.
0247   PROTOBUF_ALWAYS_INLINE uint32_t ReadTag() {
0248     return last_tag_ = ReadTagNoLastTag();
0249   }
0250 
0251   PROTOBUF_ALWAYS_INLINE uint32_t ReadTagNoLastTag();
0252 
0253   // This usually a faster alternative to ReadTag() when cutoff is a manifest
0254   // constant.  It does particularly well for cutoff >= 127.  The first part
0255   // of the return value is the tag that was read, though it can also be 0 in
0256   // the cases where ReadTag() would return 0.  If the second part is true
0257   // then the tag is known to be in [0, cutoff].  If not, the tag either is
0258   // above cutoff or is 0.  (There's intentional wiggle room when tag is 0,
0259   // because that can arise in several ways, and for best performance we want
0260   // to avoid an extra "is tag == 0?" check here.)
0261   PROTOBUF_ALWAYS_INLINE
0262   std::pair<uint32_t, bool> ReadTagWithCutoff(uint32_t cutoff) {
0263     std::pair<uint32_t, bool> result = ReadTagWithCutoffNoLastTag(cutoff);
0264     last_tag_ = result.first;
0265     return result;
0266   }
0267 
0268   PROTOBUF_ALWAYS_INLINE
0269   std::pair<uint32_t, bool> ReadTagWithCutoffNoLastTag(uint32_t cutoff);
0270 
0271   // Usually returns true if calling ReadVarint32() now would produce the given
0272   // value.  Will always return false if ReadVarint32() would not return the
0273   // given value.  If ExpectTag() returns true, it also advances past
0274   // the varint.  For best performance, use a compile-time constant as the
0275   // parameter.
0276   // Always inline because this collapses to a small number of instructions
0277   // when given a constant parameter, but GCC doesn't want to inline by default.
0278   PROTOBUF_ALWAYS_INLINE bool ExpectTag(uint32_t expected);
0279 
0280   // Like above, except this reads from the specified buffer. The caller is
0281   // responsible for ensuring that the buffer is large enough to read a varint
0282   // of the expected size. For best performance, use a compile-time constant as
0283   // the expected tag parameter.
0284   //
0285   // Returns a pointer beyond the expected tag if it was found, or NULL if it
0286   // was not.
0287   PROTOBUF_ALWAYS_INLINE
0288   static const uint8_t* ExpectTagFromArray(const uint8_t* buffer,
0289                                            uint32_t expected);
0290 
0291   // Usually returns true if no more bytes can be read.  Always returns false
0292   // if more bytes can be read.  If ExpectAtEnd() returns true, a subsequent
0293   // call to LastTagWas() will act as if ReadTag() had been called and returned
0294   // zero, and ConsumedEntireMessage() will return true.
0295   bool ExpectAtEnd();
0296 
0297   // If the last call to ReadTag() or ReadTagWithCutoff() returned the given
0298   // value, returns true.  Otherwise, returns false.
0299   // ReadTagNoLastTag/ReadTagWithCutoffNoLastTag do not preserve the last
0300   // returned value.
0301   //
0302   // This is needed because parsers for some types of embedded messages
0303   // (with field type TYPE_GROUP) don't actually know that they've reached the
0304   // end of a message until they see an ENDGROUP tag, which was actually part
0305   // of the enclosing message.  The enclosing message would like to check that
0306   // tag to make sure it had the right number, so it calls LastTagWas() on
0307   // return from the embedded parser to check.
0308   bool LastTagWas(uint32_t expected);
0309   void SetLastTag(uint32_t tag) { last_tag_ = tag; }
0310 
0311   // When parsing message (but NOT a group), this method must be called
0312   // immediately after MergeFromCodedStream() returns (if it returns true)
0313   // to further verify that the message ended in a legitimate way.  For
0314   // example, this verifies that parsing did not end on an end-group tag.
0315   // It also checks for some cases where, due to optimizations,
0316   // MergeFromCodedStream() can incorrectly return true.
0317   bool ConsumedEntireMessage();
0318   void SetConsumed() { legitimate_message_end_ = true; }
0319 
0320   // Limits ----------------------------------------------------------
0321   // Limits are used when parsing length-prefixed embedded messages.
0322   // After the message's length is read, PushLimit() is used to prevent
0323   // the CodedInputStream from reading beyond that length.  Once the
0324   // embedded message has been parsed, PopLimit() is called to undo the
0325   // limit.
0326 
0327   // Opaque type used with PushLimit() and PopLimit().  Do not modify
0328   // values of this type yourself.  The only reason that this isn't a
0329   // struct with private internals is for efficiency.
0330   typedef int Limit;
0331 
0332   // Places a limit on the number of bytes that the stream may read,
0333   // starting from the current position.  Once the stream hits this limit,
0334   // it will act like the end of the input has been reached until PopLimit()
0335   // is called.
0336   //
0337   // As the names imply, the stream conceptually has a stack of limits.  The
0338   // shortest limit on the stack is always enforced, even if it is not the
0339   // top limit.
0340   //
0341   // The value returned by PushLimit() is opaque to the caller, and must
0342   // be passed unchanged to the corresponding call to PopLimit().
0343   Limit PushLimit(int byte_limit);
0344 
0345   // Pops the last limit pushed by PushLimit().  The input must be the value
0346   // returned by that call to PushLimit().
0347   void PopLimit(Limit limit);
0348 
0349   // Returns the number of bytes left until the nearest limit on the
0350   // stack is hit, or -1 if no limits are in place.
0351   int BytesUntilLimit() const;
0352 
0353   // Returns current position relative to the beginning of the input stream.
0354   int CurrentPosition() const;
0355 
0356   // Total Bytes Limit -----------------------------------------------
0357   // To prevent malicious users from sending excessively large messages
0358   // and causing memory exhaustion, CodedInputStream imposes a hard limit on
0359   // the total number of bytes it will read.
0360 
0361   // Sets the maximum number of bytes that this CodedInputStream will read
0362   // before refusing to continue.  To prevent servers from allocating enormous
0363   // amounts of memory to hold parsed messages, the maximum message length
0364   // should be limited to the shortest length that will not harm usability.
0365   // The default limit is INT_MAX (~2GB) and apps should set shorter limits
0366   // if possible. An error will always be printed to stderr if the limit is
0367   // reached.
0368   //
0369   // Note: setting a limit less than the current read position is interpreted
0370   // as a limit on the current position.
0371   //
0372   // This is unrelated to PushLimit()/PopLimit().
0373   void SetTotalBytesLimit(int total_bytes_limit);
0374 
0375   // The Total Bytes Limit minus the Current Position, or -1 if the total bytes
0376   // limit is INT_MAX.
0377   int BytesUntilTotalBytesLimit() const;
0378 
0379   // Recursion Limit -------------------------------------------------
0380   // To prevent corrupt or malicious messages from causing stack overflows,
0381   // we must keep track of the depth of recursion when parsing embedded
0382   // messages and groups.  CodedInputStream keeps track of this because it
0383   // is the only object that is passed down the stack during parsing.
0384 
0385   // Sets the maximum recursion depth.  The default is 100.
0386   void SetRecursionLimit(int limit);
0387   int RecursionBudget() { return recursion_budget_; }
0388 
0389   static int GetDefaultRecursionLimit() { return default_recursion_limit_; }
0390 
0391   // Increments the current recursion depth.  Returns true if the depth is
0392   // under the limit, false if it has gone over.
0393   bool IncrementRecursionDepth();
0394 
0395   // Decrements the recursion depth if possible.
0396   void DecrementRecursionDepth();
0397 
0398   // Decrements the recursion depth blindly.  This is faster than
0399   // DecrementRecursionDepth().  It should be used only if all previous
0400   // increments to recursion depth were successful.
0401   void UnsafeDecrementRecursionDepth();
0402 
0403   // Shorthand for make_pair(PushLimit(byte_limit), --recursion_budget_).
0404   // Using this can reduce code size and complexity in some cases.  The caller
0405   // is expected to check that the second part of the result is non-negative (to
0406   // bail out if the depth of recursion is too high) and, if all is well, to
0407   // later pass the first part of the result to PopLimit() or similar.
0408   std::pair<CodedInputStream::Limit, int> IncrementRecursionDepthAndPushLimit(
0409       int byte_limit);
0410 
0411   // Shorthand for PushLimit(ReadVarint32(&length) ? length : 0).
0412   Limit ReadLengthAndPushLimit();
0413 
0414   // Helper that is equivalent to: {
0415   //  bool result = ConsumedEntireMessage();
0416   //  PopLimit(limit);
0417   //  UnsafeDecrementRecursionDepth();
0418   //  return result; }
0419   // Using this can reduce code size and complexity in some cases.
0420   // Do not use unless the current recursion depth is greater than zero.
0421   bool DecrementRecursionDepthAndPopLimit(Limit limit);
0422 
0423   // Helper that is equivalent to: {
0424   //  bool result = ConsumedEntireMessage();
0425   //  PopLimit(limit);
0426   //  return result; }
0427   // Using this can reduce code size and complexity in some cases.
0428   bool CheckEntireMessageConsumedAndPopLimit(Limit limit);
0429 
0430   // Extension Registry ----------------------------------------------
0431   // ADVANCED USAGE:  99.9% of people can ignore this section.
0432   //
0433   // By default, when parsing extensions, the parser looks for extension
0434   // definitions in the pool which owns the outer message's Descriptor.
0435   // However, you may call SetExtensionRegistry() to provide an alternative
0436   // pool instead.  This makes it possible, for example, to parse a message
0437   // using a generated class, but represent some extensions using
0438   // DynamicMessage.
0439 
0440   // Set the pool used to look up extensions.  Most users do not need to call
0441   // this as the correct pool will be chosen automatically.
0442   //
0443   // WARNING:  It is very easy to misuse this.  Carefully read the requirements
0444   //   below.  Do not use this unless you are sure you need it.  Almost no one
0445   //   does.
0446   //
0447   // Let's say you are parsing a message into message object m, and you want
0448   // to take advantage of SetExtensionRegistry().  You must follow these
0449   // requirements:
0450   //
0451   // The given DescriptorPool must contain m->GetDescriptor().  It is not
0452   // sufficient for it to simply contain a descriptor that has the same name
0453   // and content -- it must be the *exact object*.  In other words:
0454   //   assert(pool->FindMessageTypeByName(m->GetDescriptor()->full_name()) ==
0455   //          m->GetDescriptor());
0456   // There are two ways to satisfy this requirement:
0457   // 1) Use m->GetDescriptor()->pool() as the pool.  This is generally useless
0458   //    because this is the pool that would be used anyway if you didn't call
0459   //    SetExtensionRegistry() at all.
0460   // 2) Use a DescriptorPool which has m->GetDescriptor()->pool() as an
0461   //    "underlay".  Read the documentation for DescriptorPool for more
0462   //    information about underlays.
0463   //
0464   // You must also provide a MessageFactory.  This factory will be used to
0465   // construct Message objects representing extensions.  The factory's
0466   // GetPrototype() MUST return non-NULL for any Descriptor which can be found
0467   // through the provided pool.
0468   //
0469   // If the provided factory might return instances of protocol-compiler-
0470   // generated (i.e. compiled-in) types, or if the outer message object m is
0471   // a generated type, then the given factory MUST have this property:  If
0472   // GetPrototype() is given a Descriptor which resides in
0473   // DescriptorPool::generated_pool(), the factory MUST return the same
0474   // prototype which MessageFactory::generated_factory() would return.  That
0475   // is, given a descriptor for a generated type, the factory must return an
0476   // instance of the generated class (NOT DynamicMessage).  However, when
0477   // given a descriptor for a type that is NOT in generated_pool, the factory
0478   // is free to return any implementation.
0479   //
0480   // The reason for this requirement is that generated sub-objects may be
0481   // accessed via the standard (non-reflection) extension accessor methods,
0482   // and these methods will down-cast the object to the generated class type.
0483   // If the object is not actually of that type, the results would be undefined.
0484   // On the other hand, if an extension is not compiled in, then there is no
0485   // way the code could end up accessing it via the standard accessors -- the
0486   // only way to access the extension is via reflection.  When using reflection,
0487   // DynamicMessage and generated messages are indistinguishable, so it's fine
0488   // if these objects are represented using DynamicMessage.
0489   //
0490   // Using DynamicMessageFactory on which you have called
0491   // SetDelegateToGeneratedFactory(true) should be sufficient to satisfy the
0492   // above requirement.
0493   //
0494   // If either pool or factory is NULL, both must be NULL.
0495   //
0496   // Note that this feature is ignored when parsing "lite" messages as they do
0497   // not have descriptors.
0498   void SetExtensionRegistry(const DescriptorPool* pool,
0499                             MessageFactory* factory);
0500 
0501   // Get the DescriptorPool set via SetExtensionRegistry(), or NULL if no pool
0502   // has been provided.
0503   const DescriptorPool* GetExtensionPool();
0504 
0505   // Get the MessageFactory set via SetExtensionRegistry(), or NULL if no
0506   // factory has been provided.
0507   MessageFactory* GetExtensionFactory();
0508 
0509  private:
0510   const uint8_t* buffer_;
0511   const uint8_t* buffer_end_;  // pointer to the end of the buffer.
0512   ZeroCopyInputStream* input_;
0513   int total_bytes_read_;  // total bytes read from input_, including
0514                           // the current buffer
0515 
0516   // If total_bytes_read_ surpasses INT_MAX, we record the extra bytes here
0517   // so that we can BackUp() on destruction.
0518   int overflow_bytes_;
0519 
0520   // LastTagWas() stuff.
0521   uint32_t last_tag_;  // result of last ReadTag() or ReadTagWithCutoff().
0522 
0523   // This is set true by ReadTag{Fallback/Slow}() if it is called when exactly
0524   // at EOF, or by ExpectAtEnd() when it returns true.  This happens when we
0525   // reach the end of a message and attempt to read another tag.
0526   bool legitimate_message_end_;
0527 
0528   // See EnableAliasing().
0529   bool aliasing_enabled_;
0530 
0531   // If true, set eager parsing mode to override lazy fields.
0532   bool force_eager_parsing_;
0533 
0534   // Limits
0535   Limit current_limit_;  // if position = -1, no limit is applied
0536 
0537   // For simplicity, if the current buffer crosses a limit (either a normal
0538   // limit created by PushLimit() or the total bytes limit), buffer_size_
0539   // only tracks the number of bytes before that limit.  This field
0540   // contains the number of bytes after it.  Note that this implies that if
0541   // buffer_size_ == 0 and buffer_size_after_limit_ > 0, we know we've
0542   // hit a limit.  However, if both are zero, it doesn't necessarily mean
0543   // we aren't at a limit -- the buffer may have ended exactly at the limit.
0544   int buffer_size_after_limit_;
0545 
0546   // Maximum number of bytes to read, period.  This is unrelated to
0547   // current_limit_.  Set using SetTotalBytesLimit().
0548   int total_bytes_limit_;
0549 
0550   // Current recursion budget, controlled by IncrementRecursionDepth() and
0551   // similar.  Starts at recursion_limit_ and goes down: if this reaches
0552   // -1 we are over budget.
0553   int recursion_budget_;
0554   // Recursion depth limit, set by SetRecursionLimit().
0555   int recursion_limit_;
0556 
0557   // See SetExtensionRegistry().
0558   const DescriptorPool* extension_pool_;
0559   MessageFactory* extension_factory_;
0560 
0561   // Private member functions.
0562 
0563   // Fallback when Skip() goes past the end of the current buffer.
0564   bool SkipFallback(int count, int original_buffer_size);
0565 
0566   // Advance the buffer by a given number of bytes.
0567   void Advance(int amount);
0568 
0569   // Back up input_ to the current buffer position.
0570   void BackUpInputToCurrentPosition();
0571 
0572   // Recomputes the value of buffer_size_after_limit_.  Must be called after
0573   // current_limit_ or total_bytes_limit_ changes.
0574   void RecomputeBufferLimits();
0575 
0576   // Writes an error message saying that we hit total_bytes_limit_.
0577   void PrintTotalBytesLimitError();
0578 
0579   // Called when the buffer runs out to request more data.  Implies an
0580   // Advance(BufferSize()).
0581   bool Refresh();
0582 
0583   // When parsing varints, we optimize for the common case of small values, and
0584   // then optimize for the case when the varint fits within the current buffer
0585   // piece. The Fallback method is used when we can't use the one-byte
0586   // optimization. The Slow method is yet another fallback when the buffer is
0587   // not large enough. Making the slow path out-of-line speeds up the common
0588   // case by 10-15%. The slow path is fairly uncommon: it only triggers when a
0589   // message crosses multiple buffers.  Note: ReadVarint32Fallback() and
0590   // ReadVarint64Fallback() are called frequently and generally not inlined, so
0591   // they have been optimized to avoid "out" parameters.  The former returns -1
0592   // if it fails and the uint32_t it read otherwise.  The latter has a bool
0593   // indicating success or failure as part of its return type.
0594   int64_t ReadVarint32Fallback(uint32_t first_byte_or_zero);
0595   int ReadVarintSizeAsIntFallback();
0596   std::pair<uint64_t, bool> ReadVarint64Fallback();
0597   bool ReadVarint32Slow(uint32_t* value);
0598   bool ReadVarint64Slow(uint64_t* value);
0599   int ReadVarintSizeAsIntSlow();
0600   bool ReadLittleEndian16Fallback(uint16_t* value);
0601   bool ReadLittleEndian32Fallback(uint32_t* value);
0602   bool ReadLittleEndian64Fallback(uint64_t* value);
0603 
0604   // Fallback/slow methods for reading tags. These do not update last_tag_,
0605   // but will set legitimate_message_end_ if we are at the end of the input
0606   // stream.
0607   uint32_t ReadTagFallback(uint32_t first_byte_or_zero);
0608   uint32_t ReadTagSlow();
0609   bool ReadStringFallback(std::string* buffer, int size);
0610 
0611   // Return the size of the buffer.
0612   int BufferSize() const;
0613 
0614   static const int kDefaultTotalBytesLimit = INT_MAX;
0615 
0616   static int default_recursion_limit_;  // 100 by default.
0617 
0618   friend class google::protobuf::ZeroCopyCodedInputStream;
0619   friend class google::protobuf::internal::EpsCopyByteStream;
0620 };
0621 
0622 // EpsCopyOutputStream wraps a ZeroCopyOutputStream and exposes a new stream,
0623 // which has the property you can write kSlopBytes (16 bytes) from the current
0624 // position without bounds checks. The cursor into the stream is managed by
0625 // the user of the class and is an explicit parameter in the methods. Careful
0626 // use of this class, ie. keep ptr a local variable, eliminates the need to
0627 // for the compiler to sync the ptr value between register and memory.
0628 class PROTOBUF_EXPORT EpsCopyOutputStream {
0629  public:
0630   enum { kSlopBytes = 16 };
0631 
0632   // Initialize from a stream.
0633   EpsCopyOutputStream(ZeroCopyOutputStream* stream, bool deterministic,
0634                       uint8_t** pp)
0635       : end_(buffer_),
0636         stream_(stream),
0637         is_serialization_deterministic_(deterministic) {
0638     *pp = buffer_;
0639   }
0640 
0641   // Only for array serialization. No overflow protection, end_ will be the
0642   // pointed to the end of the array. When using this the total size is already
0643   // known, so no need to maintain the slop region.
0644   EpsCopyOutputStream(void* data, int size, bool deterministic)
0645       : end_(static_cast<uint8_t*>(data) + size),
0646         buffer_end_(nullptr),
0647         stream_(nullptr),
0648         is_serialization_deterministic_(deterministic) {}
0649 
0650   // Initialize from stream but with the first buffer already given (eager).
0651   EpsCopyOutputStream(void* data, int size, ZeroCopyOutputStream* stream,
0652                       bool deterministic, uint8_t** pp)
0653       : stream_(stream), is_serialization_deterministic_(deterministic) {
0654     *pp = SetInitialBuffer(data, size);
0655   }
0656 
0657   // Flush everything that's written into the underlying ZeroCopyOutputStream
0658   // and trims the underlying stream to the location of ptr.
0659   uint8_t* Trim(uint8_t* ptr);
0660 
0661   // After this it's guaranteed you can safely write kSlopBytes to ptr. This
0662   // will never fail! The underlying stream can produce an error. Use HadError
0663   // to check for errors.
0664   [[nodiscard]] uint8_t* EnsureSpace(uint8_t* ptr) {
0665     if (ABSL_PREDICT_FALSE(ptr >= end_)) {
0666       return EnsureSpaceFallback(ptr);
0667     }
0668     return ptr;
0669   }
0670 
0671   uint8_t* WriteRaw(const void* data, int size, uint8_t* ptr) {
0672     if (ABSL_PREDICT_FALSE(end_ - ptr < size)) {
0673       return WriteRawFallback(data, size, ptr);
0674     }
0675     std::memcpy(ptr, data, static_cast<unsigned int>(size));
0676     return ptr + size;
0677   }
0678   // Writes the buffer specified by data, size to the stream. Possibly by
0679   // aliasing the buffer (ie. not copying the data). The caller is responsible
0680   // to make sure the buffer is alive for the duration of the
0681   // ZeroCopyOutputStream.
0682 #ifndef NDEBUG
0683   PROTOBUF_NOINLINE
0684 #endif
0685   uint8_t* WriteRawMaybeAliased(const void* data, int size, uint8_t* ptr) {
0686     if (aliasing_enabled_) {
0687       return WriteAliasedRaw(data, size, ptr);
0688     } else {
0689       return WriteRaw(data, size, ptr);
0690     }
0691   }
0692 
0693   uint8_t* WriteCord(const absl::Cord& cord, uint8_t* ptr);
0694 
0695 #ifndef NDEBUG
0696   PROTOBUF_NOINLINE
0697 #endif
0698   uint8_t* WriteStringMaybeAliased(uint32_t num, absl::string_view s,
0699                                    uint8_t* ptr) {
0700     std::ptrdiff_t size = s.size();
0701     if (ABSL_PREDICT_FALSE(size >= 128 ||
0702                            end_ - ptr + 16 - TagSize(num << 3) - 1 < size)) {
0703       return WriteStringMaybeAliasedOutline(num, s, ptr);
0704     }
0705     ptr = UnsafeVarint((num << 3) | 2, ptr);
0706     *ptr++ = static_cast<uint8_t>(size);
0707     std::memcpy(ptr, s.data(), size);
0708     return ptr + size;
0709   }
0710   uint8_t* WriteBytesMaybeAliased(uint32_t num, absl::string_view s,
0711                                   uint8_t* ptr) {
0712     return WriteStringMaybeAliased(num, s, ptr);
0713   }
0714 
0715   template <typename T>
0716   PROTOBUF_ALWAYS_INLINE uint8_t* WriteString(uint32_t num, const T& s,
0717                                               uint8_t* ptr) {
0718     std::ptrdiff_t size = s.size();
0719     if (ABSL_PREDICT_FALSE(size >= 128 ||
0720                            end_ - ptr + 16 - TagSize(num << 3) - 1 < size)) {
0721       return WriteStringOutline(num, s, ptr);
0722     }
0723     ptr = UnsafeVarint((num << 3) | 2, ptr);
0724     *ptr++ = static_cast<uint8_t>(size);
0725     std::memcpy(ptr, s.data(), size);
0726     return ptr + size;
0727   }
0728 
0729   uint8_t* WriteString(uint32_t num, const absl::Cord& s, uint8_t* ptr) {
0730     ptr = EnsureSpace(ptr);
0731     ptr = WriteTag(num, 2, ptr);
0732     return WriteCordOutline(s, ptr);
0733   }
0734 
0735   template <typename T>
0736 #ifndef NDEBUG
0737   PROTOBUF_NOINLINE
0738 #endif
0739   uint8_t* WriteBytes(uint32_t num, const T& s, uint8_t* ptr) {
0740     return WriteString(num, s, ptr);
0741   }
0742 
0743   template <typename T>
0744   PROTOBUF_ALWAYS_INLINE uint8_t* WriteInt32Packed(int num, const T& r,
0745                                                    int size, uint8_t* ptr) {
0746     return WriteVarintPacked(num, r, size, ptr, Encode64);
0747   }
0748   template <typename T>
0749   PROTOBUF_ALWAYS_INLINE uint8_t* WriteUInt32Packed(int num, const T& r,
0750                                                     int size, uint8_t* ptr) {
0751     return WriteVarintPacked(num, r, size, ptr, Encode32);
0752   }
0753   template <typename T>
0754   PROTOBUF_ALWAYS_INLINE uint8_t* WriteSInt32Packed(int num, const T& r,
0755                                                     int size, uint8_t* ptr) {
0756     return WriteVarintPacked(num, r, size, ptr, ZigZagEncode32);
0757   }
0758   template <typename T>
0759   PROTOBUF_ALWAYS_INLINE uint8_t* WriteInt64Packed(int num, const T& r,
0760                                                    int size, uint8_t* ptr) {
0761     return WriteVarintPacked(num, r, size, ptr, Encode64);
0762   }
0763   template <typename T>
0764   PROTOBUF_ALWAYS_INLINE uint8_t* WriteUInt64Packed(int num, const T& r,
0765                                                     int size, uint8_t* ptr) {
0766     return WriteVarintPacked(num, r, size, ptr, Encode64);
0767   }
0768   template <typename T>
0769   PROTOBUF_ALWAYS_INLINE uint8_t* WriteSInt64Packed(int num, const T& r,
0770                                                     int size, uint8_t* ptr) {
0771     return WriteVarintPacked(num, r, size, ptr, ZigZagEncode64);
0772   }
0773   template <typename T>
0774   PROTOBUF_ALWAYS_INLINE uint8_t* WriteEnumPacked(int num, const T& r, int size,
0775                                                   uint8_t* ptr) {
0776     return WriteVarintPacked(num, r, size, ptr, Encode64);
0777   }
0778 
0779   template <typename T>
0780   PROTOBUF_ALWAYS_INLINE uint8_t* WriteFixedPacked(int num, const T& r,
0781                                                    uint8_t* ptr) {
0782     ptr = EnsureSpace(ptr);
0783     constexpr auto element_size = sizeof(typename T::value_type);
0784     auto size = r.size() * element_size;
0785     ptr = WriteLengthDelim(num, size, ptr);
0786     return WriteRawLittleEndian<element_size>(r.data(), static_cast<int>(size),
0787                                               ptr);
0788   }
0789 
0790   template <int kElementSize>
0791   PROTOBUF_ALWAYS_INLINE uint8_t* WriteRawNumericArrayLittleEndian(
0792       const void* data, int size, uint8_t* ptr) {
0793     return WriteRawLittleEndian<kElementSize>(data, size, ptr);
0794   }
0795 
0796   // Returns true if there was an underlying I/O error since this object was
0797   // created.
0798   bool HadError() const { return had_error_; }
0799 
0800   // Instructs the EpsCopyOutputStream to allow the underlying
0801   // ZeroCopyOutputStream to hold pointers to the original structure instead of
0802   // copying, if it supports it (i.e. output->AllowsAliasing() is true).  If the
0803   // underlying stream does not support aliasing, then enabling it has no
0804   // affect.  For now, this only affects the behavior of
0805   // WriteRawMaybeAliased().
0806   //
0807   // NOTE: It is caller's responsibility to ensure that the chunk of memory
0808   // remains live until all of the data has been consumed from the stream.
0809   void EnableAliasing(bool enabled);
0810 
0811   // See documentation on CodedOutputStream::SetSerializationDeterministic.
0812   void SetSerializationDeterministic(bool value) {
0813     is_serialization_deterministic_ = value;
0814   }
0815 
0816   // See documentation on CodedOutputStream::IsSerializationDeterministic.
0817   bool IsSerializationDeterministic() const {
0818     return is_serialization_deterministic_;
0819   }
0820 
0821   // The number of bytes written to the stream at position ptr, relative to the
0822   // stream's overall position.
0823   int64_t ByteCount(uint8_t* ptr) const;
0824 
0825 
0826 #ifdef PROTOBUF_INTERNAL_V2_EXPERIMENT
0827   template <typename ValT, typename CallbackT>
0828   uint8_t* WriteNumericArray(uint8_t* ptr, uint32_t count,
0829                              CallbackT&& callback) {
0830     static_assert(sizeof(ValT) > 1, "Use WriteRaw");
0831     static_assert(sizeof(ValT) < kSlopBytes, "");
0832 
0833     int64_t size = count * sizeof(ValT);
0834     while (size > 0) {
0835       ptr = EnsureSpace(ptr);
0836       int64_t chunk_size = std::min<int64_t>(GetSize(ptr), size);
0837       int64_t round_down_size = (chunk_size / sizeof(ValT)) * sizeof(ValT);
0838       ABSL_DCHECK_GT(round_down_size, 0u);
0839 
0840       callback(ptr, round_down_size);
0841 
0842       size -= round_down_size;
0843       ptr += round_down_size;
0844     }
0845     return ptr;
0846   }
0847 #endif  // PROTOBUF_INTERNAL_V2_EXPERIMENT
0848 
0849  private:
0850   uint8_t* end_;
0851   uint8_t* buffer_end_ = buffer_;
0852   uint8_t buffer_[2 * kSlopBytes];
0853   ZeroCopyOutputStream* stream_;
0854   bool had_error_ = false;
0855   bool aliasing_enabled_ = false;  // See EnableAliasing().
0856   bool is_serialization_deterministic_;
0857   bool skip_check_consistency_ = false;
0858 
0859   uint8_t* EnsureSpaceFallback(uint8_t* ptr);
0860   inline uint8_t* Next();
0861   int Flush(uint8_t* ptr);
0862   std::ptrdiff_t GetSize(uint8_t* ptr) const {
0863     ABSL_DCHECK(ptr <= end_ + kSlopBytes);  // NOLINT
0864     return end_ + kSlopBytes - ptr;
0865   }
0866 
0867   uint8_t* Error() {
0868     had_error_ = true;
0869     // We use the patch buffer to always guarantee space to write to.
0870     end_ = buffer_ + kSlopBytes;
0871     return buffer_;
0872   }
0873 
0874   static constexpr int TagSize(uint32_t tag) {
0875     return (tag < (1 << 7))    ? 1
0876            : (tag < (1 << 14)) ? 2
0877            : (tag < (1 << 21)) ? 3
0878            : (tag < (1 << 28)) ? 4
0879                                : 5;
0880   }
0881 
0882   PROTOBUF_ALWAYS_INLINE uint8_t* WriteTag(uint32_t num, uint32_t wt,
0883                                            uint8_t* ptr) {
0884     ABSL_DCHECK(ptr < end_);  // NOLINT
0885     return UnsafeVarint((num << 3) | wt, ptr);
0886   }
0887 
0888   PROTOBUF_ALWAYS_INLINE uint8_t* WriteLengthDelim(int num, uint32_t size,
0889                                                    uint8_t* ptr) {
0890     ptr = WriteTag(num, 2, ptr);
0891     return UnsafeWriteSize(size, ptr);
0892   }
0893 
0894   uint8_t* WriteRawFallback(const void* data, int size, uint8_t* ptr);
0895 
0896   uint8_t* WriteAliasedRaw(const void* data, int size, uint8_t* ptr);
0897 
0898   uint8_t* WriteStringMaybeAliasedOutline(uint32_t num, absl::string_view s,
0899                                           uint8_t* ptr);
0900   uint8_t* WriteStringOutline(uint32_t num, absl::string_view s, uint8_t* ptr);
0901   uint8_t* WriteCordOutline(const absl::Cord& c, uint8_t* ptr);
0902 
0903   template <typename T, typename E>
0904   PROTOBUF_ALWAYS_INLINE uint8_t* WriteVarintPacked(int num, const T& r,
0905                                                     int size, uint8_t* ptr,
0906                                                     const E& encode) {
0907     ptr = EnsureSpace(ptr);
0908     ptr = WriteLengthDelim(num, size, ptr);
0909     auto it = r.data();
0910     auto end = it + r.size();
0911     do {
0912       ptr = EnsureSpace(ptr);
0913       ptr = UnsafeVarint(encode(*it++), ptr);
0914     } while (it < end);
0915     return ptr;
0916   }
0917 
0918   static uint32_t Encode32(uint32_t v) { return v; }
0919   static uint64_t Encode64(uint64_t v) { return v; }
0920   static uint32_t ZigZagEncode32(int32_t v) {
0921     return (static_cast<uint32_t>(v) << 1) ^ static_cast<uint32_t>(v >> 31);
0922   }
0923   static uint64_t ZigZagEncode64(int64_t v) {
0924     return (static_cast<uint64_t>(v) << 1) ^ static_cast<uint64_t>(v >> 63);
0925   }
0926 
0927   template <typename T>
0928   PROTOBUF_ALWAYS_INLINE static uint8_t* UnsafeVarint(T value, uint8_t* ptr) {
0929     static_assert(std::is_unsigned<T>::value,
0930                   "Varint serialization must be unsigned");
0931     while (ABSL_PREDICT_FALSE(value >= 0x80)) {
0932       *ptr = static_cast<uint8_t>(value | 0x80);
0933       value >>= 7;
0934       ++ptr;
0935     }
0936     *ptr++ = static_cast<uint8_t>(value);
0937     return ptr;
0938   }
0939 
0940   PROTOBUF_ALWAYS_INLINE static uint8_t* UnsafeWriteSize(uint32_t value,
0941                                                          uint8_t* ptr) {
0942     while (ABSL_PREDICT_FALSE(value >= 0x80)) {
0943       *ptr = static_cast<uint8_t>(value | 0x80);
0944       value >>= 7;
0945       ++ptr;
0946     }
0947     *ptr++ = static_cast<uint8_t>(value);
0948     return ptr;
0949   }
0950 
0951   template <int S>
0952   uint8_t* WriteRawLittleEndian(const void* data, int size, uint8_t* ptr);
0953 #if !defined(ABSL_IS_LITTLE_ENDIAN) || \
0954     defined(PROTOBUF_DISABLE_LITTLE_ENDIAN_OPT_FOR_TEST)
0955   uint8_t* WriteRawLittleEndian32(const void* data, int size, uint8_t* ptr);
0956   uint8_t* WriteRawLittleEndian64(const void* data, int size, uint8_t* ptr);
0957 #endif
0958 
0959   // These methods are for CodedOutputStream. Ideally they should be private
0960   // but to match current behavior of CodedOutputStream as close as possible
0961   // we allow it some functionality.
0962  public:
0963   uint8_t* SetInitialBuffer(void* data, int size) {
0964     auto ptr = static_cast<uint8_t*>(data);
0965     if (size > kSlopBytes) {
0966       end_ = ptr + size - kSlopBytes;
0967       buffer_end_ = nullptr;
0968       return ptr;
0969     } else {
0970       end_ = buffer_ + size;
0971       buffer_end_ = ptr;
0972       return buffer_;
0973     }
0974   }
0975 
0976  private:
0977   // Needed by CodedOutputStream HadError. HadError needs to flush the patch
0978   // buffers to ensure there is no error as of yet.
0979   uint8_t* FlushAndResetBuffer(uint8_t*);
0980 
0981   // The following functions mimic the old CodedOutputStream behavior as close
0982   // as possible. They flush the current state to the stream, behave as
0983   // the old CodedOutputStream and then return to normal operation.
0984   bool Skip(int count, uint8_t** pp);
0985   bool GetDirectBufferPointer(void** data, int* size, uint8_t** pp);
0986   uint8_t* GetDirectBufferForNBytesAndAdvance(int size, uint8_t** pp);
0987 
0988   friend class CodedOutputStream;
0989 };
0990 
0991 template <>
0992 inline uint8_t* EpsCopyOutputStream::WriteRawLittleEndian<1>(const void* data,
0993                                                              int size,
0994                                                              uint8_t* ptr) {
0995   return WriteRaw(data, size, ptr);
0996 }
0997 template <>
0998 inline uint8_t* EpsCopyOutputStream::WriteRawLittleEndian<4>(const void* data,
0999                                                              int size,
1000                                                              uint8_t* ptr) {
1001 #if defined(ABSL_IS_LITTLE_ENDIAN) && \
1002     !defined(PROTOBUF_DISABLE_LITTLE_ENDIAN_OPT_FOR_TEST)
1003   return WriteRaw(data, size, ptr);
1004 #else
1005   return WriteRawLittleEndian32(data, size, ptr);
1006 #endif
1007 }
1008 template <>
1009 inline uint8_t* EpsCopyOutputStream::WriteRawLittleEndian<8>(const void* data,
1010                                                              int size,
1011                                                              uint8_t* ptr) {
1012 #if defined(ABSL_IS_LITTLE_ENDIAN) && \
1013     !defined(PROTOBUF_DISABLE_LITTLE_ENDIAN_OPT_FOR_TEST)
1014   return WriteRaw(data, size, ptr);
1015 #else
1016   return WriteRawLittleEndian64(data, size, ptr);
1017 #endif
1018 }
1019 
1020 // Class which encodes and writes binary data which is composed of varint-
1021 // encoded integers and fixed-width pieces.  Wraps a ZeroCopyOutputStream.
1022 // Most users will not need to deal with CodedOutputStream.
1023 //
1024 // Most methods of CodedOutputStream which return a bool return false if an
1025 // underlying I/O error occurs.  Once such a failure occurs, the
1026 // CodedOutputStream is broken and is no longer useful. The Write* methods do
1027 // not return the stream status, but will invalidate the stream if an error
1028 // occurs. The client can probe HadError() to determine the status.
1029 //
1030 // Note that every method of CodedOutputStream which writes some data has
1031 // a corresponding static "ToArray" version. These versions write directly
1032 // to the provided buffer, returning a pointer past the last written byte.
1033 // They require that the buffer has sufficient capacity for the encoded data.
1034 // This allows an optimization where we check if an output stream has enough
1035 // space for an entire message before we start writing and, if there is, we
1036 // call only the ToArray methods to avoid doing bound checks for each
1037 // individual value.
1038 // i.e., in the example above:
1039 //
1040 //   CodedOutputStream* coded_output = new CodedOutputStream(raw_output);
1041 //   int magic_number = 1234;
1042 //   char text[] = "Hello world!";
1043 //
1044 //   int coded_size = sizeof(magic_number) +
1045 //                    CodedOutputStream::VarintSize32(strlen(text)) +
1046 //                    strlen(text);
1047 //
1048 //   uint8_t* buffer =
1049 //       coded_output->GetDirectBufferForNBytesAndAdvance(coded_size);
1050 //   if (buffer != nullptr) {
1051 //     // The output stream has enough space in the buffer: write directly to
1052 //     // the array.
1053 //     buffer = CodedOutputStream::WriteLittleEndian32ToArray(magic_number,
1054 //                                                            buffer);
1055 //     buffer = CodedOutputStream::WriteVarint32ToArray(strlen(text), buffer);
1056 //     buffer = CodedOutputStream::WriteRawToArray(text, strlen(text), buffer);
1057 //   } else {
1058 //     // Make bound-checked writes, which will ask the underlying stream for
1059 //     // more space as needed.
1060 //     coded_output->WriteLittleEndian32(magic_number);
1061 //     coded_output->WriteVarint32(strlen(text));
1062 //     coded_output->WriteRaw(text, strlen(text));
1063 //   }
1064 //
1065 //   delete coded_output;
1066 class PROTOBUF_EXPORT CodedOutputStream {
1067  public:
1068   // Creates a CodedOutputStream that writes to the given `stream`.
1069   // The provided stream must publicly derive from `ZeroCopyOutputStream`.
1070   template <class Stream, class = typename std::enable_if<std::is_base_of<
1071                               ZeroCopyOutputStream, Stream>::value>::type>
1072   explicit CodedOutputStream(Stream* stream);
1073 
1074   // Creates a CodedOutputStream that writes to the given `stream`, and does
1075   // an 'eager initialization' of the internal state if `eager_init` is true.
1076   // The provided stream must publicly derive from `ZeroCopyOutputStream`.
1077   template <class Stream, class = typename std::enable_if<std::is_base_of<
1078                               ZeroCopyOutputStream, Stream>::value>::type>
1079   CodedOutputStream(Stream* stream, bool eager_init);
1080   CodedOutputStream(const CodedOutputStream&) = delete;
1081   CodedOutputStream& operator=(const CodedOutputStream&) = delete;
1082 
1083   // Destroy the CodedOutputStream and position the underlying
1084   // ZeroCopyOutputStream immediately after the last byte written.
1085   ~CodedOutputStream();
1086 
1087   // Returns true if there was an underlying I/O error since this object was
1088   // created. On should call Trim before this function in order to catch all
1089   // errors.
1090   bool HadError() {
1091     cur_ = impl_.FlushAndResetBuffer(cur_);
1092     ABSL_DCHECK(cur_);
1093     return impl_.HadError();
1094   }
1095 
1096   // Trims any unused space in the underlying buffer so that its size matches
1097   // the number of bytes written by this stream. The underlying buffer will
1098   // automatically be trimmed when this stream is destroyed; this call is only
1099   // necessary if the underlying buffer is accessed *before* the stream is
1100   // destroyed.
1101   void Trim() { cur_ = impl_.Trim(cur_); }
1102 
1103   // Skips a number of bytes, leaving the bytes unmodified in the underlying
1104   // buffer.  Returns false if an underlying write error occurs.  This is
1105   // mainly useful with GetDirectBufferPointer().
1106   // Note of caution, the skipped bytes may contain uninitialized data. The
1107   // caller must make sure that the skipped bytes are properly initialized,
1108   // otherwise you might leak bytes from your heap.
1109   bool Skip(int count) { return impl_.Skip(count, &cur_); }
1110 
1111   // Sets *data to point directly at the unwritten part of the
1112   // CodedOutputStream's underlying buffer, and *size to the size of that
1113   // buffer, but does not advance the stream's current position.  This will
1114   // always either produce a non-empty buffer or return false.  If the caller
1115   // writes any data to this buffer, it should then call Skip() to skip over
1116   // the consumed bytes.  This may be useful for implementing external fast
1117   // serialization routines for types of data not covered by the
1118   // CodedOutputStream interface.
1119   bool GetDirectBufferPointer(void** data, int* size) {
1120     return impl_.GetDirectBufferPointer(data, size, &cur_);
1121   }
1122 
1123   // If there are at least "size" bytes available in the current buffer,
1124   // returns a pointer directly into the buffer and advances over these bytes.
1125   // The caller may then write directly into this buffer (e.g. using the
1126   // *ToArray static methods) rather than go through CodedOutputStream.  If
1127   // there are not enough bytes available, returns NULL.  The return pointer is
1128   // invalidated as soon as any other non-const method of CodedOutputStream
1129   // is called.
1130   inline uint8_t* GetDirectBufferForNBytesAndAdvance(int size) {
1131     return impl_.GetDirectBufferForNBytesAndAdvance(size, &cur_);
1132   }
1133 
1134   // Write raw bytes, copying them from the given buffer.
1135   void WriteRaw(const void* buffer, int size) {
1136     cur_ = impl_.WriteRaw(buffer, size, cur_);
1137   }
1138   // Like WriteRaw()  but will try to write aliased data if aliasing is
1139   // turned on.
1140   void WriteRawMaybeAliased(const void* data, int size);
1141   // Like WriteRaw()  but writing directly to the target array.
1142   // This is _not_ inlined, as the compiler often optimizes memcpy into inline
1143   // copy loops. Since this gets called by every field with string or bytes
1144   // type, inlining may lead to a significant amount of code bloat, with only a
1145   // minor performance gain.
1146   static uint8_t* WriteRawToArray(const void* buffer, int size,
1147                                   uint8_t* target);
1148 
1149   // Equivalent to WriteRaw(str.data(), str.size()).
1150   void WriteString(absl::string_view str);
1151   // Like WriteString()  but writing directly to the target array.
1152   static uint8_t* WriteStringToArray(absl::string_view str, uint8_t* target);
1153   // Write the varint-encoded size of str followed by str.
1154   static uint8_t* WriteStringWithSizeToArray(absl::string_view str,
1155                                              uint8_t* target);
1156 
1157   // Like WriteString() but writes a Cord.
1158   void WriteCord(const absl::Cord& cord) { cur_ = impl_.WriteCord(cord, cur_); }
1159 
1160   // Like WriteCord() but writing directly to the target array.
1161   static uint8_t* WriteCordToArray(const absl::Cord& cord, uint8_t* target);
1162 
1163 
1164   // Write a 16-bit little-endian integer.
1165   void WriteLittleEndian16(uint16_t value) {
1166     cur_ = impl_.EnsureSpace(cur_);
1167     SetCur(WriteLittleEndian16ToArray(value, Cur()));
1168   }
1169   // Like WriteLittleEndian16() but writing directly to the target array.
1170   static uint8_t* WriteLittleEndian16ToArray(uint16_t value, uint8_t* target);
1171   // Write a 32-bit little-endian integer.
1172   void WriteLittleEndian32(uint32_t value) {
1173     cur_ = impl_.EnsureSpace(cur_);
1174     SetCur(WriteLittleEndian32ToArray(value, Cur()));
1175   }
1176   // Like WriteLittleEndian32() but writing directly to the target array.
1177   static uint8_t* WriteLittleEndian32ToArray(uint32_t value, uint8_t* target);
1178   // Write a 64-bit little-endian integer.
1179   void WriteLittleEndian64(uint64_t value) {
1180     cur_ = impl_.EnsureSpace(cur_);
1181     SetCur(WriteLittleEndian64ToArray(value, Cur()));
1182   }
1183   // Like WriteLittleEndian64() but writing directly to the target array.
1184   static uint8_t* WriteLittleEndian64ToArray(uint64_t value, uint8_t* target);
1185 
1186   // Write an unsigned integer with Varint encoding.  Writing a 32-bit value
1187   // is equivalent to casting it to uint64_t and writing it as a 64-bit value,
1188   // but may be more efficient.
1189   void WriteVarint32(uint32_t value);
1190   // Like WriteVarint32()  but writing directly to the target array.
1191   static uint8_t* WriteVarint32ToArray(uint32_t value, uint8_t* target);
1192   // Like WriteVarint32ToArray()
1193   [[deprecated("Please use WriteVarint32ToArray() instead")]] static uint8_t*
1194   WriteVarint32ToArrayOutOfLine(uint32_t value, uint8_t* target) {
1195     return WriteVarint32ToArray(value, target);
1196   }
1197   // Write an unsigned integer with Varint encoding.
1198   void WriteVarint64(uint64_t value);
1199   // Like WriteVarint64()  but writing directly to the target array.
1200   static uint8_t* WriteVarint64ToArray(uint64_t value, uint8_t* target);
1201 
1202   // Equivalent to WriteVarint32() except when the value is negative,
1203   // in which case it must be sign-extended to a full 10 bytes.
1204   void WriteVarint32SignExtended(int32_t value);
1205   // Like WriteVarint32SignExtended()  but writing directly to the target array.
1206   static uint8_t* WriteVarint32SignExtendedToArray(int32_t value,
1207                                                    uint8_t* target);
1208 
1209   // This is identical to WriteVarint32(), but optimized for writing tags.
1210   // In particular, if the input is a compile-time constant, this method
1211   // compiles down to a couple instructions.
1212   // Always inline because otherwise the aforementioned optimization can't work,
1213   // but GCC by default doesn't want to inline this.
1214   void WriteTag(uint32_t value);
1215   // Like WriteTag()  but writing directly to the target array.
1216   PROTOBUF_ALWAYS_INLINE
1217   static uint8_t* WriteTagToArray(uint32_t value, uint8_t* target);
1218 
1219   // Returns the number of bytes needed to encode the given value as a varint.
1220   static size_t VarintSize32(uint32_t value);
1221   // Returns the number of bytes needed to encode the given value as a varint.
1222   static size_t VarintSize64(uint64_t value);
1223 
1224   // If negative, 10 bytes.  Otherwise, same as VarintSize32().
1225   static size_t VarintSize32SignExtended(int32_t value);
1226 
1227   // Same as above, plus one.  The additional one comes at no compute cost.
1228   static size_t VarintSize32PlusOne(uint32_t value);
1229   static size_t VarintSize64PlusOne(uint64_t value);
1230   static size_t VarintSize32SignExtendedPlusOne(int32_t value);
1231 
1232   // Compile-time equivalent of VarintSize32().
1233   template <uint32_t Value>
1234   struct StaticVarintSize32 {
1235     static const size_t value = (Value < (1 << 7))    ? 1
1236                                 : (Value < (1 << 14)) ? 2
1237                                 : (Value < (1 << 21)) ? 3
1238                                 : (Value < (1 << 28)) ? 4
1239                                                       : 5;
1240   };
1241 
1242   // Returns the total number of bytes written since this object was created.
1243   int ByteCount() const {
1244     return static_cast<int>(impl_.ByteCount(cur_) - start_count_);
1245   }
1246 
1247   // Instructs the CodedOutputStream to allow the underlying
1248   // ZeroCopyOutputStream to hold pointers to the original structure instead of
1249   // copying, if it supports it (i.e. output->AllowsAliasing() is true).  If the
1250   // underlying stream does not support aliasing, then enabling it has no
1251   // affect.  For now, this only affects the behavior of
1252   // WriteRawMaybeAliased().
1253   //
1254   // NOTE: It is caller's responsibility to ensure that the chunk of memory
1255   // remains live until all of the data has been consumed from the stream.
1256   void EnableAliasing(bool enabled) { impl_.EnableAliasing(enabled); }
1257 
1258   // Indicate to the serializer whether the user wants deterministic
1259   // serialization. The default when this is not called comes from the global
1260   // default, controlled by SetDefaultSerializationDeterministic.
1261   //
1262   // What deterministic serialization means is entirely up to the driver of the
1263   // serialization process (i.e. the caller of methods like WriteVarint32). In
1264   // the case of serializing a proto buffer message using one of the methods of
1265   // MessageLite, this means that for a given binary equal messages will always
1266   // be serialized to the same bytes. This implies:
1267   //
1268   //   * Repeated serialization of a message will return the same bytes.
1269   //
1270   //   * Different processes running the same binary (including on different
1271   //     machines) will serialize equal messages to the same bytes.
1272   //
1273   // Note that this is *not* canonical across languages. It is also unstable
1274   // across different builds with intervening message definition changes, due to
1275   // unknown fields. Users who need canonical serialization (e.g. persistent
1276   // storage in a canonical form, fingerprinting) should define their own
1277   // canonicalization specification and implement the serializer using
1278   // reflection APIs rather than relying on this API.
1279   void SetSerializationDeterministic(bool value) {
1280     impl_.SetSerializationDeterministic(value);
1281   }
1282 
1283   // Return whether the user wants deterministic serialization. See above.
1284   bool IsSerializationDeterministic() const {
1285     return impl_.IsSerializationDeterministic();
1286   }
1287 
1288   static bool IsDefaultSerializationDeterministic() {
1289     return default_serialization_deterministic_.load(
1290                std::memory_order_relaxed) != 0;
1291   }
1292 
1293   template <typename Func>
1294   void Serialize(const Func& func);
1295 
1296   uint8_t* Cur() const { return cur_; }
1297   void SetCur(uint8_t* ptr) { cur_ = ptr; }
1298   EpsCopyOutputStream* EpsCopy() { return &impl_; }
1299 
1300  private:
1301   template <class Stream>
1302   void InitEagerly(Stream* stream);
1303 
1304   EpsCopyOutputStream impl_;
1305   uint8_t* cur_;
1306   int64_t start_count_;
1307   static std::atomic<bool> default_serialization_deterministic_;
1308 
1309   // See above.  Other projects may use "friend" to allow them to call this.
1310   // After SetDefaultSerializationDeterministic() completes, all protocol
1311   // buffer serializations will be deterministic by default.  Thread safe.
1312   // However, the meaning of "after" is subtle here: to be safe, each thread
1313   // that wants deterministic serialization by default needs to call
1314   // SetDefaultSerializationDeterministic() or ensure on its own that another
1315   // thread has done so.
1316   friend void google::protobuf::internal::MapTestForceDeterministic();
1317   static void SetDefaultSerializationDeterministic() {
1318     default_serialization_deterministic_.store(true, std::memory_order_relaxed);
1319   }
1320 };
1321 
1322 // inline methods ====================================================
1323 // The vast majority of varints are only one byte.  These inline
1324 // methods optimize for that case.
1325 
1326 inline bool CodedInputStream::ReadVarint32(uint32_t* value) {
1327   uint32_t v = 0;
1328   if (ABSL_PREDICT_TRUE(buffer_ < buffer_end_)) {
1329     v = *buffer_;
1330     if (v < 0x80) {
1331       *value = v;
1332       Advance(1);
1333       return true;
1334     }
1335   }
1336   int64_t result = ReadVarint32Fallback(v);
1337   *value = static_cast<uint32_t>(result);
1338   return result >= 0;
1339 }
1340 
1341 inline bool CodedInputStream::ReadVarint64(uint64_t* value) {
1342   if (ABSL_PREDICT_TRUE(buffer_ < buffer_end_) && *buffer_ < 0x80) {
1343     *value = *buffer_;
1344     Advance(1);
1345     return true;
1346   }
1347   std::pair<uint64_t, bool> p = ReadVarint64Fallback();
1348   *value = p.first;
1349   return p.second;
1350 }
1351 
1352 inline bool CodedInputStream::ReadVarintSizeAsInt(int* value) {
1353   if (ABSL_PREDICT_TRUE(buffer_ < buffer_end_)) {
1354     int v = *buffer_;
1355     if (v < 0x80) {
1356       *value = v;
1357       Advance(1);
1358       return true;
1359     }
1360   }
1361   *value = ReadVarintSizeAsIntFallback();
1362   return *value >= 0;
1363 }
1364 
1365 // static
1366 inline const uint8_t* CodedInputStream::ReadLittleEndian16FromArray(
1367     const uint8_t* buffer, uint16_t* value) {
1368   memcpy(value, buffer, sizeof(*value));
1369   *value = google::protobuf::internal::little_endian::ToHost(*value);
1370   return buffer + sizeof(*value);
1371 }
1372 // static
1373 inline const uint8_t* CodedInputStream::ReadLittleEndian32FromArray(
1374     const uint8_t* buffer, uint32_t* value) {
1375   memcpy(value, buffer, sizeof(*value));
1376   *value = google::protobuf::internal::little_endian::ToHost(*value);
1377   return buffer + sizeof(*value);
1378 }
1379 // static
1380 inline const uint8_t* CodedInputStream::ReadLittleEndian64FromArray(
1381     const uint8_t* buffer, uint64_t* value) {
1382   memcpy(value, buffer, sizeof(*value));
1383   *value = google::protobuf::internal::little_endian::ToHost(*value);
1384   return buffer + sizeof(*value);
1385 }
1386 
1387 inline bool CodedInputStream::ReadLittleEndian16(uint16_t* value) {
1388   if (ABSL_PREDICT_TRUE(BufferSize() >= static_cast<int>(sizeof(*value)))) {
1389     buffer_ = ReadLittleEndian16FromArray(buffer_, value);
1390     return true;
1391   } else {
1392     return ReadLittleEndian16Fallback(value);
1393   }
1394 }
1395 
1396 inline bool CodedInputStream::ReadLittleEndian32(uint32_t* value) {
1397 #if defined(ABSL_IS_LITTLE_ENDIAN) && \
1398     !defined(PROTOBUF_DISABLE_LITTLE_ENDIAN_OPT_FOR_TEST)
1399   if (ABSL_PREDICT_TRUE(BufferSize() >= static_cast<int>(sizeof(*value)))) {
1400     buffer_ = ReadLittleEndian32FromArray(buffer_, value);
1401     return true;
1402   } else {
1403     return ReadLittleEndian32Fallback(value);
1404   }
1405 #else
1406   return ReadLittleEndian32Fallback(value);
1407 #endif
1408 }
1409 
1410 inline bool CodedInputStream::ReadLittleEndian64(uint64_t* value) {
1411 #if defined(ABSL_IS_LITTLE_ENDIAN) && \
1412     !defined(PROTOBUF_DISABLE_LITTLE_ENDIAN_OPT_FOR_TEST)
1413   if (ABSL_PREDICT_TRUE(BufferSize() >= static_cast<int>(sizeof(*value)))) {
1414     buffer_ = ReadLittleEndian64FromArray(buffer_, value);
1415     return true;
1416   } else {
1417     return ReadLittleEndian64Fallback(value);
1418   }
1419 #else
1420   return ReadLittleEndian64Fallback(value);
1421 #endif
1422 }
1423 
1424 inline uint32_t CodedInputStream::ReadTagNoLastTag() {
1425   uint32_t v = 0;
1426   if (ABSL_PREDICT_TRUE(buffer_ < buffer_end_)) {
1427     v = *buffer_;
1428     if (v < 0x80) {
1429       Advance(1);
1430       return v;
1431     }
1432   }
1433   v = ReadTagFallback(v);
1434   return v;
1435 }
1436 
1437 inline std::pair<uint32_t, bool> CodedInputStream::ReadTagWithCutoffNoLastTag(
1438     uint32_t cutoff) {
1439   // In performance-sensitive code we can expect cutoff to be a compile-time
1440   // constant, and things like "cutoff >= kMax1ByteVarint" to be evaluated at
1441   // compile time.
1442   uint32_t first_byte_or_zero = 0;
1443   if (ABSL_PREDICT_TRUE(buffer_ < buffer_end_)) {
1444     // Hot case: buffer_ non_empty, buffer_[0] in [1, 128).
1445     // TODO: Is it worth rearranging this? E.g., if the number of fields
1446     // is large enough then is it better to check for the two-byte case first?
1447     first_byte_or_zero = buffer_[0];
1448     if (static_cast<int8_t>(buffer_[0]) > 0) {
1449       const uint32_t kMax1ByteVarint = 0x7f;
1450       uint32_t tag = buffer_[0];
1451       Advance(1);
1452       return std::make_pair(tag, cutoff >= kMax1ByteVarint || tag <= cutoff);
1453     }
1454     // Other hot case: cutoff >= 0x80, buffer_ has at least two bytes available,
1455     // and tag is two bytes.  The latter is tested by bitwise-and-not of the
1456     // first byte and the second byte.
1457     if (cutoff >= 0x80 && ABSL_PREDICT_TRUE(buffer_ + 1 < buffer_end_) &&
1458         ABSL_PREDICT_TRUE((buffer_[0] & ~buffer_[1]) >= 0x80)) {
1459       const uint32_t kMax2ByteVarint = (0x7f << 7) + 0x7f;
1460       uint32_t tag = (1u << 7) * buffer_[1] + (buffer_[0] - 0x80);
1461       Advance(2);
1462       // It might make sense to test for tag == 0 now, but it is so rare that
1463       // that we don't bother.  A varint-encoded 0 should be one byte unless
1464       // the encoder lost its mind.  The second part of the return value of
1465       // this function is allowed to be either true or false if the tag is 0,
1466       // so we don't have to check for tag == 0.  We may need to check whether
1467       // it exceeds cutoff.
1468       bool at_or_below_cutoff = cutoff >= kMax2ByteVarint || tag <= cutoff;
1469       return std::make_pair(tag, at_or_below_cutoff);
1470     }
1471   }
1472   // Slow path
1473   const uint32_t tag = ReadTagFallback(first_byte_or_zero);
1474   return std::make_pair(tag, static_cast<uint32_t>(tag - 1) < cutoff);
1475 }
1476 
1477 inline bool CodedInputStream::LastTagWas(uint32_t expected) {
1478   return last_tag_ == expected;
1479 }
1480 
1481 inline bool CodedInputStream::ConsumedEntireMessage() {
1482   return legitimate_message_end_;
1483 }
1484 
1485 inline bool CodedInputStream::ExpectTag(uint32_t expected) {
1486   if (expected < (1 << 7)) {
1487     if (ABSL_PREDICT_TRUE(buffer_ < buffer_end_) && buffer_[0] == expected) {
1488       Advance(1);
1489       return true;
1490     } else {
1491       return false;
1492     }
1493   } else if (expected < (1 << 14)) {
1494     if (ABSL_PREDICT_TRUE(BufferSize() >= 2) &&
1495         buffer_[0] == static_cast<uint8_t>(expected | 0x80) &&
1496         buffer_[1] == static_cast<uint8_t>(expected >> 7)) {
1497       Advance(2);
1498       return true;
1499     } else {
1500       return false;
1501     }
1502   } else {
1503     // Don't bother optimizing for larger values.
1504     return false;
1505   }
1506 }
1507 
1508 inline const uint8_t* CodedInputStream::ExpectTagFromArray(
1509     const uint8_t* buffer, uint32_t expected) {
1510   if (expected < (1 << 7)) {
1511     if (buffer[0] == expected) {
1512       return buffer + 1;
1513     }
1514   } else if (expected < (1 << 14)) {
1515     if (buffer[0] == static_cast<uint8_t>(expected | 0x80) &&
1516         buffer[1] == static_cast<uint8_t>(expected >> 7)) {
1517       return buffer + 2;
1518     }
1519   }
1520   return nullptr;
1521 }
1522 
1523 inline void CodedInputStream::GetDirectBufferPointerInline(const void** data,
1524                                                            int* size) {
1525   *data = buffer_;
1526   *size = static_cast<int>(buffer_end_ - buffer_);
1527 }
1528 
1529 inline bool CodedInputStream::ExpectAtEnd() {
1530   // If we are at a limit we know no more bytes can be read.  Otherwise, it's
1531   // hard to say without calling Refresh(), and we'd rather not do that.
1532 
1533   if (buffer_ == buffer_end_ && ((buffer_size_after_limit_ != 0) ||
1534                                  (total_bytes_read_ == current_limit_))) {
1535     last_tag_ = 0;                   // Pretend we called ReadTag()...
1536     legitimate_message_end_ = true;  // ... and it hit EOF.
1537     return true;
1538   } else {
1539     return false;
1540   }
1541 }
1542 
1543 inline int CodedInputStream::CurrentPosition() const {
1544   return total_bytes_read_ - (BufferSize() + buffer_size_after_limit_);
1545 }
1546 
1547 inline void CodedInputStream::Advance(int amount) { buffer_ += amount; }
1548 
1549 inline void CodedInputStream::SetRecursionLimit(int limit) {
1550   recursion_budget_ += limit - recursion_limit_;
1551   recursion_limit_ = limit;
1552 }
1553 
1554 inline bool CodedInputStream::IncrementRecursionDepth() {
1555   --recursion_budget_;
1556   return recursion_budget_ >= 0;
1557 }
1558 
1559 inline void CodedInputStream::DecrementRecursionDepth() {
1560   if (recursion_budget_ < recursion_limit_) ++recursion_budget_;
1561 }
1562 
1563 inline void CodedInputStream::UnsafeDecrementRecursionDepth() {
1564   assert(recursion_budget_ < recursion_limit_);
1565   ++recursion_budget_;
1566 }
1567 
1568 inline void CodedInputStream::SetExtensionRegistry(const DescriptorPool* pool,
1569                                                    MessageFactory* factory) {
1570   extension_pool_ = pool;
1571   extension_factory_ = factory;
1572 }
1573 
1574 inline const DescriptorPool* CodedInputStream::GetExtensionPool() {
1575   return extension_pool_;
1576 }
1577 
1578 inline MessageFactory* CodedInputStream::GetExtensionFactory() {
1579   return extension_factory_;
1580 }
1581 
1582 inline int CodedInputStream::BufferSize() const {
1583   return static_cast<int>(buffer_end_ - buffer_);
1584 }
1585 
1586 inline CodedInputStream::CodedInputStream(ZeroCopyInputStream* input)
1587     : buffer_(nullptr),
1588       buffer_end_(nullptr),
1589       input_(input),
1590       total_bytes_read_(0),
1591       overflow_bytes_(0),
1592       last_tag_(0),
1593       legitimate_message_end_(false),
1594       aliasing_enabled_(false),
1595       force_eager_parsing_(false),
1596       current_limit_(std::numeric_limits<int32_t>::max()),
1597       buffer_size_after_limit_(0),
1598       total_bytes_limit_(kDefaultTotalBytesLimit),
1599       recursion_budget_(default_recursion_limit_),
1600       recursion_limit_(default_recursion_limit_),
1601       extension_pool_(nullptr),
1602       extension_factory_(nullptr) {
1603   // Eagerly Refresh() so buffer space is immediately available.
1604   Refresh();
1605 }
1606 
1607 inline CodedInputStream::CodedInputStream(const uint8_t* buffer, int size)
1608     : buffer_(buffer),
1609       buffer_end_(buffer + size),
1610       input_(nullptr),
1611       total_bytes_read_(size),
1612       overflow_bytes_(0),
1613       last_tag_(0),
1614       legitimate_message_end_(false),
1615       aliasing_enabled_(false),
1616       force_eager_parsing_(false),
1617       current_limit_(size),
1618       buffer_size_after_limit_(0),
1619       total_bytes_limit_(kDefaultTotalBytesLimit),
1620       recursion_budget_(default_recursion_limit_),
1621       recursion_limit_(default_recursion_limit_),
1622       extension_pool_(nullptr),
1623       extension_factory_(nullptr) {
1624   // Note that setting current_limit_ == size is important to prevent some
1625   // code paths from trying to access input_ and segfaulting.
1626 }
1627 
1628 inline bool CodedInputStream::IsFlat() const { return input_ == nullptr; }
1629 
1630 inline bool CodedInputStream::Skip(int count) {
1631   if (count < 0) return false;  // security: count is often user-supplied
1632 
1633   const int original_buffer_size = BufferSize();
1634 
1635   if (count <= original_buffer_size) {
1636     // Just skipping within the current buffer.  Easy.
1637     Advance(count);
1638     return true;
1639   }
1640 
1641   return SkipFallback(count, original_buffer_size);
1642 }
1643 
1644 template <class Stream, class>
1645 inline CodedOutputStream::CodedOutputStream(Stream* stream)
1646     : impl_(stream, IsDefaultSerializationDeterministic(), &cur_),
1647       start_count_(stream->ByteCount()) {
1648   InitEagerly(stream);
1649 }
1650 
1651 template <class Stream, class>
1652 inline CodedOutputStream::CodedOutputStream(Stream* stream, bool eager_init)
1653     : impl_(stream, IsDefaultSerializationDeterministic(), &cur_),
1654       start_count_(stream->ByteCount()) {
1655   if (eager_init) {
1656     InitEagerly(stream);
1657   }
1658 }
1659 
1660 template <class Stream>
1661 inline void CodedOutputStream::InitEagerly(Stream* stream) {
1662   void* data;
1663   int size;
1664   if (ABSL_PREDICT_TRUE(stream->Next(&data, &size) && size > 0)) {
1665     cur_ = impl_.SetInitialBuffer(data, size);
1666   }
1667 }
1668 
1669 inline uint8_t* CodedOutputStream::WriteVarint32ToArray(uint32_t value,
1670                                                         uint8_t* target) {
1671   return EpsCopyOutputStream::UnsafeVarint(value, target);
1672 }
1673 
1674 inline uint8_t* CodedOutputStream::WriteVarint64ToArray(uint64_t value,
1675                                                         uint8_t* target) {
1676   return EpsCopyOutputStream::UnsafeVarint(value, target);
1677 }
1678 
1679 inline void CodedOutputStream::WriteVarint32SignExtended(int32_t value) {
1680   WriteVarint64(static_cast<uint64_t>(value));
1681 }
1682 
1683 inline uint8_t* CodedOutputStream::WriteVarint32SignExtendedToArray(
1684     int32_t value, uint8_t* target) {
1685   return WriteVarint64ToArray(static_cast<uint64_t>(value), target);
1686 }
1687 
1688 inline uint8_t* CodedOutputStream::WriteLittleEndian16ToArray(uint16_t value,
1689                                                               uint8_t* target) {
1690   uint16_t little_endian_value = google::protobuf::internal::little_endian::ToHost(value);
1691   memcpy(target, &little_endian_value, sizeof(value));
1692   return target + sizeof(value);
1693 }
1694 
1695 inline uint8_t* CodedOutputStream::WriteLittleEndian32ToArray(uint32_t value,
1696                                                               uint8_t* target) {
1697 #if defined(ABSL_IS_LITTLE_ENDIAN) && \
1698     !defined(PROTOBUF_DISABLE_LITTLE_ENDIAN_OPT_FOR_TEST)
1699   memcpy(target, &value, sizeof(value));
1700 #else
1701   target[0] = static_cast<uint8_t>(value);
1702   target[1] = static_cast<uint8_t>(value >> 8);
1703   target[2] = static_cast<uint8_t>(value >> 16);
1704   target[3] = static_cast<uint8_t>(value >> 24);
1705 #endif
1706   return target + sizeof(value);
1707 }
1708 
1709 inline uint8_t* CodedOutputStream::WriteLittleEndian64ToArray(uint64_t value,
1710                                                               uint8_t* target) {
1711 #if defined(ABSL_IS_LITTLE_ENDIAN) && \
1712     !defined(PROTOBUF_DISABLE_LITTLE_ENDIAN_OPT_FOR_TEST)
1713   memcpy(target, &value, sizeof(value));
1714 #else
1715   uint32_t part0 = static_cast<uint32_t>(value);
1716   uint32_t part1 = static_cast<uint32_t>(value >> 32);
1717 
1718   target[0] = static_cast<uint8_t>(part0);
1719   target[1] = static_cast<uint8_t>(part0 >> 8);
1720   target[2] = static_cast<uint8_t>(part0 >> 16);
1721   target[3] = static_cast<uint8_t>(part0 >> 24);
1722   target[4] = static_cast<uint8_t>(part1);
1723   target[5] = static_cast<uint8_t>(part1 >> 8);
1724   target[6] = static_cast<uint8_t>(part1 >> 16);
1725   target[7] = static_cast<uint8_t>(part1 >> 24);
1726 #endif
1727   return target + sizeof(value);
1728 }
1729 
1730 inline void CodedOutputStream::WriteVarint32(uint32_t value) {
1731   cur_ = impl_.EnsureSpace(cur_);
1732   SetCur(WriteVarint32ToArray(value, Cur()));
1733 }
1734 
1735 inline void CodedOutputStream::WriteVarint64(uint64_t value) {
1736   cur_ = impl_.EnsureSpace(cur_);
1737   SetCur(WriteVarint64ToArray(value, Cur()));
1738 }
1739 
1740 inline void CodedOutputStream::WriteTag(uint32_t value) {
1741   WriteVarint32(value);
1742 }
1743 
1744 inline uint8_t* CodedOutputStream::WriteTagToArray(uint32_t value,
1745                                                    uint8_t* target) {
1746   return WriteVarint32ToArray(value, target);
1747 }
1748 
1749 #if (defined(__x86__) || defined(__x86_64__) || defined(_M_IX86) || \
1750      defined(_M_X64)) &&                                            \
1751     !(defined(__LZCNT__) || defined(__AVX2__))
1752 // X86 CPUs lacking the lzcnt instruction are faster with the bsr-based
1753 // implementation. MSVC does not define __LZCNT__, the nearest option that
1754 // it interprets as lzcnt availability is __AVX2__.
1755 #define PROTOBUF_CODED_STREAM_H_PREFER_BSR 1
1756 #else
1757 #define PROTOBUF_CODED_STREAM_H_PREFER_BSR 0
1758 #endif
1759 inline size_t CodedOutputStream::VarintSize32(uint32_t value) {
1760 #if PROTOBUF_CODED_STREAM_H_PREFER_BSR
1761   // Explicit OR 0x1 to avoid calling absl::countl_zero(0), which
1762   // requires a branch to check for on platforms without a clz instruction.
1763   uint32_t log2value = (std::numeric_limits<uint32_t>::digits - 1) -
1764                        absl::countl_zero(value | 0x1);
1765   return static_cast<size_t>((log2value * 9 + (64 + 9)) / 64);
1766 #else
1767   uint32_t clz = absl::countl_zero(value);
1768   return static_cast<size_t>(
1769       ((std::numeric_limits<uint32_t>::digits * 9 + 64) - (clz * 9)) / 64);
1770 #endif
1771 }
1772 
1773 inline size_t CodedOutputStream::VarintSize32PlusOne(uint32_t value) {
1774   // Same as above, but one more.
1775 #if PROTOBUF_CODED_STREAM_H_PREFER_BSR
1776   uint32_t log2value = (std::numeric_limits<uint32_t>::digits - 1) -
1777                        absl::countl_zero(value | 0x1);
1778   return static_cast<size_t>((log2value * 9 + (64 + 9) + 64) / 64);
1779 #else
1780   uint32_t clz = absl::countl_zero(value);
1781   return static_cast<size_t>(
1782       ((std::numeric_limits<uint32_t>::digits * 9 + 64 + 64) - (clz * 9)) / 64);
1783 #endif
1784 }
1785 
1786 inline size_t CodedOutputStream::VarintSize64(uint64_t value) {
1787 #if PROTOBUF_CODED_STREAM_H_PREFER_BSR
1788   // Explicit OR 0x1 to avoid calling absl::countl_zero(0), which
1789   // requires a branch to check for on platforms without a clz instruction.
1790   uint32_t log2value = (std::numeric_limits<uint64_t>::digits - 1) -
1791                        absl::countl_zero(value | 0x1);
1792   return static_cast<size_t>((log2value * 9 + (64 + 9)) / 64);
1793 #else
1794   uint32_t clz = absl::countl_zero(value);
1795   return static_cast<size_t>(
1796       ((std::numeric_limits<uint64_t>::digits * 9 + 64) - (clz * 9)) / 64);
1797 #endif
1798 }
1799 
1800 inline size_t CodedOutputStream::VarintSize64PlusOne(uint64_t value) {
1801   // Same as above, but one more.
1802 #if PROTOBUF_CODED_STREAM_H_PREFER_BSR
1803   uint32_t log2value = (std::numeric_limits<uint64_t>::digits - 1) -
1804                        absl::countl_zero(value | 0x1);
1805   return static_cast<size_t>((log2value * 9 + (64 + 9) + 64) / 64);
1806 #else
1807   uint32_t clz = absl::countl_zero(value);
1808   return static_cast<size_t>(
1809       ((std::numeric_limits<uint64_t>::digits * 9 + 64 + 64) - (clz * 9)) / 64);
1810 #endif
1811 }
1812 
1813 inline size_t CodedOutputStream::VarintSize32SignExtended(int32_t value) {
1814   return VarintSize64(static_cast<uint64_t>(int64_t{value}));
1815 }
1816 
1817 inline size_t CodedOutputStream::VarintSize32SignExtendedPlusOne(
1818     int32_t value) {
1819   return VarintSize64PlusOne(static_cast<uint64_t>(int64_t{value}));
1820 }
1821 #undef PROTOBUF_CODED_STREAM_H_PREFER_BSR
1822 
1823 inline void CodedOutputStream::WriteString(absl::string_view str) {
1824   WriteRaw(str.data(), static_cast<int>(str.size()));
1825 }
1826 
1827 inline void CodedOutputStream::WriteRawMaybeAliased(const void* data,
1828                                                     int size) {
1829   cur_ = impl_.WriteRawMaybeAliased(data, size, cur_);
1830 }
1831 
1832 inline uint8_t* CodedOutputStream::WriteRawToArray(const void* data, int size,
1833                                                    uint8_t* target) {
1834   memcpy(target, data, static_cast<unsigned int>(size));
1835   return target + size;
1836 }
1837 
1838 inline uint8_t* CodedOutputStream::WriteStringToArray(absl::string_view str,
1839                                                       uint8_t* target) {
1840   return WriteRawToArray(str.data(), static_cast<int>(str.size()), target);
1841 }
1842 
1843 }  // namespace io
1844 }  // namespace protobuf
1845 }  // namespace google
1846 
1847 #if defined(_MSC_VER) && _MSC_VER >= 1300 && !defined(__INTEL_COMPILER)
1848 #pragma runtime_checks("c", restore)
1849 #endif  // _MSC_VER && !defined(__INTEL_COMPILER)
1850 
1851 #include "google/protobuf/port_undef.inc"
1852 
1853 #endif  // GOOGLE_PROTOBUF_IO_CODED_STREAM_H__