bytestream.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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. // This file declares the ByteSink and ByteSource abstract interfaces. These
  31. // interfaces represent objects that consume (ByteSink) or produce (ByteSource)
  32. // a sequence of bytes. Using these abstract interfaces in your APIs can help
  33. // make your code work with a variety of input and output types.
  34. //
  35. // This file also declares the following commonly used implementations of these
  36. // interfaces.
  37. //
  38. // ByteSink:
  39. // UncheckedArrayByteSink Writes to an array, without bounds checking
  40. // CheckedArrayByteSink Writes to an array, with bounds checking
  41. // GrowingArrayByteSink Allocates and writes to a growable buffer
  42. // StringByteSink Writes to an STL string
  43. // NullByteSink Consumes a never-ending stream of bytes
  44. //
  45. // ByteSource:
  46. // ArrayByteSource Reads from an array or string/StringPiece
  47. // LimitedByteSource Limits the number of bytes read from an
  48. #ifndef GOOGLE_PROTOBUF_STUBS_BYTESTREAM_H_
  49. #define GOOGLE_PROTOBUF_STUBS_BYTESTREAM_H_
  50. #include <stddef.h>
  51. #include <string>
  52. #include <google/protobuf/stubs/common.h>
  53. #include <google/protobuf/stubs/stringpiece.h>
  54. #include <google/protobuf/port_def.inc>
  55. class CordByteSink;
  56. namespace google {
  57. namespace protobuf {
  58. namespace strings {
  59. // An abstract interface for an object that consumes a sequence of bytes. This
  60. // interface offers a way to append data as well as a Flush() function.
  61. //
  62. // Example:
  63. //
  64. // string my_data;
  65. // ...
  66. // ByteSink* sink = ...
  67. // sink->Append(my_data.data(), my_data.size());
  68. // sink->Flush();
  69. //
  70. class PROTOBUF_EXPORT ByteSink {
  71. public:
  72. ByteSink() {}
  73. virtual ~ByteSink() {}
  74. // Appends the "n" bytes starting at "bytes".
  75. virtual void Append(const char* bytes, size_t n) = 0;
  76. // Flushes internal buffers. The default implementation does nothing. ByteSink
  77. // subclasses may use internal buffers that require calling Flush() at the end
  78. // of the stream.
  79. virtual void Flush();
  80. private:
  81. GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ByteSink);
  82. };
  83. // An abstract interface for an object that produces a fixed-size sequence of
  84. // bytes.
  85. //
  86. // Example:
  87. //
  88. // ByteSource* source = ...
  89. // while (source->Available() > 0) {
  90. // StringPiece data = source->Peek();
  91. // ... do something with "data" ...
  92. // source->Skip(data.length());
  93. // }
  94. //
  95. class PROTOBUF_EXPORT ByteSource {
  96. public:
  97. ByteSource() {}
  98. virtual ~ByteSource() {}
  99. // Returns the number of bytes left to read from the source. Available()
  100. // should decrease by N each time Skip(N) is called. Available() may not
  101. // increase. Available() returning 0 indicates that the ByteSource is
  102. // exhausted.
  103. //
  104. // Note: Size() may have been a more appropriate name as it's more
  105. // indicative of the fixed-size nature of a ByteSource.
  106. virtual size_t Available() const = 0;
  107. // Returns a StringPiece of the next contiguous region of the source. Does not
  108. // reposition the source. The returned region is empty iff Available() == 0.
  109. //
  110. // The returned region is valid until the next call to Skip() or until this
  111. // object is destroyed, whichever occurs first.
  112. //
  113. // The length of the returned StringPiece will be <= Available().
  114. virtual StringPiece Peek() = 0;
  115. // Skips the next n bytes. Invalidates any StringPiece returned by a previous
  116. // call to Peek().
  117. //
  118. // REQUIRES: Available() >= n
  119. virtual void Skip(size_t n) = 0;
  120. // Writes the next n bytes in this ByteSource to the given ByteSink, and
  121. // advances this ByteSource past the copied bytes. The default implementation
  122. // of this method just copies the bytes normally, but subclasses might
  123. // override CopyTo to optimize certain cases.
  124. //
  125. // REQUIRES: Available() >= n
  126. virtual void CopyTo(ByteSink* sink, size_t n);
  127. private:
  128. GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ByteSource);
  129. };
  130. //
  131. // Some commonly used implementations of ByteSink
  132. //
  133. // Implementation of ByteSink that writes to an unsized byte array. No
  134. // bounds-checking is performed--it is the caller's responsibility to ensure
  135. // that the destination array is large enough.
  136. //
  137. // Example:
  138. //
  139. // char buf[10];
  140. // UncheckedArrayByteSink sink(buf);
  141. // sink.Append("hi", 2); // OK
  142. // sink.Append(data, 100); // WOOPS! Overflows buf[10].
  143. //
  144. class PROTOBUF_EXPORT UncheckedArrayByteSink : public ByteSink {
  145. public:
  146. explicit UncheckedArrayByteSink(char* dest) : dest_(dest) {}
  147. virtual void Append(const char* data, size_t n) override;
  148. // Returns the current output pointer so that a caller can see how many bytes
  149. // were produced.
  150. //
  151. // Note: this method is not part of the ByteSink interface.
  152. char* CurrentDestination() const { return dest_; }
  153. private:
  154. char* dest_;
  155. GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(UncheckedArrayByteSink);
  156. };
  157. // Implementation of ByteSink that writes to a sized byte array. This sink will
  158. // not write more than "capacity" bytes to outbuf. Once "capacity" bytes are
  159. // appended, subsequent bytes will be ignored and Overflowed() will return true.
  160. // Overflowed() does not cause a runtime error (i.e., it does not CHECK fail).
  161. //
  162. // Example:
  163. //
  164. // char buf[10];
  165. // CheckedArrayByteSink sink(buf, 10);
  166. // sink.Append("hi", 2); // OK
  167. // sink.Append(data, 100); // Will only write 8 more bytes
  168. //
  169. class PROTOBUF_EXPORT CheckedArrayByteSink : public ByteSink {
  170. public:
  171. CheckedArrayByteSink(char* outbuf, size_t capacity);
  172. virtual void Append(const char* bytes, size_t n) override;
  173. // Returns the number of bytes actually written to the sink.
  174. size_t NumberOfBytesWritten() const { return size_; }
  175. // Returns true if any bytes were discarded, i.e., if there was an
  176. // attempt to write more than 'capacity' bytes.
  177. bool Overflowed() const { return overflowed_; }
  178. private:
  179. char* outbuf_;
  180. const size_t capacity_;
  181. size_t size_;
  182. bool overflowed_;
  183. GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(CheckedArrayByteSink);
  184. };
  185. // Implementation of ByteSink that allocates an internal buffer (a char array)
  186. // and expands it as needed to accommodate appended data (similar to a string),
  187. // and allows the caller to take ownership of the internal buffer via the
  188. // GetBuffer() method. The buffer returned from GetBuffer() must be deleted by
  189. // the caller with delete[]. GetBuffer() also sets the internal buffer to be
  190. // empty, and subsequent appends to the sink will create a new buffer. The
  191. // destructor will free the internal buffer if GetBuffer() was not called.
  192. //
  193. // Example:
  194. //
  195. // GrowingArrayByteSink sink(10);
  196. // sink.Append("hi", 2);
  197. // sink.Append(data, n);
  198. // const char* buf = sink.GetBuffer(); // Ownership transferred
  199. // delete[] buf;
  200. //
  201. class PROTOBUF_EXPORT GrowingArrayByteSink : public strings::ByteSink {
  202. public:
  203. explicit GrowingArrayByteSink(size_t estimated_size);
  204. virtual ~GrowingArrayByteSink();
  205. virtual void Append(const char* bytes, size_t n) override;
  206. // Returns the allocated buffer, and sets nbytes to its size. The caller takes
  207. // ownership of the buffer and must delete it with delete[].
  208. char* GetBuffer(size_t* nbytes);
  209. private:
  210. void Expand(size_t amount);
  211. void ShrinkToFit();
  212. size_t capacity_;
  213. char* buf_;
  214. size_t size_;
  215. GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(GrowingArrayByteSink);
  216. };
  217. // Implementation of ByteSink that appends to the given string.
  218. // Existing contents of "dest" are not modified; new data is appended.
  219. //
  220. // Example:
  221. //
  222. // string dest = "Hello ";
  223. // StringByteSink sink(&dest);
  224. // sink.Append("World", 5);
  225. // assert(dest == "Hello World");
  226. //
  227. class PROTOBUF_EXPORT StringByteSink : public ByteSink {
  228. public:
  229. explicit StringByteSink(std::string* dest) : dest_(dest) {}
  230. virtual void Append(const char* data, size_t n) override;
  231. private:
  232. std::string* dest_;
  233. GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(StringByteSink);
  234. };
  235. // Implementation of ByteSink that discards all data.
  236. //
  237. // Example:
  238. //
  239. // NullByteSink sink;
  240. // sink.Append(data, data.size()); // All data ignored.
  241. //
  242. class PROTOBUF_EXPORT NullByteSink : public ByteSink {
  243. public:
  244. NullByteSink() {}
  245. void Append(const char* /*data*/, size_t /*n*/) override {}
  246. private:
  247. GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(NullByteSink);
  248. };
  249. //
  250. // Some commonly used implementations of ByteSource
  251. //
  252. // Implementation of ByteSource that reads from a StringPiece.
  253. //
  254. // Example:
  255. //
  256. // string data = "Hello";
  257. // ArrayByteSource source(data);
  258. // assert(source.Available() == 5);
  259. // assert(source.Peek() == "Hello");
  260. //
  261. class PROTOBUF_EXPORT ArrayByteSource : public ByteSource {
  262. public:
  263. explicit ArrayByteSource(StringPiece s) : input_(s) {}
  264. virtual size_t Available() const override;
  265. virtual StringPiece Peek() override;
  266. virtual void Skip(size_t n) override;
  267. private:
  268. StringPiece input_;
  269. GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ArrayByteSource);
  270. };
  271. // Implementation of ByteSource that wraps another ByteSource, limiting the
  272. // number of bytes returned.
  273. //
  274. // The caller maintains ownership of the underlying source, and may not use the
  275. // underlying source while using the LimitByteSource object. The underlying
  276. // source's pointer is advanced by n bytes every time this LimitByteSource
  277. // object is advanced by n.
  278. //
  279. // Example:
  280. //
  281. // string data = "Hello World";
  282. // ArrayByteSource abs(data);
  283. // assert(abs.Available() == data.size());
  284. //
  285. // LimitByteSource limit(abs, 5);
  286. // assert(limit.Available() == 5);
  287. // assert(limit.Peek() == "Hello");
  288. //
  289. class PROTOBUF_EXPORT LimitByteSource : public ByteSource {
  290. public:
  291. // Returns at most "limit" bytes from "source".
  292. LimitByteSource(ByteSource* source, size_t limit);
  293. virtual size_t Available() const override;
  294. virtual StringPiece Peek() override;
  295. virtual void Skip(size_t n) override;
  296. // We override CopyTo so that we can forward to the underlying source, in
  297. // case it has an efficient implementation of CopyTo.
  298. virtual void CopyTo(ByteSink* sink, size_t n) override;
  299. private:
  300. ByteSource* source_;
  301. size_t limit_;
  302. };
  303. } // namespace strings
  304. } // namespace protobuf
  305. } // namespace google
  306. #include <google/protobuf/port_undef.inc>
  307. #endif // GOOGLE_PROTOBUF_STUBS_BYTESTREAM_H_