Minor changes to folly/experimental/io
[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 class IOBufQueue {
33  public:
34   struct Options {
35     Options() : cacheChainLength(false) { }
36     bool cacheChainLength;
37   };
38
39   /**
40    * Commonly used Options, currently the only possible value other than
41    * the default.
42    */
43   static Options cacheChainLength() {
44     Options options;
45     options.cacheChainLength = true;
46     return options;
47   }
48
49   explicit IOBufQueue(const Options& options = Options());
50
51   /**
52    * Add a buffer or buffer chain to the end of this queue. The
53    * queue takes ownership of buf.
54    */
55   void append(std::unique_ptr<folly::IOBuf>&& buf);
56
57   /**
58    * Add a queue to the end of this queue. The queue takes ownership of
59    * all buffers from the other queue.
60    */
61   void append(IOBufQueue& other);
62   void append(IOBufQueue&& other) {
63     append(other);  // call lvalue reference overload, above
64   }
65
66   /**
67    * Copy len bytes, starting at buf, to the end of this queue.
68    * The caller retains ownership of the source data.
69    */
70   void append(const void* buf, size_t len);
71
72   /**
73    * Copy a string to the end of this queue.
74    * The caller retains ownership of the source data.
75    */
76   void append(const std::string& buf) {
77     append(buf.data(), buf.length());
78   }
79
80   /**
81    * Append a chain of IOBuf objects that point to consecutive regions
82    * within buf.
83    *
84    * Just like IOBuf::wrapBuffer, this should only be used when the caller
85    * knows ahead of time and can ensure that all IOBuf objects that will point
86    * to this buffer will be destroyed before the buffer itself is destroyed;
87    * all other caveats from wrapBuffer also apply.
88    *
89    * Every buffer except for the last will wrap exactly blockSize bytes.
90    * Importantly, this method may be used to wrap buffers larger than 4GB.
91    */
92   void wrapBuffer(const void* buf, size_t len,
93                   uint32_t blockSize=(1U << 31));  // default block size: 2GB
94
95   /**
96    * Obtain a writable block of contiguous bytes at the end of this
97    * queue, allocating more space if necessary.  The amount of space
98    * reserved will be between min and max, inclusive; the IOBufQueue
99    * implementation may pick a value in that range that makes efficient
100    * use of already-allocated internal space.
101    *
102    * If the caller subsequently writes anything into the returned space,
103    * it must call the postallocate() method.
104    *
105    * @return The starting address of the block and the length in bytes.
106    *
107    * @note The point of the preallocate()/postallocate() mechanism is
108    *       to support I/O APIs such as Thrift's TAsyncSocket::ReadCallback
109    *       that request a buffer from the application and then, in a later
110    *       callback, tell the application how much of the buffer they've
111    *       filled with data.
112    */
113   std::pair<void*,uint32_t> preallocate(uint32_t min, uint32_t max);
114
115   /**
116    * Tell the queue that the caller has written data into the first n
117    * bytes provided by the previous preallocate() call.
118    *
119    * @note n should be less than or equal to the size returned by
120    *       preallocate().  If n is zero, the caller may skip the call
121    *       to postallocate().  If n is nonzero, the caller must not
122    *       invoke any other non-const methods on this IOBufQueue between
123    *       the call to preallocate and the call to postallocate().
124    */
125   void postallocate(uint32_t n);
126
127   /**
128    * Obtain a writable block of n contiguous bytes, allocating more space
129    * if necessary, and mark it as used.  The caller can fill it later.
130    */
131   void* allocate(uint32_t n) {
132     void* p = preallocate(n, n).first;
133     postallocate(n);
134     return p;
135   }
136
137   /**
138    * Split off the first n bytes of the queue into a separate IOBuf chain,
139    * and transfer ownership of the new chain to the caller.  The IOBufQueue
140    * retains ownership of everything after the split point.
141    *
142    * @warning If the split point lies in the middle of some IOBuf within
143    *          the chain, this function may, as an implementation detail,
144    *          clone that IOBuf.
145    *
146    * @throws std::underflow_error if n exceeds the number of bytes
147    *         in the queue.
148    */
149   std::unique_ptr<folly::IOBuf> split(size_t n);
150
151   /**
152    * Similar to IOBuf::trimStart, but works on the whole queue.  Will
153    * pop off buffers that have been completely trimmed.
154    */
155   void trimStart(size_t amount);
156
157   /**
158    * Similar to IOBuf::trimEnd, but works on the whole queue.  Will
159    * pop off buffers that have been completely trimmed.
160    */
161   void trimEnd(size_t amount);
162
163   /**
164    * Transfer ownership of the queue's entire IOBuf chain to the caller.
165    */
166   std::unique_ptr<folly::IOBuf>&& move() {
167     chainLength_ = 0;
168     return std::move(head_);
169   }
170
171   /**
172    * Access
173    */
174   const folly::IOBuf* front() const {
175     return head_.get();
176   }
177
178   /**
179    * Total chain length, only valid if cacheLength was specified in the
180    * constructor.
181    */
182   size_t chainLength() const {
183     if (!options_.cacheChainLength) {
184       throw std::invalid_argument("IOBufQueue: chain length not cached");
185     }
186     return chainLength_;
187   }
188
189   const Options& options() const {
190     return options_;
191   }
192
193   /** Movable */
194   IOBufQueue(IOBufQueue&&);
195   IOBufQueue& operator=(IOBufQueue&&);
196
197  private:
198   static const size_t kChainLengthNotCached = (size_t)-1;
199   /** Not copyable */
200   IOBufQueue(const IOBufQueue&) = delete;
201   IOBufQueue& operator=(const IOBufQueue&) = delete;
202
203   Options options_;
204   size_t chainLength_;
205   /** Everything that has been appended but not yet discarded or moved out */
206   std::unique_ptr<folly::IOBuf> head_;
207 };
208
209 } // folly
210
211 #endif // FOLLY_IO_IOBUF_QUEUE_H