1 // Protocol Buffers - Google's data interchange format
2 // Copyright 2008 Google Inc.  All rights reserved.
3 // https://developers.google.com/protocol-buffers/
4 //
5 // Redistribution and use in source and binary forms, with or without
6 // modification, are permitted provided that the following conditions are
7 // met:
8 //
9 //     * Redistributions of source code must retain the above copyright
10 // notice, this list of conditions and the following disclaimer.
11 //     * Redistributions in binary form must reproduce the above
12 // copyright notice, this list of conditions and the following disclaimer
13 // in the documentation and/or other materials provided with the
14 // distribution.
15 //     * Neither the name of Google Inc. nor the names of its
16 // contributors may be used to endorse or promote products derived from
17 // this software without specific prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 
31 // Author: kenton@google.com (Kenton Varda)
32 //  Based on original Protocol Buffers design by
33 //  Sanjay Ghemawat, Jeff Dean, and others.
34 //
35 // This file contains common implementations of the interfaces defined in
36 // zero_copy_stream.h which are included in the "lite" protobuf library.
37 // These implementations cover I/O on raw arrays and strings, as well as
38 // adaptors which make it easy to implement streams based on traditional
39 // streams.  Of course, many users will probably want to write their own
40 // implementations of these interfaces specific to the particular I/O
41 // abstractions they prefer to use, but these should cover the most common
42 // cases.
43 
44 #ifndef GOOGLE_PROTOBUF_IO_ZERO_COPY_STREAM_IMPL_LITE_H__
45 #define GOOGLE_PROTOBUF_IO_ZERO_COPY_STREAM_IMPL_LITE_H__
46 
47 
48 #include <iosfwd>
49 #include <memory>
50 #include <string>
51 #include <vector> /* Needed by GCC 4.9 on Android (see Bug 1186561) */
52 
53 #include <google/protobuf/stubs/callback.h>
54 #include <google/protobuf/stubs/common.h>
55 #include <google/protobuf/io/zero_copy_stream.h>
56 #include <google/protobuf/stubs/stl_util.h>
57 
58 
59 #include <google/protobuf/port_def.inc>
60 
61 namespace google {
62 namespace protobuf {
63 namespace io {
64 
65 // ===================================================================
66 
67 // A ZeroCopyInputStream backed by an in-memory array of bytes.
68 class PROTOBUF_EXPORT ArrayInputStream : public ZeroCopyInputStream {
69  public:
70   // Create an InputStream that returns the bytes pointed to by "data".
71   // "data" remains the property of the caller but must remain valid until
72   // the stream is destroyed.  If a block_size is given, calls to Next()
73   // will return data blocks no larger than the given size.  Otherwise, the
74   // first call to Next() returns the entire array.  block_size is mainly
75   // useful for testing; in production you would probably never want to set
76   // it.
77   ArrayInputStream(const void* data, int size, int block_size = -1);
78   ~ArrayInputStream() override = default;
79 
80   // implements ZeroCopyInputStream ----------------------------------
81   bool Next(const void** data, int* size) override;
82   void BackUp(int count) override;
83   bool Skip(int count) override;
84   int64_t ByteCount() const override;
85 
86 
87  private:
88   const uint8* const data_;  // The byte array.
89   const int size_;           // Total size of the array.
90   const int block_size_;     // How many bytes to return at a time.
91 
92   int position_;
93   int last_returned_size_;  // How many bytes we returned last time Next()
94                             // was called (used for error checking only).
95 
96   GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ArrayInputStream);
97 };
98 
99 // ===================================================================
100 
101 // A ZeroCopyOutputStream backed by an in-memory array of bytes.
102 class PROTOBUF_EXPORT ArrayOutputStream : public ZeroCopyOutputStream {
103  public:
104   // Create an OutputStream that writes to the bytes pointed to by "data".
105   // "data" remains the property of the caller but must remain valid until
106   // the stream is destroyed.  If a block_size is given, calls to Next()
107   // will return data blocks no larger than the given size.  Otherwise, the
108   // first call to Next() returns the entire array.  block_size is mainly
109   // useful for testing; in production you would probably never want to set
110   // it.
111   ArrayOutputStream(void* data, int size, int block_size = -1);
112   ~ArrayOutputStream() override = default;
113 
114   // implements ZeroCopyOutputStream ---------------------------------
115   bool Next(void** data, int* size) override;
116   void BackUp(int count) override;
117   int64_t ByteCount() const override;
118 
119  private:
120   uint8* const data_;     // The byte array.
121   const int size_;        // Total size of the array.
122   const int block_size_;  // How many bytes to return at a time.
123 
124   int position_;
125   int last_returned_size_;  // How many bytes we returned last time Next()
126                             // was called (used for error checking only).
127 
128   GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ArrayOutputStream);
129 };
130 
131 // ===================================================================
132 
133 // A ZeroCopyOutputStream which appends bytes to a string.
134 class PROTOBUF_EXPORT StringOutputStream : public ZeroCopyOutputStream {
135  public:
136   // Create a StringOutputStream which appends bytes to the given string.
137   // The string remains property of the caller, but it is mutated in arbitrary
138   // ways and MUST NOT be accessed in any way until you're done with the
139   // stream. Either be sure there's no further usage, or (safest) destroy the
140   // stream before using the contents.
141   //
142   // Hint:  If you call target->reserve(n) before creating the stream,
143   //   the first call to Next() will return at least n bytes of buffer
144   //   space.
145   explicit StringOutputStream(std::string* target);
146   ~StringOutputStream() override = default;
147 
148   // implements ZeroCopyOutputStream ---------------------------------
149   bool Next(void** data, int* size) override;
150   void BackUp(int count) override;
151   int64_t ByteCount() const override;
152 
153  private:
154   static const int kMinimumSize = 16;
155 
156   std::string* target_;
157 
158   GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(StringOutputStream);
159 };
160 
161 // Note:  There is no StringInputStream.  Instead, just create an
162 // ArrayInputStream as follows:
163 //   ArrayInputStream input(str.data(), str.size());
164 
165 // ===================================================================
166 
167 // A generic traditional input stream interface.
168 //
169 // Lots of traditional input streams (e.g. file descriptors, C stdio
170 // streams, and C++ iostreams) expose an interface where every read
171 // involves copying bytes into a buffer.  If you want to take such an
172 // interface and make a ZeroCopyInputStream based on it, simply implement
173 // CopyingInputStream and then use CopyingInputStreamAdaptor.
174 //
175 // CopyingInputStream implementations should avoid buffering if possible.
176 // CopyingInputStreamAdaptor does its own buffering and will read data
177 // in large blocks.
178 class PROTOBUF_EXPORT CopyingInputStream {
179  public:
~CopyingInputStream()180   virtual ~CopyingInputStream() {}
181 
182   // Reads up to "size" bytes into the given buffer.  Returns the number of
183   // bytes read.  Read() waits until at least one byte is available, or
184   // returns zero if no bytes will ever become available (EOF), or -1 if a
185   // permanent read error occurred.
186   virtual int Read(void* buffer, int size) = 0;
187 
188   // Skips the next "count" bytes of input.  Returns the number of bytes
189   // actually skipped.  This will always be exactly equal to "count" unless
190   // EOF was reached or a permanent read error occurred.
191   //
192   // The default implementation just repeatedly calls Read() into a scratch
193   // buffer.
194   virtual int Skip(int count);
195 };
196 
197 // A ZeroCopyInputStream which reads from a CopyingInputStream.  This is
198 // useful for implementing ZeroCopyInputStreams that read from traditional
199 // streams.  Note that this class is not really zero-copy.
200 //
201 // If you want to read from file descriptors or C++ istreams, this is
202 // already implemented for you:  use FileInputStream or IstreamInputStream
203 // respectively.
204 class PROTOBUF_EXPORT CopyingInputStreamAdaptor : public ZeroCopyInputStream {
205  public:
206   // Creates a stream that reads from the given CopyingInputStream.
207   // If a block_size is given, it specifies the number of bytes that
208   // should be read and returned with each call to Next().  Otherwise,
209   // a reasonable default is used.  The caller retains ownership of
210   // copying_stream unless SetOwnsCopyingStream(true) is called.
211   explicit CopyingInputStreamAdaptor(CopyingInputStream* copying_stream,
212                                      int block_size = -1);
213   ~CopyingInputStreamAdaptor() override;
214 
215   // Call SetOwnsCopyingStream(true) to tell the CopyingInputStreamAdaptor to
216   // delete the underlying CopyingInputStream when it is destroyed.
SetOwnsCopyingStream(bool value)217   void SetOwnsCopyingStream(bool value) { owns_copying_stream_ = value; }
218 
219   // implements ZeroCopyInputStream ----------------------------------
220   bool Next(const void** data, int* size) override;
221   void BackUp(int count) override;
222   bool Skip(int count) override;
223   int64_t ByteCount() const override;
224 
225  private:
226   // Insures that buffer_ is not NULL.
227   void AllocateBufferIfNeeded();
228   // Frees the buffer and resets buffer_used_.
229   void FreeBuffer();
230 
231   // The underlying copying stream.
232   CopyingInputStream* copying_stream_;
233   bool owns_copying_stream_;
234 
235   // True if we have seen a permenant error from the underlying stream.
236   bool failed_;
237 
238   // The current position of copying_stream_, relative to the point where
239   // we started reading.
240   int64 position_;
241 
242   // Data is read into this buffer.  It may be NULL if no buffer is currently
243   // in use.  Otherwise, it points to an array of size buffer_size_.
244   std::unique_ptr<uint8[]> buffer_;
245   const int buffer_size_;
246 
247   // Number of valid bytes currently in the buffer (i.e. the size last
248   // returned by Next()).  0 <= buffer_used_ <= buffer_size_.
249   int buffer_used_;
250 
251   // Number of bytes in the buffer which were backed up over by a call to
252   // BackUp().  These need to be returned again.
253   // 0 <= backup_bytes_ <= buffer_used_
254   int backup_bytes_;
255 
256   GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(CopyingInputStreamAdaptor);
257 };
258 
259 // ===================================================================
260 
261 // A generic traditional output stream interface.
262 //
263 // Lots of traditional output streams (e.g. file descriptors, C stdio
264 // streams, and C++ iostreams) expose an interface where every write
265 // involves copying bytes from a buffer.  If you want to take such an
266 // interface and make a ZeroCopyOutputStream based on it, simply implement
267 // CopyingOutputStream and then use CopyingOutputStreamAdaptor.
268 //
269 // CopyingOutputStream implementations should avoid buffering if possible.
270 // CopyingOutputStreamAdaptor does its own buffering and will write data
271 // in large blocks.
272 class PROTOBUF_EXPORT CopyingOutputStream {
273  public:
~CopyingOutputStream()274   virtual ~CopyingOutputStream() {}
275 
276   // Writes "size" bytes from the given buffer to the output.  Returns true
277   // if successful, false on a write error.
278   virtual bool Write(const void* buffer, int size) = 0;
279 };
280 
281 // A ZeroCopyOutputStream which writes to a CopyingOutputStream.  This is
282 // useful for implementing ZeroCopyOutputStreams that write to traditional
283 // streams.  Note that this class is not really zero-copy.
284 //
285 // If you want to write to file descriptors or C++ ostreams, this is
286 // already implemented for you:  use FileOutputStream or OstreamOutputStream
287 // respectively.
288 class PROTOBUF_EXPORT CopyingOutputStreamAdaptor : public ZeroCopyOutputStream {
289  public:
290   // Creates a stream that writes to the given Unix file descriptor.
291   // If a block_size is given, it specifies the size of the buffers
292   // that should be returned by Next().  Otherwise, a reasonable default
293   // is used.
294   explicit CopyingOutputStreamAdaptor(CopyingOutputStream* copying_stream,
295                                       int block_size = -1);
296   ~CopyingOutputStreamAdaptor() override;
297 
298   // Writes all pending data to the underlying stream.  Returns false if a
299   // write error occurred on the underlying stream.  (The underlying
300   // stream itself is not necessarily flushed.)
301   bool Flush();
302 
303   // Call SetOwnsCopyingStream(true) to tell the CopyingOutputStreamAdaptor to
304   // delete the underlying CopyingOutputStream when it is destroyed.
SetOwnsCopyingStream(bool value)305   void SetOwnsCopyingStream(bool value) { owns_copying_stream_ = value; }
306 
307   // implements ZeroCopyOutputStream ---------------------------------
308   bool Next(void** data, int* size) override;
309   void BackUp(int count) override;
310   int64_t ByteCount() const override;
311 
312  private:
313   // Write the current buffer, if it is present.
314   bool WriteBuffer();
315   // Insures that buffer_ is not NULL.
316   void AllocateBufferIfNeeded();
317   // Frees the buffer.
318   void FreeBuffer();
319 
320   // The underlying copying stream.
321   CopyingOutputStream* copying_stream_;
322   bool owns_copying_stream_;
323 
324   // True if we have seen a permenant error from the underlying stream.
325   bool failed_;
326 
327   // The current position of copying_stream_, relative to the point where
328   // we started writing.
329   int64 position_;
330 
331   // Data is written from this buffer.  It may be NULL if no buffer is
332   // currently in use.  Otherwise, it points to an array of size buffer_size_.
333   std::unique_ptr<uint8[]> buffer_;
334   const int buffer_size_;
335 
336   // Number of valid bytes currently in the buffer (i.e. the size last
337   // returned by Next()).  When BackUp() is called, we just reduce this.
338   // 0 <= buffer_used_ <= buffer_size_.
339   int buffer_used_;
340 
341   GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(CopyingOutputStreamAdaptor);
342 };
343 
344 // ===================================================================
345 
346 // A ZeroCopyInputStream which wraps some other stream and limits it to
347 // a particular byte count.
348 class PROTOBUF_EXPORT LimitingInputStream : public ZeroCopyInputStream {
349  public:
350   LimitingInputStream(ZeroCopyInputStream* input, int64 limit);
351   ~LimitingInputStream() override;
352 
353   // implements ZeroCopyInputStream ----------------------------------
354   bool Next(const void** data, int* size) override;
355   void BackUp(int count) override;
356   bool Skip(int count) override;
357   int64_t ByteCount() const override;
358 
359 
360  private:
361   ZeroCopyInputStream* input_;
362   int64 limit_;  // Decreases as we go, becomes negative if we overshoot.
363   int64 prior_bytes_read_;  // Bytes read on underlying stream at construction
364 
365   GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(LimitingInputStream);
366 };
367 
368 
369 // ===================================================================
370 
371 // mutable_string_data() and as_string_data() are workarounds to improve
372 // the performance of writing new data to an existing string.  Unfortunately
373 // the methods provided by the string class are suboptimal, and using memcpy()
374 // is mildly annoying because it requires its pointer args to be non-NULL even
375 // if we ask it to copy 0 bytes.  Furthermore, string_as_array() has the
376 // property that it always returns NULL if its arg is the empty string, exactly
377 // what we want to avoid if we're using it in conjunction with memcpy()!
378 // With C++11, the desired memcpy() boils down to memcpy(..., &(*s)[0], size),
379 // where s is a string*.  Without C++11, &(*s)[0] is not guaranteed to be safe,
380 // so we use string_as_array(), and live with the extra logic that tests whether
381 // *s is empty.
382 
383 // Return a pointer to mutable characters underlying the given string.  The
384 // return value is valid until the next time the string is resized.  We
385 // trust the caller to treat the return value as an array of length s->size().
mutable_string_data(std::string * s)386 inline char* mutable_string_data(std::string* s) {
387   // This should be simpler & faster than string_as_array() because the latter
388   // is guaranteed to return NULL when *s is empty, so it has to check for that.
389   return &(*s)[0];
390 }
391 
392 // as_string_data(s) is equivalent to
393 //  ({ char* p = mutable_string_data(s); make_pair(p, p != NULL); })
394 // Sometimes it's faster: in some scenarios p cannot be NULL, and then the
395 // code can avoid that check.
as_string_data(std::string * s)396 inline std::pair<char*, bool> as_string_data(std::string* s) {
397   char* p = mutable_string_data(s);
398   return std::make_pair(p, true);
399 }
400 
401 }  // namespace io
402 }  // namespace protobuf
403 }  // namespace google
404 
405 #include <google/protobuf/port_undef.inc>
406 
407 #endif  // GOOGLE_PROTOBUF_IO_ZERO_COPY_STREAM_IMPL_LITE_H__
408