Return the maximum available space from IOBufQueue::preallocate
[folly.git] / folly / experimental / io / IOBufQueue.h
1 /*
2  * Copyright 2012 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #ifndef FOLLY_IO_IOBUF_QUEUE_H
18 #define FOLLY_IO_IOBUF_QUEUE_H
19
20 #include "folly/experimental/io/IOBuf.h"
21
22 #include <stdexcept>
23 #include <string>
24
25 namespace folly {
26
27 /**
28  * An IOBufQueue encapsulates a chain of IOBufs and provides
29  * convenience functions to append data to the back of the chain
30  * and remove data from the front.
31  *
32  * You may also prepend data into the headroom of the first buffer in the
33  * chain, if any.
34  */
35 class IOBufQueue {
36  public:
37   struct Options {
38     Options() : cacheChainLength(false) { }
39     bool cacheChainLength;
40   };
41
42   /**
43    * Commonly used Options, currently the only possible value other than
44    * the default.
45    */
46   static Options cacheChainLength() {
47     Options options;
48     options.cacheChainLength = true;
49     return options;
50   }
51
52   explicit IOBufQueue(const Options& options = Options());
53
54   /**
55    * Return a space to prepend bytes and the amount of headroom available.
56    */
57   std::pair<void*, uint32_t> headroom();
58
59   /**
60    * Indicate that n bytes from the headroom have been used.
61    */
62   void markPrepended(uint32_t n);
63
64   /**
65    * Prepend an existing range; throws std::overflow_error if not enough
66    * room.
67    */
68   void prepend(const void* buf, uint32_t n);
69
70   /**
71    * Add a buffer or buffer chain to the end of this queue. The
72    * queue takes ownership of buf.
73    */
74   void append(std::unique_ptr<folly::IOBuf>&& buf);
75
76   /**
77    * Add a queue to the end of this queue. The queue takes ownership of
78    * all buffers from the other queue.
79    */
80   void append(IOBufQueue& other);
81   void append(IOBufQueue&& other) {
82     append(other);  // call lvalue reference overload, above
83   }
84
85   /**
86    * Copy len bytes, starting at buf, to the end of this queue.
87    * The caller retains ownership of the source data.
88    */
89   void append(const void* buf, size_t len);
90
91   /**
92    * Copy a string to the end of this queue.
93    * The caller retains ownership of the source data.
94    */
95   void append(const std::string& buf) {
96     append(buf.data(), buf.length());
97   }
98
99   /**
100    * Append a chain of IOBuf objects that point to consecutive regions
101    * within buf.
102    *
103    * Just like IOBuf::wrapBuffer, this should only be used when the caller
104    * knows ahead of time and can ensure that all IOBuf objects that will point
105    * to this buffer will be destroyed before the buffer itself is destroyed;
106    * all other caveats from wrapBuffer also apply.
107    *
108    * Every buffer except for the last will wrap exactly blockSize bytes.
109    * Importantly, this method may be used to wrap buffers larger than 4GB.
110    */
111   void wrapBuffer(const void* buf, size_t len,
112                   uint32_t blockSize=(1U << 31));  // default block size: 2GB
113
114   /**
115    * Obtain a writable block of contiguous bytes at the end of this
116    * queue, allocating more space if necessary.  The amount of space
117    * reserved will be at least min.  If min contiguous space is not
118    * available at the end of the queue, and IOBuf with size maxHint is
119    * appended to the chain and returned.  The actual available space
120    * may be larger than maxHint.
121    *
122    * If the caller subsequently writes anything into the returned space,
123    * it must call the postallocate() method.
124    *
125    * @return The starting address of the block and the length in bytes.
126    *
127    * @note The point of the preallocate()/postallocate() mechanism is
128    *       to support I/O APIs such as Thrift's TAsyncSocket::ReadCallback
129    *       that request a buffer from the application and then, in a later
130    *       callback, tell the application how much of the buffer they've
131    *       filled with data.
132    */
133   std::pair<void*,uint32_t> preallocate(uint32_t min, uint32_t maxHint);
134
135   /**
136    * Tell the queue that the caller has written data into the first n
137    * bytes provided by the previous preallocate() call.
138    *
139    * @note n should be less than or equal to the size returned by
140    *       preallocate().  If n is zero, the caller may skip the call
141    *       to postallocate().  If n is nonzero, the caller must not
142    *       invoke any other non-const methods on this IOBufQueue between
143    *       the call to preallocate and the call to postallocate().
144    */
145   void postallocate(uint32_t n);
146
147   /**
148    * Obtain a writable block of n contiguous bytes, allocating more space
149    * if necessary, and mark it as used.  The caller can fill it later.
150    */
151   void* allocate(uint32_t n) {
152     void* p = preallocate(n, n).first;
153     postallocate(n);
154     return p;
155   }
156
157   /**
158    * Split off the first n bytes of the queue into a separate IOBuf chain,
159    * and transfer ownership of the new chain to the caller.  The IOBufQueue
160    * retains ownership of everything after the split point.
161    *
162    * @warning If the split point lies in the middle of some IOBuf within
163    *          the chain, this function may, as an implementation detail,
164    *          clone that IOBuf.
165    *
166    * @throws std::underflow_error if n exceeds the number of bytes
167    *         in the queue.
168    */
169   std::unique_ptr<folly::IOBuf> split(size_t n);
170
171   /**
172    * Similar to IOBuf::trimStart, but works on the whole queue.  Will
173    * pop off buffers that have been completely trimmed.
174    */
175   void trimStart(size_t amount);
176
177   /**
178    * Similar to IOBuf::trimEnd, but works on the whole queue.  Will
179    * pop off buffers that have been completely trimmed.
180    */
181   void trimEnd(size_t amount);
182
183   /**
184    * Transfer ownership of the queue's entire IOBuf chain to the caller.
185    */
186   std::unique_ptr<folly::IOBuf> move() {
187     chainLength_ = 0;
188     return std::move(head_);
189   }
190
191   /**
192    * Access
193    */
194   const folly::IOBuf* front() const {
195     return head_.get();
196   }
197
198   /**
199    * Total chain length, only valid if cacheLength was specified in the
200    * constructor.
201    */
202   size_t chainLength() const {
203     if (!options_.cacheChainLength) {
204       throw std::invalid_argument("IOBufQueue: chain length not cached");
205     }
206     return chainLength_;
207   }
208
209   const Options& options() const {
210     return options_;
211   }
212
213   /** Movable */
214   IOBufQueue(IOBufQueue&&);
215   IOBufQueue& operator=(IOBufQueue&&);
216
217  private:
218   static const size_t kChainLengthNotCached = (size_t)-1;
219   /** Not copyable */
220   IOBufQueue(const IOBufQueue&) = delete;
221   IOBufQueue& operator=(const IOBufQueue&) = delete;
222
223   Options options_;
224   size_t chainLength_;
225   /** Everything that has been appended but not yet discarded or moved out */
226   std::unique_ptr<folly::IOBuf> head_;
227 };
228
229 } // folly
230
231 #endif // FOLLY_IO_IOBUF_QUEUE_H