Back to home page

EIC code displayed by LXR

 
 

    


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

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