Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-09-22 08:53:15

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 common implementations of the interfaces defined in
0013 // zero_copy_stream.h which are included in the "lite" protobuf library.
0014 // These implementations cover I/O on raw arrays and strings, as well as
0015 // adaptors which make it easy to implement streams based on traditional
0016 // streams.  Of course, many users will probably want to write their own
0017 // implementations of these interfaces specific to the particular I/O
0018 // abstractions they prefer to use, but these should cover the most common
0019 // cases.
0020 
0021 #ifndef GOOGLE_PROTOBUF_IO_ZERO_COPY_STREAM_IMPL_LITE_H__
0022 #define GOOGLE_PROTOBUF_IO_ZERO_COPY_STREAM_IMPL_LITE_H__
0023 
0024 #include <cstddef>
0025 #include <cstdint>
0026 #include <memory>
0027 #include <string>
0028 #include <utility>
0029 
0030 #include "absl/base/attributes.h"
0031 #include "absl/base/macros.h"
0032 #include "absl/strings/cord.h"
0033 #include "absl/strings/cord_buffer.h"
0034 #include "google/protobuf/io/zero_copy_stream.h"
0035 
0036 // Must be included last.
0037 #include "google/protobuf/port_def.inc"
0038 
0039 namespace google {
0040 namespace protobuf {
0041 namespace io {
0042 
0043 // ===================================================================
0044 
0045 // A ZeroCopyInputStream backed by an in-memory array of bytes.
0046 class PROTOBUF_EXPORT ArrayInputStream final : public ZeroCopyInputStream {
0047  public:
0048   // Create an InputStream that returns the bytes pointed to by "data".
0049   // "data" remains the property of the caller but must remain valid until
0050   // the stream is destroyed.  If a block_size is given, calls to Next()
0051   // will return data blocks no larger than the given size.  Otherwise, the
0052   // first call to Next() returns the entire array.  block_size is mainly
0053   // useful for testing; in production you would probably never want to set
0054   // it.
0055   ArrayInputStream(const void* data, int size, int block_size = -1);
0056   ~ArrayInputStream() override = default;
0057 
0058   // `ArrayInputStream` is neither copiable nor assignable
0059   ArrayInputStream(const ArrayInputStream&) = delete;
0060   ArrayInputStream& operator=(const ArrayInputStream&) = delete;
0061 
0062   // implements ZeroCopyInputStream ----------------------------------
0063   bool Next(const void** data, int* size) override;
0064   void BackUp(int count) override;
0065   bool Skip(int count) override;
0066   int64_t ByteCount() const override;
0067 
0068 
0069  private:
0070   const uint8_t* const data_;  // The byte array.
0071   const int size_;           // Total size of the array.
0072   const int block_size_;     // How many bytes to return at a time.
0073 
0074   int position_;
0075   int last_returned_size_;  // How many bytes we returned last time Next()
0076                             // was called (used for error checking only).
0077 };
0078 
0079 // ===================================================================
0080 
0081 // A ZeroCopyOutputStream backed by an in-memory array of bytes.
0082 class PROTOBUF_EXPORT ArrayOutputStream final : public ZeroCopyOutputStream {
0083  public:
0084   // Create an OutputStream that writes to the bytes pointed to by "data".
0085   // "data" remains the property of the caller but must remain valid until
0086   // the stream is destroyed.  If a block_size is given, calls to Next()
0087   // will return data blocks no larger than the given size.  Otherwise, the
0088   // first call to Next() returns the entire array.  block_size is mainly
0089   // useful for testing; in production you would probably never want to set
0090   // it.
0091   ArrayOutputStream(void* data, int size, int block_size = -1);
0092   ~ArrayOutputStream() override = default;
0093 
0094   // `ArrayOutputStream` is neither copiable nor assignable
0095   ArrayOutputStream(const ArrayOutputStream&) = delete;
0096   ArrayOutputStream& operator=(const ArrayOutputStream&) = delete;
0097 
0098   // implements ZeroCopyOutputStream ---------------------------------
0099   bool Next(void** data, int* size) override;
0100   void BackUp(int count) override;
0101   int64_t ByteCount() const override;
0102 
0103  private:
0104   uint8_t* const data_;     // The byte array.
0105   const int size_;        // Total size of the array.
0106   const int block_size_;  // How many bytes to return at a time.
0107 
0108   int position_;
0109   int last_returned_size_;  // How many bytes we returned last time Next()
0110                             // was called (used for error checking only).
0111 };
0112 
0113 // ===================================================================
0114 
0115 // A ZeroCopyOutputStream which appends bytes to a string.
0116 class PROTOBUF_EXPORT StringOutputStream final : public ZeroCopyOutputStream {
0117  public:
0118   // Create a StringOutputStream which appends bytes to the given string.
0119   // The string remains property of the caller, but it is mutated in arbitrary
0120   // ways and MUST NOT be accessed in any way until you're done with the
0121   // stream. Either be sure there's no further usage, or (safest) destroy the
0122   // stream before using the contents.
0123   //
0124   // Hint:  If you call target->reserve(n) before creating the stream,
0125   //   the first call to Next() will return at least n bytes of buffer
0126   //   space.
0127   explicit StringOutputStream(std::string* target);
0128   ~StringOutputStream() override = default;
0129 
0130   // `StringOutputStream` is neither copiable nor assignable
0131   StringOutputStream(const StringOutputStream&) = delete;
0132   StringOutputStream& operator=(const StringOutputStream&) = delete;
0133 
0134   // implements ZeroCopyOutputStream ---------------------------------
0135   bool Next(void** data, int* size) override;
0136   void BackUp(int count) override;
0137   int64_t ByteCount() const override;
0138 
0139  private:
0140   static constexpr size_t kMinimumSize = 16;
0141 
0142   std::string* target_;
0143 };
0144 
0145 // Note:  There is no StringInputStream.  Instead, just create an
0146 // ArrayInputStream as follows:
0147 //   ArrayInputStream input(str.data(), str.size());
0148 
0149 // ===================================================================
0150 
0151 // A generic traditional input stream interface.
0152 //
0153 // Lots of traditional input streams (e.g. file descriptors, C stdio
0154 // streams, and C++ iostreams) expose an interface where every read
0155 // involves copying bytes into a buffer.  If you want to take such an
0156 // interface and make a ZeroCopyInputStream based on it, simply implement
0157 // CopyingInputStream and then use CopyingInputStreamAdaptor.
0158 //
0159 // CopyingInputStream implementations should avoid buffering if possible.
0160 // CopyingInputStreamAdaptor does its own buffering and will read data
0161 // in large blocks.
0162 class PROTOBUF_EXPORT CopyingInputStream {
0163  public:
0164   virtual ~CopyingInputStream() = default;
0165 
0166   // Reads up to "size" bytes into the given buffer.  Returns the number of
0167   // bytes read.  Read() waits until at least one byte is available, or
0168   // returns zero if no bytes will ever become available (EOF), or -1 if a
0169   // permanent read error occurred.
0170   virtual int Read(void* buffer, int size) = 0;
0171 
0172   // Skips the next "count" bytes of input.  Returns the number of bytes
0173   // actually skipped.  This will always be exactly equal to "count" unless
0174   // EOF was reached or a permanent read error occurred.
0175   //
0176   // The default implementation just repeatedly calls Read() into a scratch
0177   // buffer.
0178   virtual int Skip(int count);
0179 };
0180 
0181 // A ZeroCopyInputStream which reads from a CopyingInputStream.  This is
0182 // useful for implementing ZeroCopyInputStreams that read from traditional
0183 // streams.  Note that this class is not really zero-copy.
0184 //
0185 // If you want to read from file descriptors or C++ istreams, this is
0186 // already implemented for you:  use FileInputStream or IstreamInputStream
0187 // respectively.
0188 class PROTOBUF_EXPORT CopyingInputStreamAdaptor : public ZeroCopyInputStream {
0189  public:
0190   // Creates a stream that reads from the given CopyingInputStream.
0191   // If a block_size is given, it specifies the number of bytes that
0192   // should be read and returned with each call to Next().  Otherwise,
0193   // a reasonable default is used.  The caller retains ownership of
0194   // copying_stream unless SetOwnsCopyingStream(true) is called.
0195   explicit CopyingInputStreamAdaptor(CopyingInputStream* copying_stream,
0196                                      int block_size = -1);
0197   ~CopyingInputStreamAdaptor() override;
0198 
0199   // `CopyingInputStreamAdaptor` is neither copiable nor assignable
0200   CopyingInputStreamAdaptor(const CopyingInputStreamAdaptor&) = delete;
0201   CopyingInputStreamAdaptor& operator=(const CopyingInputStreamAdaptor&) = delete;
0202 
0203   // Call SetOwnsCopyingStream(true) to tell the CopyingInputStreamAdaptor to
0204   // delete the underlying CopyingInputStream when it is destroyed.
0205   void SetOwnsCopyingStream(bool value) { owns_copying_stream_ = value; }
0206 
0207   // implements ZeroCopyInputStream ----------------------------------
0208   bool Next(const void** data, int* size) override;
0209   void BackUp(int count) override;
0210   bool Skip(int count) override;
0211   int64_t ByteCount() const override;
0212 
0213  private:
0214   // Insures that buffer_ is not NULL.
0215   void AllocateBufferIfNeeded();
0216   // Frees the buffer and resets buffer_used_.
0217   void FreeBuffer();
0218 
0219   // The underlying copying stream.
0220   CopyingInputStream* copying_stream_;
0221   bool owns_copying_stream_;
0222 
0223   // True if we have seen a permanent error from the underlying stream.
0224   bool failed_;
0225 
0226   // The current position of copying_stream_, relative to the point where
0227   // we started reading.
0228   int64_t position_;
0229 
0230   // Data is read into this buffer.  It may be NULL if no buffer is currently
0231   // in use.  Otherwise, it points to an array of size buffer_size_.
0232   std::unique_ptr<uint8_t[]> buffer_;
0233   const int buffer_size_;
0234 
0235   // Number of valid bytes currently in the buffer (i.e. the size last
0236   // returned by Next()).  0 <= buffer_used_ <= buffer_size_.
0237   int buffer_used_;
0238 
0239   // Number of bytes in the buffer which were backed up over by a call to
0240   // BackUp().  These need to be returned again.
0241   // 0 <= backup_bytes_ <= buffer_used_
0242   int backup_bytes_;
0243 };
0244 
0245 // ===================================================================
0246 
0247 // A generic traditional output stream interface.
0248 //
0249 // Lots of traditional output streams (e.g. file descriptors, C stdio
0250 // streams, and C++ iostreams) expose an interface where every write
0251 // involves copying bytes from a buffer.  If you want to take such an
0252 // interface and make a ZeroCopyOutputStream based on it, simply implement
0253 // CopyingOutputStream and then use CopyingOutputStreamAdaptor.
0254 //
0255 // CopyingOutputStream implementations should avoid buffering if possible.
0256 // CopyingOutputStreamAdaptor does its own buffering and will write data
0257 // in large blocks.
0258 class PROTOBUF_EXPORT CopyingOutputStream {
0259  public:
0260   virtual ~CopyingOutputStream() = default;
0261 
0262   // Writes "size" bytes from the given buffer to the output.  Returns true
0263   // if successful, false on a write error.
0264   virtual bool Write(const void* buffer, int size) = 0;
0265 };
0266 
0267 // A ZeroCopyOutputStream which writes to a CopyingOutputStream.  This is
0268 // useful for implementing ZeroCopyOutputStreams that write to traditional
0269 // streams.  Note that this class is not really zero-copy.
0270 //
0271 // If you want to write to file descriptors or C++ ostreams, this is
0272 // already implemented for you:  use FileOutputStream or OstreamOutputStream
0273 // respectively.
0274 class PROTOBUF_EXPORT CopyingOutputStreamAdaptor : public ZeroCopyOutputStream {
0275  public:
0276   // Creates a stream that writes to the given Unix file descriptor.
0277   // If a block_size is given, it specifies the size of the buffers
0278   // that should be returned by Next().  Otherwise, a reasonable default
0279   // is used.
0280   explicit CopyingOutputStreamAdaptor(CopyingOutputStream* copying_stream,
0281                                       int block_size = -1);
0282   ~CopyingOutputStreamAdaptor() override;
0283 
0284   // `CopyingOutputStreamAdaptor` is neither copiable nor assignable
0285   CopyingOutputStreamAdaptor(const CopyingOutputStreamAdaptor&) = delete;
0286   CopyingOutputStreamAdaptor& operator=(const CopyingOutputStreamAdaptor&) = delete;
0287 
0288   // Writes all pending data to the underlying stream.  Returns false if a
0289   // write error occurred on the underlying stream.  (The underlying
0290   // stream itself is not necessarily flushed.)
0291   bool Flush();
0292 
0293   // Call SetOwnsCopyingStream(true) to tell the CopyingOutputStreamAdaptor to
0294   // delete the underlying CopyingOutputStream when it is destroyed.
0295   void SetOwnsCopyingStream(bool value) { owns_copying_stream_ = value; }
0296 
0297   // implements ZeroCopyOutputStream ---------------------------------
0298   bool Next(void** data, int* size) override;
0299   void BackUp(int count) override;
0300   int64_t ByteCount() const override;
0301   bool WriteAliasedRaw(const void* data, int size) override;
0302   bool AllowsAliasing() const override { return true; }
0303   bool WriteCord(const absl::Cord& cord) override;
0304 
0305  private:
0306   // Write the current buffer, if it is present.
0307   bool WriteBuffer();
0308   // Insures that buffer_ is not NULL.
0309   void AllocateBufferIfNeeded();
0310   // Frees the buffer.
0311   void FreeBuffer();
0312 
0313   // The underlying copying stream.
0314   CopyingOutputStream* copying_stream_;
0315   bool owns_copying_stream_;
0316 
0317   // True if we have seen a permanent error from the underlying stream.
0318   bool failed_;
0319 
0320   // The current position of copying_stream_, relative to the point where
0321   // we started writing.
0322   int64_t position_;
0323 
0324   // Data is written from this buffer.  It may be NULL if no buffer is
0325   // currently in use.  Otherwise, it points to an array of size buffer_size_.
0326   std::unique_ptr<uint8_t[]> buffer_;
0327   const int buffer_size_;
0328 
0329   // Number of valid bytes currently in the buffer (i.e. the size last
0330   // returned by Next()).  When BackUp() is called, we just reduce this.
0331   // 0 <= buffer_used_ <= buffer_size_.
0332   int buffer_used_;
0333 };
0334 
0335 // ===================================================================
0336 
0337 // A ZeroCopyInputStream which wraps some other stream and limits it to
0338 // a particular byte count.
0339 class PROTOBUF_EXPORT LimitingInputStream final : public ZeroCopyInputStream {
0340  public:
0341   LimitingInputStream(ZeroCopyInputStream* input, int64_t limit);
0342   ~LimitingInputStream() override;
0343 
0344   // `LimitingInputStream` is neither copiable nor assignable
0345   LimitingInputStream(const LimitingInputStream&) = delete;
0346   LimitingInputStream& operator=(const LimitingInputStream&) = delete;
0347 
0348   // implements ZeroCopyInputStream ----------------------------------
0349   bool Next(const void** data, int* size) override;
0350   void BackUp(int count) override;
0351   bool Skip(int count) override;
0352   int64_t ByteCount() const override;
0353   bool ReadCord(absl::Cord* cord, int count) override;
0354 
0355 
0356  private:
0357   ZeroCopyInputStream* input_;
0358   int64_t limit_;  // Decreases as we go, becomes negative if we overshoot.
0359   int64_t prior_bytes_read_;  // Bytes read on underlying stream at construction
0360 };
0361 
0362 // ===================================================================
0363 
0364 // A ZeroCopyInputStream backed by a Cord.  This stream implements ReadCord()
0365 // in a way that can share memory between the source and destination cords
0366 // rather than copying.
0367 class PROTOBUF_EXPORT CordInputStream final : public ZeroCopyInputStream {
0368  public:
0369   // Creates an InputStream that reads from the given Cord. `cord` must
0370   // not be null and must outlive this CordInputStream instance. `cord` must
0371   // not be modified while this instance is actively being used: any change
0372   // to `cord` will lead to undefined behavior on any subsequent call into
0373   // this instance.
0374   explicit CordInputStream(
0375       const absl::Cord* cord ABSL_ATTRIBUTE_LIFETIME_BOUND);
0376 
0377 
0378   // `CordInputStream` is neither copiable nor assignable
0379   CordInputStream(const CordInputStream&) = delete;
0380   CordInputStream& operator=(const CordInputStream&) = delete;
0381 
0382   // implements ZeroCopyInputStream ----------------------------------
0383   bool Next(const void** data, int* size) override;
0384   void BackUp(int count) override;
0385   bool Skip(int count) override;
0386   int64_t ByteCount() const override;
0387   bool ReadCord(absl::Cord* cord, int count) override;
0388 
0389 
0390  private:
0391   // Moves `it_` to the next available chunk skipping `skip` extra bytes
0392   // and updates the chunk data pointers.
0393   bool NextChunk(size_t skip);
0394 
0395   // Updates the current chunk data context `data_`, `size_` and `available_`.
0396   // If `bytes_remaining_` is zero, sets `size_` and `available_` to zero.
0397   // Returns true if more data is available, false otherwise.
0398   bool LoadChunkData();
0399 
0400   absl::Cord::CharIterator it_;
0401   size_t length_;
0402   size_t bytes_remaining_;
0403   const char* data_;
0404   size_t size_;
0405   size_t available_;
0406 };
0407 
0408 // ===================================================================
0409 
0410 // A ZeroCopyOutputStream that writes to a Cord.  This stream implements
0411 // WriteCord() in a way that can share memory between the source and
0412 // destination cords rather than copying.
0413 class PROTOBUF_EXPORT CordOutputStream final : public ZeroCopyOutputStream {
0414  public:
0415   // Creates an OutputStream streaming serialized data into a Cord. `size_hint`,
0416   // if given, is the expected total size of the resulting Cord. This is a hint
0417   // only, used for optimization. Callers can obtain the generated Cord value by
0418   // invoking `Consume()`.
0419   explicit CordOutputStream(size_t size_hint = 0);
0420 
0421   // Creates an OutputStream with an initial Cord value. This constructor can be
0422   // used by applications wanting to directly append serialization data to a
0423   // given cord. In such cases, donating the existing value as in:
0424   //
0425   //   CordOutputStream stream(std::move(cord));
0426   //   message.SerializeToZeroCopyStream(&stream);
0427   //   cord = std::move(stream.Consume());
0428   //
0429   // is more efficient then appending the serialized cord in application code:
0430   //
0431   //   CordOutputStream stream;
0432   //   message.SerializeToZeroCopyStream(&stream);
0433   //   cord.Append(stream.Consume());
0434   //
0435   // The former allows `CordOutputStream` to utilize pre-existing privately
0436   // owned Cord buffers from the donated cord where the latter does not, which
0437   // may lead to more memory usage when serialuzing data into existing cords.
0438   explicit CordOutputStream(absl::Cord cord, size_t size_hint = 0);
0439 
0440   // Creates an OutputStream with an initial Cord value and initial buffer.
0441   // This donates both the preexisting cord in `cord`, as well as any
0442   // pre-existing data and additional capacity in `buffer`.
0443   // This function is mainly intended to be used in internal serialization logic
0444   // using eager buffer initialization in EpsCopyOutputStream.
0445   // The donated buffer can be empty, partially empty or full: the outputstream
0446   // will DTRT in all cases and preserve any pre-existing data.
0447   explicit CordOutputStream(absl::Cord cord, absl::CordBuffer buffer,
0448                             size_t size_hint = 0);
0449 
0450   // Creates an OutputStream with an initial buffer.
0451   // This method is logically identical to, but more efficient than:
0452   //   `CordOutputStream(absl::Cord(), std::move(buffer), size_hint)`
0453   explicit CordOutputStream(absl::CordBuffer buffer, size_t size_hint = 0);
0454 
0455   // `CordOutputStream` is neither copiable nor assignable
0456   CordOutputStream(const CordOutputStream&) = delete;
0457   CordOutputStream& operator=(const CordOutputStream&) = delete;
0458 
0459   // implements `ZeroCopyOutputStream` ---------------------------------
0460   bool Next(void** data, int* size) final;
0461   void BackUp(int count) final;
0462   int64_t ByteCount() const final;
0463   bool WriteCord(const absl::Cord& cord) final;
0464 
0465   // Consumes the serialized data as a cord value. `Consume()` internally
0466   // flushes any pending state 'as if' BackUp(0) was called. While a final call
0467   // to BackUp() is generally required by the `ZeroCopyOutputStream` contract,
0468   // applications using `CordOutputStream` directly can call `Consume()` without
0469   // a preceding call to `BackUp()`.
0470   //
0471   // While it will rarely be useful in practice (and especially in the presence
0472   // of size hints) an instance is safe to be used after a call to `Consume()`.
0473   // The only logical change in state is that all serialized data is extracted,
0474   // and any new serialization calls will serialize into new cord data.
0475   absl::Cord Consume();
0476 
0477  private:
0478   // State of `buffer_` and 'cord_. As a default CordBuffer instance always has
0479   // inlined capacity, we track state explicitly to avoid returning 'existing
0480   // capacity' from the default or 'moved from' CordBuffer. 'kSteal' indicates
0481   // we should (attempt to) steal the next buffer from the cord.
0482   enum class State { kEmpty, kFull, kPartial, kSteal };
0483 
0484   absl::Cord cord_;
0485   size_t size_hint_;
0486   State state_ = State::kEmpty;
0487   absl::CordBuffer buffer_;
0488 };
0489 
0490 
0491 // ===================================================================
0492 
0493 // Return a pointer to mutable characters underlying the given string.  The
0494 // return value is valid until the next time the string is resized.  We
0495 // trust the caller to treat the return value as an array of length s->size().
0496 inline char* mutable_string_data(std::string* s) {
0497   return &(*s)[0];
0498 }
0499 
0500 // as_string_data(s) is equivalent to
0501 //  ({ char* p = mutable_string_data(s); make_pair(p, p != NULL); })
0502 // Sometimes it's faster: in some scenarios p cannot be NULL, and then the
0503 // code can avoid that check.
0504 inline std::pair<char*, bool> as_string_data(std::string* s) {
0505   char* p = mutable_string_data(s);
0506   return std::make_pair(p, true);
0507 }
0508 
0509 }  // namespace io
0510 }  // namespace protobuf
0511 }  // namespace google
0512 
0513 #include "google/protobuf/port_undef.inc"
0514 
0515 #endif  // GOOGLE_PROTOBUF_IO_ZERO_COPY_STREAM_IMPL_LITE_H__