move assignment operators for folly::Synchronized
[folly.git] / folly / io / IOBuf.h
1 /*
2  * Copyright 2013 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_H_
18 #define FOLLY_IO_IOBUF_H_
19
20 #include <glog/logging.h>
21 #include <atomic>
22 #include <cassert>
23 #include <cinttypes>
24 #include <cstddef>
25 #include <cstring>
26 #include <memory>
27 #include <limits>
28 #include <sys/uio.h>
29 #include <type_traits>
30
31 #include <boost/iterator/iterator_facade.hpp>
32
33 #include "folly/FBString.h"
34 #include "folly/Range.h"
35 #include "folly/FBVector.h"
36
37 // Ignore shadowing warnings within this file, so includers can use -Wshadow.
38 #pragma GCC diagnostic push
39 #pragma GCC diagnostic ignored "-Wshadow"
40
41 namespace folly {
42
43 /**
44  * An IOBuf is a pointer to a buffer of data.
45  *
46  * IOBuf objects are intended to be used primarily for networking code, and are
47  * modelled somewhat after FreeBSD's mbuf data structure, and Linux's sk_buff
48  * structure.
49  *
50  * IOBuf objects facilitate zero-copy network programming, by allowing multiple
51  * IOBuf objects to point to the same underlying buffer of data, using a
52  * reference count to track when the buffer is no longer needed and can be
53  * freed.
54  *
55  *
56  * Data Layout
57  * -----------
58  *
59  * The IOBuf itself is a small object containing a pointer to the buffer and
60  * information about which segment of the buffer contains valid data.
61  *
62  * The data layout looks like this:
63  *
64  *  +-------+
65  *  | IOBuf |
66  *  +-------+
67  *   /
68  *  |
69  *  v
70  *  +------------+--------------------+-----------+
71  *  | headroom   |        data        |  tailroom |
72  *  +------------+--------------------+-----------+
73  *  ^            ^                    ^           ^
74  *  buffer()   data()               tail()      bufferEnd()
75  *
76  *  The length() method returns the length of the valid data; capacity()
77  *  returns the entire capacity of the buffer (from buffer() to bufferEnd()).
78  *  The headroom() and tailroom() methods return the amount of unused capacity
79  *  available before and after the data.
80  *
81  *
82  * Buffer Sharing
83  * --------------
84  *
85  * The buffer itself is reference counted, and multiple IOBuf objects may point
86  * to the same buffer.  Each IOBuf may point to a different section of valid
87  * data within the underlying buffer.  For example, if multiple protocol
88  * requests are read from the network into a single buffer, a separate IOBuf
89  * may be created for each request, all sharing the same underlying buffer.
90  *
91  * In other words, when multiple IOBufs share the same underlying buffer, the
92  * data() and tail() methods on each IOBuf may point to a different segment of
93  * the data.  However, the buffer() and bufferEnd() methods will point to the
94  * same location for all IOBufs sharing the same underlying buffer.
95  *
96  *       +-----------+     +---------+
97  *       |  IOBuf 1  |     | IOBuf 2 |
98  *       +-----------+     +---------+
99  *        |         | _____/        |
100  *   data |    tail |/    data      | tail
101  *        v         v               v
102  *  +-------------------------------------+
103  *  |     |         |               |     |
104  *  +-------------------------------------+
105  *
106  * If you only read data from an IOBuf, you don't need to worry about other
107  * IOBuf objects possibly sharing the same underlying buffer.  However, if you
108  * ever write to the buffer you need to first ensure that no other IOBufs point
109  * to the same buffer.  The unshare() method may be used to ensure that you
110  * have an unshared buffer.
111  *
112  *
113  * IOBuf Chains
114  * ------------
115  *
116  * IOBuf objects also contain pointers to next and previous IOBuf objects.
117  * This can be used to represent a single logical piece of data that its stored
118  * in non-contiguous chunks in separate buffers.
119  *
120  * A single IOBuf object can only belong to one chain at a time.
121  *
122  * IOBuf chains are always circular.  The "prev" pointer in the head of the
123  * chain points to the tail of the chain.  However, it is up to the user to
124  * decide which IOBuf is the head.  Internally the IOBuf code does not care
125  * which element is the head.
126  *
127  * The lifetime of all IOBufs in the chain are linked: when one element in the
128  * chain is deleted, all other chained elements are also deleted.  Conceptually
129  * it is simplest to treat this as if the head of the chain owns all other
130  * IOBufs in the chain.  When you delete the head of the chain, it will delete
131  * the other elements as well.  For this reason, prependChain() and
132  * appendChain() take ownership of of the new elements being added to this
133  * chain.
134  *
135  * When the coalesce() method is used to coalesce an entire IOBuf chain into a
136  * single IOBuf, all other IOBufs in the chain are eliminated and automatically
137  * deleted.  The unshare() method may coalesce the chain; if it does it will
138  * similarly delete all IOBufs eliminated from the chain.
139  *
140  * As discussed in the following section, it is up to the user to maintain a
141  * lock around the entire IOBuf chain if multiple threads need to access the
142  * chain.  IOBuf does not provide any internal locking.
143  *
144  *
145  * Synchronization
146  * ---------------
147  *
148  * When used in multithread programs, a single IOBuf object should only be used
149  * in a single thread at a time.  If a caller uses a single IOBuf across
150  * multiple threads the caller is responsible for using an external lock to
151  * synchronize access to the IOBuf.
152  *
153  * Two separate IOBuf objects may be accessed concurrently in separate threads
154  * without locking, even if they point to the same underlying buffer.  The
155  * buffer reference count is always accessed atomically, and no other
156  * operations should affect other IOBufs that point to the same data segment.
157  * The caller is responsible for using unshare() to ensure that the data buffer
158  * is not shared by other IOBufs before writing to it, and this ensures that
159  * the data itself is not modified in one thread while also being accessed from
160  * another thread.
161  *
162  * For IOBuf chains, no two IOBufs in the same chain should be accessed
163  * simultaneously in separate threads.  The caller must maintain a lock around
164  * the entire chain if the chain, or individual IOBufs in the chain, may be
165  * accessed by multiple threads.
166  *
167  *
168  * IOBuf Object Allocation/Sharing
169  * -------------------------------
170  *
171  * IOBuf objects themselves are always allocated on the heap.  The IOBuf
172  * constructors are private, so IOBuf objects may not be created on the stack.
173  * In part this is done since some IOBuf objects use small-buffer optimization
174  * and contain the buffer data immediately after the IOBuf object itself.  The
175  * coalesce() and unshare() methods also expect to be able to delete subsequent
176  * IOBuf objects in the chain if they are no longer needed due to coalescing.
177  *
178  * The IOBuf structure also does not provide room for an intrusive refcount on
179  * the IOBuf object itself, only the underlying data buffer is reference
180  * counted.  If users want to share the same IOBuf object between multiple
181  * parts of the code, they are responsible for managing this sharing on their
182  * own.  (For example, by using a shared_ptr.  Alternatively, users always have
183  * the option of using clone() to create a second IOBuf that points to the same
184  * underlying buffer.)
185  *
186  * With jemalloc, allocating small objects like IOBuf objects should be
187  * relatively fast, and the cost of allocating IOBuf objects on the heap and
188  * cloning new IOBufs should be relatively cheap.
189  */
190 namespace detail {
191 // Is T a unique_ptr<> to a standard-layout type?
192 template <class T, class Enable=void> struct IsUniquePtrToSL
193   : public std::false_type { };
194 template <class T, class D>
195 struct IsUniquePtrToSL<
196   std::unique_ptr<T, D>,
197   typename std::enable_if<std::is_standard_layout<T>::value>::type>
198   : public std::true_type { };
199 }  // namespace detail
200
201 class IOBuf {
202  public:
203   class Iterator;
204
205   typedef ByteRange value_type;
206   typedef Iterator iterator;
207   typedef Iterator const_iterator;
208
209   typedef void (*FreeFunction)(void* buf, void* userData);
210
211   /**
212    * Allocate a new IOBuf object with the requested capacity.
213    *
214    * Returns a new IOBuf object that must be (eventually) deleted by the
215    * caller.  The returned IOBuf may actually have slightly more capacity than
216    * requested.
217    *
218    * The data pointer will initially point to the start of the newly allocated
219    * buffer, and will have a data length of 0.
220    *
221    * Throws std::bad_alloc on error.
222    */
223   static std::unique_ptr<IOBuf> create(uint32_t capacity);
224
225   /**
226    * Allocate a new IOBuf chain with the requested total capacity, allocating
227    * no more than maxBufCapacity to each buffer.
228    */
229   static std::unique_ptr<IOBuf> createChain(
230       size_t totalCapacity, uint32_t maxBufCapacity);
231
232   /**
233    * Create a new IOBuf pointing to an existing data buffer.
234    *
235    * The new IOBuffer will assume ownership of the buffer, and free it by
236    * calling the specified FreeFunction when the last IOBuf pointing to this
237    * buffer is destroyed.  The function will be called with a pointer to the
238    * buffer as the first argument, and the supplied userData value as the
239    * second argument.  The free function must never throw exceptions.
240    *
241    * If no FreeFunction is specified, the buffer will be freed using free().
242    *
243    * The IOBuf data pointer will initially point to the start of the buffer,
244    *
245    * In the first version of this function, the length of data is unspecified
246    * and is initialized to the capacity of the buffer
247    *
248    * In the second version, the user specifies the valid length of data
249    * in the buffer
250    *
251    * On error, std::bad_alloc will be thrown.  If freeOnError is true (the
252    * default) the buffer will be freed before throwing the error.
253    */
254   static std::unique_ptr<IOBuf> takeOwnership(void* buf, uint32_t capacity,
255                                               FreeFunction freeFn = NULL,
256                                               void* userData = NULL,
257                                               bool freeOnError = true) {
258     return takeOwnership(buf, capacity, capacity, freeFn,
259                          userData, freeOnError);
260   }
261
262   static std::unique_ptr<IOBuf> takeOwnership(void* buf, uint32_t capacity,
263                                               uint32_t length,
264                                               FreeFunction freeFn = NULL,
265                                               void* userData = NULL,
266                                               bool freeOnError = true);
267
268   /**
269    * Create a new IOBuf pointing to an existing data buffer made up of
270    * count objects of a given standard-layout type.
271    *
272    * This is dangerous -- it is essentially equivalent to doing
273    * reinterpret_cast<unsigned char*> on your data -- but it's often useful
274    * for serialization / deserialization.
275    *
276    * The new IOBuffer will assume ownership of the buffer, and free it
277    * appropriately (by calling the UniquePtr's custom deleter, or by calling
278    * delete or delete[] appropriately if there is no custom deleter)
279    * when the buffer is destroyed.  The custom deleter, if any, must never
280    * throw exceptions.
281    *
282    * The IOBuf data pointer will initially point to the start of the buffer,
283    * and the length will be the full capacity of the buffer (count *
284    * sizeof(T)).
285    *
286    * On error, std::bad_alloc will be thrown, and the buffer will be freed
287    * before throwing the error.
288    */
289   template <class UniquePtr>
290   static typename std::enable_if<detail::IsUniquePtrToSL<UniquePtr>::value,
291                                  std::unique_ptr<IOBuf>>::type
292   takeOwnership(UniquePtr&& buf, size_t count=1);
293
294   /**
295    * Create a new IOBuf object that points to an existing user-owned buffer.
296    *
297    * This should only be used when the caller knows the lifetime of the IOBuf
298    * object ahead of time and can ensure that all IOBuf objects that will point
299    * to this buffer will be destroyed before the buffer itself is destroyed.
300    *
301    * This buffer will not be freed automatically when the last IOBuf
302    * referencing it is destroyed.  It is the caller's responsibility to free
303    * the buffer after the last IOBuf has been destroyed.
304    *
305    * The IOBuf data pointer will initially point to the start of the buffer,
306    * and the length will be the full capacity of the buffer.
307    *
308    * An IOBuf created using wrapBuffer() will always be reported as shared.
309    * unshare() may be used to create a writable copy of the buffer.
310    *
311    * On error, std::bad_alloc will be thrown.
312    */
313   static std::unique_ptr<IOBuf> wrapBuffer(const void* buf, uint32_t capacity);
314
315   /**
316    * Convenience function to create a new IOBuf object that copies data from a
317    * user-supplied buffer, optionally allocating a given amount of
318    * headroom and tailroom.
319    */
320   static std::unique_ptr<IOBuf> copyBuffer(const void* buf, uint32_t size,
321                                            uint32_t headroom=0,
322                                            uint32_t minTailroom=0);
323
324   /**
325    * Convenience function to create a new IOBuf object that copies data from a
326    * user-supplied string, optionally allocating a given amount of
327    * headroom and tailroom.
328    *
329    * Beware when attempting to invoke this function with a constant string
330    * literal and a headroom argument: you will likely end up invoking the
331    * version of copyBuffer() above.  IOBuf::copyBuffer("hello", 3) will treat
332    * the first argument as a const void*, and will invoke the version of
333    * copyBuffer() above, with the size argument of 3.
334    */
335   static std::unique_ptr<IOBuf> copyBuffer(const std::string& buf,
336                                            uint32_t headroom=0,
337                                            uint32_t minTailroom=0);
338
339   /**
340    * A version of copyBuffer() that returns a null pointer if the input string
341    * is empty.
342    */
343   static std::unique_ptr<IOBuf> maybeCopyBuffer(const std::string& buf,
344                                                 uint32_t headroom=0,
345                                                 uint32_t minTailroom=0);
346
347   /**
348    * Convenience function to free a chain of IOBufs held by a unique_ptr.
349    */
350   static void destroy(std::unique_ptr<IOBuf>&& data) {
351     auto destroyer = std::move(data);
352   }
353
354   /**
355    * Destroy this IOBuf.
356    *
357    * Deleting an IOBuf will automatically destroy all IOBufs in the chain.
358    * (See the comments above regarding the ownership model of IOBuf chains.
359    * All subsequent IOBufs in the chain are considered to be owned by the head
360    * of the chain.  Users should only explicitly delete the head of a chain.)
361    *
362    * When each individual IOBuf is destroyed, it will release its reference
363    * count on the underlying buffer.  If it was the last user of the buffer,
364    * the buffer will be freed.
365    */
366   ~IOBuf();
367
368   /**
369    * Check whether the chain is empty (i.e., whether the IOBufs in the
370    * chain have a total data length of zero).
371    *
372    * This method is semantically equivalent to
373    *   i->computeChainDataLength()==0
374    * but may run faster because it can short-circuit as soon as it
375    * encounters a buffer with length()!=0
376    */
377   bool empty() const;
378
379   /**
380    * Get the pointer to the start of the data.
381    */
382   const uint8_t* data() const {
383     return data_;
384   }
385
386   /**
387    * Get a writable pointer to the start of the data.
388    *
389    * The caller is responsible for calling unshare() first to ensure that it is
390    * actually safe to write to the buffer.
391    */
392   uint8_t* writableData() {
393     return data_;
394   }
395
396   /**
397    * Get the pointer to the end of the data.
398    */
399   const uint8_t* tail() const {
400     return data_ + length_;
401   }
402
403   /**
404    * Get a writable pointer to the end of the data.
405    *
406    * The caller is responsible for calling unshare() first to ensure that it is
407    * actually safe to write to the buffer.
408    */
409   uint8_t* writableTail() {
410     return data_ + length_;
411   }
412
413   /**
414    * Get the data length.
415    */
416   uint32_t length() const {
417     return length_;
418   }
419
420   /**
421    * Get the amount of head room.
422    *
423    * Returns the number of bytes in the buffer before the start of the data.
424    */
425   uint32_t headroom() const {
426     return data_ - buffer();
427   }
428
429   /**
430    * Get the amount of tail room.
431    *
432    * Returns the number of bytes in the buffer after the end of the data.
433    */
434   uint32_t tailroom() const {
435     return bufferEnd() - tail();
436   }
437
438   /**
439    * Get the pointer to the start of the buffer.
440    *
441    * Note that this is the pointer to the very beginning of the usable buffer,
442    * not the start of valid data within the buffer.  Use the data() method to
443    * get a pointer to the start of the data within the buffer.
444    */
445   const uint8_t* buffer() const {
446     return (flags_ & kFlagExt) ? ext_.buf : int_.buf;
447   }
448
449   /**
450    * Get a writable pointer to the start of the buffer.
451    *
452    * The caller is responsible for calling unshare() first to ensure that it is
453    * actually safe to write to the buffer.
454    */
455   uint8_t* writableBuffer() {
456     return (flags_ & kFlagExt) ? ext_.buf : int_.buf;
457   }
458
459   /**
460    * Get the pointer to the end of the buffer.
461    *
462    * Note that this is the pointer to the very end of the usable buffer,
463    * not the end of valid data within the buffer.  Use the tail() method to
464    * get a pointer to the end of the data within the buffer.
465    */
466   const uint8_t* bufferEnd() const {
467     return (flags_ & kFlagExt) ?
468       ext_.buf + ext_.capacity :
469       int_.buf + kMaxInternalDataSize;
470   }
471
472   /**
473    * Get the total size of the buffer.
474    *
475    * This returns the total usable length of the buffer.  Use the length()
476    * method to get the length of the actual valid data in this IOBuf.
477    */
478   uint32_t capacity() const {
479     return (flags_ & kFlagExt) ?  ext_.capacity : kMaxInternalDataSize;
480   }
481
482   /**
483    * Get a pointer to the next IOBuf in this chain.
484    */
485   IOBuf* next() {
486     return next_;
487   }
488   const IOBuf* next() const {
489     return next_;
490   }
491
492   /**
493    * Get a pointer to the previous IOBuf in this chain.
494    */
495   IOBuf* prev() {
496     return prev_;
497   }
498   const IOBuf* prev() const {
499     return prev_;
500   }
501
502   /**
503    * Shift the data forwards in the buffer.
504    *
505    * This shifts the data pointer forwards in the buffer to increase the
506    * headroom.  This is commonly used to increase the headroom in a newly
507    * allocated buffer.
508    *
509    * The caller is responsible for ensuring that there is sufficient
510    * tailroom in the buffer before calling advance().
511    *
512    * If there is a non-zero data length, advance() will use memmove() to shift
513    * the data forwards in the buffer.  In this case, the caller is responsible
514    * for making sure the buffer is unshared, so it will not affect other IOBufs
515    * that may be sharing the same underlying buffer.
516    */
517   void advance(uint32_t amount) {
518     // In debug builds, assert if there is a problem.
519     assert(amount <= tailroom());
520
521     if (length_ > 0) {
522       memmove(data_ + amount, data_, length_);
523     }
524     data_ += amount;
525   }
526
527   /**
528    * Shift the data backwards in the buffer.
529    *
530    * The caller is responsible for ensuring that there is sufficient headroom
531    * in the buffer before calling retreat().
532    *
533    * If there is a non-zero data length, retreat() will use memmove() to shift
534    * the data backwards in the buffer.  In this case, the caller is responsible
535    * for making sure the buffer is unshared, so it will not affect other IOBufs
536    * that may be sharing the same underlying buffer.
537    */
538   void retreat(uint32_t amount) {
539     // In debug builds, assert if there is a problem.
540     assert(amount <= headroom());
541
542     if (length_ > 0) {
543       memmove(data_ - amount, data_, length_);
544     }
545     data_ -= amount;
546   }
547
548   /**
549    * Adjust the data pointer to include more valid data at the beginning.
550    *
551    * This moves the data pointer backwards to include more of the available
552    * buffer.  The caller is responsible for ensuring that there is sufficient
553    * headroom for the new data.  The caller is also responsible for populating
554    * this section with valid data.
555    *
556    * This does not modify any actual data in the buffer.
557    */
558   void prepend(uint32_t amount) {
559     CHECK(amount <= headroom());
560     data_ -= amount;
561     length_ += amount;
562   }
563
564   /**
565    * Adjust the tail pointer to include more valid data at the end.
566    *
567    * This moves the tail pointer forwards to include more of the available
568    * buffer.  The caller is responsible for ensuring that there is sufficient
569    * tailroom for the new data.  The caller is also responsible for populating
570    * this section with valid data.
571    *
572    * This does not modify any actual data in the buffer.
573    */
574   void append(uint32_t amount) {
575     CHECK(amount <= tailroom());
576     length_ += amount;
577   }
578
579   /**
580    * Adjust the data pointer forwards to include less valid data.
581    *
582    * This moves the data pointer forwards so that the first amount bytes are no
583    * longer considered valid data.  The caller is responsible for ensuring that
584    * amount is less than or equal to the actual data length.
585    *
586    * This does not modify any actual data in the buffer.
587    */
588   void trimStart(uint32_t amount) {
589     CHECK(amount <= length_);
590     data_ += amount;
591     length_ -= amount;
592   }
593
594   /**
595    * Adjust the tail pointer backwards to include less valid data.
596    *
597    * This moves the tail pointer backwards so that the last amount bytes are no
598    * longer considered valid data.  The caller is responsible for ensuring that
599    * amount is less than or equal to the actual data length.
600    *
601    * This does not modify any actual data in the buffer.
602    */
603   void trimEnd(uint32_t amount) {
604     CHECK(amount <= length_);
605     length_ -= amount;
606   }
607
608   /**
609    * Clear the buffer.
610    *
611    * Postcondition: headroom() == 0, length() == 0, tailroom() == capacity()
612    */
613   void clear() {
614     data_ = writableBuffer();
615     length_ = 0;
616   }
617
618   /**
619    * Ensure that this buffer has at least minHeadroom headroom bytes and at
620    * least minTailroom tailroom bytes.  The buffer must be writable
621    * (you must call unshare() before this, if necessary).
622    *
623    * Postcondition: headroom() >= minHeadroom, tailroom() >= minTailroom,
624    * the data (between data() and data() + length()) is preserved.
625    */
626   void reserve(uint32_t minHeadroom, uint32_t minTailroom) {
627     // Maybe we don't need to do anything.
628     if (headroom() >= minHeadroom && tailroom() >= minTailroom) {
629       return;
630     }
631     // If the buffer is empty but we have enough total room (head + tail),
632     // move the data_ pointer around.
633     if (length() == 0 &&
634         headroom() + tailroom() >= minHeadroom + minTailroom) {
635       data_ = writableBuffer() + minHeadroom;
636       return;
637     }
638     // Bah, we have to do actual work.
639     reserveSlow(minHeadroom, minTailroom);
640   }
641
642   /**
643    * Return true if this IOBuf is part of a chain of multiple IOBufs, or false
644    * if this is the only IOBuf in its chain.
645    */
646   bool isChained() const {
647     assert((next_ == this) == (prev_ == this));
648     return next_ != this;
649   }
650
651   /**
652    * Get the number of IOBufs in this chain.
653    *
654    * Beware that this method has to walk the entire chain.
655    * Use isChained() if you just want to check if this IOBuf is part of a chain
656    * or not.
657    */
658   uint32_t countChainElements() const;
659
660   /**
661    * Get the length of all the data in this IOBuf chain.
662    *
663    * Beware that this method has to walk the entire chain.
664    */
665   uint64_t computeChainDataLength() const;
666
667   /**
668    * Insert another IOBuf chain immediately before this IOBuf.
669    *
670    * For example, if there are two IOBuf chains (A, B, C) and (D, E, F),
671    * and B->prependChain(D) is called, the (D, E, F) chain will be subsumed
672    * and become part of the chain starting at A, which will now look like
673    * (A, D, E, F, B, C)
674    *
675    * Note that since IOBuf chains are circular, head->prependChain(other) can
676    * be used to append the other chain at the very end of the chain pointed to
677    * by head.  For example, if there are two IOBuf chains (A, B, C) and
678    * (D, E, F), and A->prependChain(D) is called, the chain starting at A will
679    * now consist of (A, B, C, D, E, F)
680    *
681    * The elements in the specified IOBuf chain will become part of this chain,
682    * and will be owned by the head of this chain.  When this chain is
683    * destroyed, all elements in the supplied chain will also be destroyed.
684    *
685    * For this reason, appendChain() only accepts an rvalue-reference to a
686    * unique_ptr(), to make it clear that it is taking ownership of the supplied
687    * chain.  If you have a raw pointer, you can pass in a new temporary
688    * unique_ptr around the raw pointer.  If you have an existing,
689    * non-temporary unique_ptr, you must call std::move(ptr) to make it clear
690    * that you are destroying the original pointer.
691    */
692   void prependChain(std::unique_ptr<IOBuf>&& iobuf);
693
694   /**
695    * Append another IOBuf chain immediately after this IOBuf.
696    *
697    * For example, if there are two IOBuf chains (A, B, C) and (D, E, F),
698    * and B->appendChain(D) is called, the (D, E, F) chain will be subsumed
699    * and become part of the chain starting at A, which will now look like
700    * (A, B, D, E, F, C)
701    *
702    * The elements in the specified IOBuf chain will become part of this chain,
703    * and will be owned by the head of this chain.  When this chain is
704    * destroyed, all elements in the supplied chain will also be destroyed.
705    *
706    * For this reason, appendChain() only accepts an rvalue-reference to a
707    * unique_ptr(), to make it clear that it is taking ownership of the supplied
708    * chain.  If you have a raw pointer, you can pass in a new temporary
709    * unique_ptr around the raw pointer.  If you have an existing,
710    * non-temporary unique_ptr, you must call std::move(ptr) to make it clear
711    * that you are destroying the original pointer.
712    */
713   void appendChain(std::unique_ptr<IOBuf>&& iobuf) {
714     // Just use prependChain() on the next element in our chain
715     next_->prependChain(std::move(iobuf));
716   }
717
718   /**
719    * Remove this IOBuf from its current chain.
720    *
721    * Since ownership of all elements an IOBuf chain is normally maintained by
722    * the head of the chain, unlink() transfers ownership of this IOBuf from the
723    * chain and gives it to the caller.  A new unique_ptr to the IOBuf is
724    * returned to the caller.  The caller must store the returned unique_ptr (or
725    * call release() on it) to take ownership, otherwise the IOBuf will be
726    * immediately destroyed.
727    *
728    * Since unlink transfers ownership of the IOBuf to the caller, be careful
729    * not to call unlink() on the head of a chain if you already maintain
730    * ownership on the head of the chain via other means.  The pop() method
731    * is a better choice for that situation.
732    */
733   std::unique_ptr<IOBuf> unlink() {
734     next_->prev_ = prev_;
735     prev_->next_ = next_;
736     prev_ = this;
737     next_ = this;
738     return std::unique_ptr<IOBuf>(this);
739   }
740
741   /**
742    * Remove this IOBuf from its current chain and return a unique_ptr to
743    * the IOBuf that formerly followed it in the chain.
744    */
745   std::unique_ptr<IOBuf> pop() {
746     IOBuf *next = next_;
747     next_->prev_ = prev_;
748     prev_->next_ = next_;
749     prev_ = this;
750     next_ = this;
751     return std::unique_ptr<IOBuf>((next == this) ? NULL : next);
752   }
753
754   /**
755    * Remove a subchain from this chain.
756    *
757    * Remove the subchain starting at head and ending at tail from this chain.
758    *
759    * Returns a unique_ptr pointing to head.  (In other words, ownership of the
760    * head of the subchain is transferred to the caller.)  If the caller ignores
761    * the return value and lets the unique_ptr be destroyed, the subchain will
762    * be immediately destroyed.
763    *
764    * The subchain referenced by the specified head and tail must be part of the
765    * same chain as the current IOBuf, but must not contain the current IOBuf.
766    * However, the specified head and tail may be equal to each other (i.e.,
767    * they may be a subchain of length 1).
768    */
769   std::unique_ptr<IOBuf> separateChain(IOBuf* head, IOBuf* tail) {
770     assert(head != this);
771     assert(tail != this);
772
773     head->prev_->next_ = tail->next_;
774     tail->next_->prev_ = head->prev_;
775
776     head->prev_ = tail;
777     tail->next_ = head;
778
779     return std::unique_ptr<IOBuf>(head);
780   }
781
782   /**
783    * Return true if at least one of the IOBufs in this chain are shared,
784    * or false if all of the IOBufs point to unique buffers.
785    *
786    * Use isSharedOne() to only check this IOBuf rather than the entire chain.
787    */
788   bool isShared() const {
789     const IOBuf* current = this;
790     while (true) {
791       if (current->isSharedOne()) {
792         return true;
793       }
794       current = current->next_;
795       if (current == this) {
796         return false;
797       }
798     }
799   }
800
801   /**
802    * Return true if other IOBufs are also pointing to the buffer used by this
803    * IOBuf, and false otherwise.
804    *
805    * If this IOBuf points at a buffer owned by another (non-IOBuf) part of the
806    * code (i.e., if the IOBuf was created using wrapBuffer(), or was cloned
807    * from such an IOBuf), it is always considered shared.
808    *
809    * This only checks the current IOBuf, and not other IOBufs in the chain.
810    */
811   bool isSharedOne() const {
812     // If this is a user-owned buffer, it is always considered shared
813     if (flags_ & kFlagUserOwned) {
814       return true;
815     }
816
817     if (flags_ & kFlagExt) {
818       return ext_.sharedInfo->refcount.load(std::memory_order_acquire) > 1;
819     } else {
820       return false;
821     }
822   }
823
824   /**
825    * Ensure that this IOBuf has a unique buffer that is not shared by other
826    * IOBufs.
827    *
828    * unshare() operates on an entire chain of IOBuf objects.  If the chain is
829    * shared, it may also coalesce the chain when making it unique.  If the
830    * chain is coalesced, subsequent IOBuf objects in the current chain will be
831    * automatically deleted.
832    *
833    * Note that buffers owned by other (non-IOBuf) users are automatically
834    * considered shared.
835    *
836    * Throws std::bad_alloc on error.  On error the IOBuf chain will be
837    * unmodified.
838    *
839    * Currently unshare may also throw std::overflow_error if it tries to
840    * coalesce.  (TODO: In the future it would be nice if unshare() were smart
841    * enough not to coalesce the entire buffer if the data is too large.
842    * However, in practice this seems unlikely to become an issue.)
843    */
844   void unshare() {
845     if (isChained()) {
846       unshareChained();
847     } else {
848       unshareOne();
849     }
850   }
851
852   /**
853    * Ensure that this IOBuf has a unique buffer that is not shared by other
854    * IOBufs.
855    *
856    * unshareOne() operates on a single IOBuf object.  This IOBuf will have a
857    * unique buffer after unshareOne() returns, but other IOBufs in the chain
858    * may still be shared after unshareOne() returns.
859    *
860    * Throws std::bad_alloc on error.  On error the IOBuf will be unmodified.
861    */
862   void unshareOne() {
863     if (isSharedOne()) {
864       unshareOneSlow();
865     }
866   }
867
868   /**
869    * Coalesce this IOBuf chain into a single buffer.
870    *
871    * This method moves all of the data in this IOBuf chain into a single
872    * contiguous buffer, if it is not already in one buffer.  After coalesce()
873    * returns, this IOBuf will be a chain of length one.  Other IOBufs in the
874    * chain will be automatically deleted.
875    *
876    * After coalescing, the IOBuf will have at least as much headroom as the
877    * first IOBuf in the chain, and at least as much tailroom as the last IOBuf
878    * in the chain.
879    *
880    * Throws std::bad_alloc on error.  On error the IOBuf chain will be
881    * unmodified.  Throws std::overflow_error if the length of the entire chain
882    * larger than can be described by a uint32_t capacity.
883    */
884   void coalesce() {
885     if (!isChained()) {
886       return;
887     }
888     coalesceSlow();
889   }
890
891   /**
892    * Ensure that this chain has at least maxLength bytes available as a
893    * contiguous memory range.
894    *
895    * This method coalesces whole buffers in the chain into this buffer as
896    * necessary until this buffer's length() is at least maxLength.
897    *
898    * After coalescing, the IOBuf will have at least as much headroom as the
899    * first IOBuf in the chain, and at least as much tailroom as the last IOBuf
900    * that was coalesced.
901    *
902    * Throws std::bad_alloc on error.  On error the IOBuf chain will be
903    * unmodified.  Throws std::overflow_error if the length of the coalesced
904    * portion of the chain is larger than can be described by a uint32_t
905    * capacity.  (Although maxLength is uint32_t, gather() doesn't split
906    * buffers, so coalescing whole buffers may result in a capacity that can't
907    * be described in uint32_t.
908    *
909    * Upon return, either enough of the chain was coalesced into a contiguous
910    * region, or the entire chain was coalesced.  That is,
911    * length() >= maxLength || !isChained() is true.
912    */
913   void gather(uint32_t maxLength) {
914     if (!isChained() || length_ >= maxLength) {
915       return;
916     }
917     coalesceSlow(maxLength);
918   }
919
920   /**
921    * Return a new IOBuf chain sharing the same data as this chain.
922    *
923    * The new IOBuf chain will normally point to the same underlying data
924    * buffers as the original chain.  (The one exception to this is if some of
925    * the IOBufs in this chain contain small internal data buffers which cannot
926    * be shared.)
927    */
928   std::unique_ptr<IOBuf> clone() const;
929
930   /**
931    * Return a new IOBuf with the same data as this IOBuf.
932    *
933    * The new IOBuf returned will not be part of a chain (even if this IOBuf is
934    * part of a larger chain).
935    */
936   std::unique_ptr<IOBuf> cloneOne() const;
937
938   /**
939    * Return an iovector suitable for e.g. writev()
940    *
941    *   auto iov = buf->getIov();
942    *   auto xfer = writev(fd, iov.data(), iov.size());
943    *
944    * Naturally, the returned iovector is invalid if you modify the buffer
945    * chain.
946    */
947   folly::fbvector<struct iovec> getIov() const;
948
949   // Overridden operator new and delete.
950   // These directly use malloc() and free() to allocate the space for IOBuf
951   // objects.  This is needed since IOBuf::create() manually uses malloc when
952   // allocating IOBuf objects with an internal buffer.
953   void* operator new(size_t size);
954   void* operator new(size_t size, void* ptr);
955   void operator delete(void* ptr);
956
957   /**
958    * Destructively convert this IOBuf to a fbstring efficiently.
959    * We rely on fbstring's AcquireMallocatedString constructor to
960    * transfer memory.
961    */
962   fbstring moveToFbString();
963
964   /**
965    * Iteration support: a chain of IOBufs may be iterated through using
966    * STL-style iterators over const ByteRanges.  Iterators are only invalidated
967    * if the IOBuf that they currently point to is removed.
968    */
969   Iterator cbegin() const;
970   Iterator cend() const;
971   Iterator begin() const;
972   Iterator end() const;
973
974  private:
975   enum FlagsEnum {
976     kFlagExt = 0x1,
977     kFlagUserOwned = 0x2,
978     kFlagFreeSharedInfo = 0x4,
979   };
980
981   // Values for the ExternalBuf type field.
982   // We currently don't really use this for anything, other than to have it
983   // around for debugging purposes.  We store it at the moment just because we
984   // have the 4 extra bytes in the ExternalBuf struct that would just be
985   // padding otherwise.
986   enum ExtBufTypeEnum {
987     kExtAllocated = 0,
988     kExtUserSupplied = 1,
989     kExtUserOwned = 2,
990   };
991
992   struct SharedInfo {
993     SharedInfo();
994     SharedInfo(FreeFunction fn, void* arg);
995
996     // A pointer to a function to call to free the buffer when the refcount
997     // hits 0.  If this is NULL, free() will be used instead.
998     FreeFunction freeFn;
999     void* userData;
1000     std::atomic<uint32_t> refcount;
1001   };
1002   struct ExternalBuf {
1003     uint32_t capacity;
1004     uint32_t type;
1005     uint8_t* buf;
1006     // SharedInfo may be NULL if kFlagUserOwned is set.  It is non-NULL
1007     // in all other cases.
1008     SharedInfo* sharedInfo;
1009   };
1010   struct InternalBuf {
1011     uint8_t buf[] __attribute__((aligned));
1012   };
1013
1014   // The maximum size for an IOBuf object, including any internal data buffer
1015   static const uint32_t kMaxIOBufSize = 256;
1016   static const uint32_t kMaxInternalDataSize;
1017
1018   // Forbidden copy constructor and assignment opererator
1019   IOBuf(IOBuf const &);
1020   IOBuf& operator=(IOBuf const &);
1021
1022   /**
1023    * Create a new IOBuf with internal data.
1024    *
1025    * end is a pointer to the end of the IOBuf's internal data buffer.
1026    */
1027   explicit IOBuf(uint8_t* end);
1028
1029   /**
1030    * Create a new IOBuf pointing to an external buffer.
1031    *
1032    * The caller is responsible for holding a reference count for this new
1033    * IOBuf.  The IOBuf constructor does not automatically increment the
1034    * reference count.
1035    */
1036   IOBuf(ExtBufTypeEnum type, uint32_t flags,
1037         uint8_t* buf, uint32_t capacity,
1038         uint8_t* data, uint32_t length,
1039         SharedInfo* sharedInfo);
1040
1041   void unshareOneSlow();
1042   void unshareChained();
1043   void coalesceSlow(size_t maxLength=std::numeric_limits<size_t>::max());
1044   // newLength must be the entire length of the buffers between this and
1045   // end (no truncation)
1046   void coalesceAndReallocate(
1047       size_t newHeadroom,
1048       size_t newLength,
1049       IOBuf* end,
1050       size_t newTailroom);
1051   void decrementRefcount();
1052   void reserveSlow(uint32_t minHeadroom, uint32_t minTailroom);
1053
1054   static size_t goodExtBufferSize(uint32_t minCapacity);
1055   static void initExtBuffer(uint8_t* buf, size_t mallocSize,
1056                             SharedInfo** infoReturn,
1057                             uint32_t* capacityReturn);
1058   static void allocExtBuffer(uint32_t minCapacity,
1059                              uint8_t** bufReturn,
1060                              SharedInfo** infoReturn,
1061                              uint32_t* capacityReturn);
1062
1063   /*
1064    * Member variables
1065    */
1066
1067   /*
1068    * Links to the next and the previous IOBuf in this chain.
1069    *
1070    * The chain is circularly linked (the last element in the chain points back
1071    * at the head), and next_ and prev_ can never be NULL.  If this IOBuf is the
1072    * only element in the chain, next_ and prev_ will both point to this.
1073    */
1074   IOBuf* next_;
1075   IOBuf* prev_;
1076
1077   /*
1078    * A pointer to the start of the data referenced by this IOBuf, and the
1079    * length of the data.
1080    *
1081    * This may refer to any subsection of the actual buffer capacity.
1082    */
1083   uint8_t* data_;
1084   uint32_t length_;
1085   uint32_t flags_;
1086
1087   union {
1088     ExternalBuf ext_;
1089     InternalBuf int_;
1090   };
1091
1092   struct DeleterBase {
1093     virtual ~DeleterBase() { }
1094     virtual void dispose(void* p) = 0;
1095   };
1096
1097   template <class UniquePtr>
1098   struct UniquePtrDeleter : public DeleterBase {
1099     typedef typename UniquePtr::pointer Pointer;
1100     typedef typename UniquePtr::deleter_type Deleter;
1101
1102     explicit UniquePtrDeleter(Deleter deleter) : deleter_(std::move(deleter)){ }
1103     void dispose(void* p) {
1104       try {
1105         deleter_(static_cast<Pointer>(p));
1106         delete this;
1107       } catch (...) {
1108         abort();
1109       }
1110     }
1111
1112    private:
1113     Deleter deleter_;
1114   };
1115
1116   static void freeUniquePtrBuffer(void* ptr, void* userData) {
1117     static_cast<DeleterBase*>(userData)->dispose(ptr);
1118   }
1119 };
1120
1121 template <class UniquePtr>
1122 typename std::enable_if<detail::IsUniquePtrToSL<UniquePtr>::value,
1123                         std::unique_ptr<IOBuf>>::type
1124 IOBuf::takeOwnership(UniquePtr&& buf, size_t count) {
1125   size_t size = count * sizeof(typename UniquePtr::element_type);
1126   CHECK_LT(size, size_t(std::numeric_limits<uint32_t>::max()));
1127   auto deleter = new UniquePtrDeleter<UniquePtr>(buf.get_deleter());
1128   return takeOwnership(buf.release(),
1129                        size,
1130                        &IOBuf::freeUniquePtrBuffer,
1131                        deleter);
1132 }
1133
1134 inline std::unique_ptr<IOBuf> IOBuf::copyBuffer(
1135     const void* data, uint32_t size, uint32_t headroom,
1136     uint32_t minTailroom) {
1137   uint32_t capacity = headroom + size + minTailroom;
1138   std::unique_ptr<IOBuf> buf = create(capacity);
1139   buf->advance(headroom);
1140   memcpy(buf->writableData(), data, size);
1141   buf->append(size);
1142   return buf;
1143 }
1144
1145 inline std::unique_ptr<IOBuf> IOBuf::copyBuffer(const std::string& buf,
1146                                                 uint32_t headroom,
1147                                                 uint32_t minTailroom) {
1148   return copyBuffer(buf.data(), buf.size(), headroom, minTailroom);
1149 }
1150
1151 inline std::unique_ptr<IOBuf> IOBuf::maybeCopyBuffer(const std::string& buf,
1152                                                      uint32_t headroom,
1153                                                      uint32_t minTailroom) {
1154   if (buf.empty()) {
1155     return nullptr;
1156   }
1157   return copyBuffer(buf.data(), buf.size(), headroom, minTailroom);
1158 }
1159
1160 class IOBuf::Iterator : public boost::iterator_facade<
1161     IOBuf::Iterator,  // Derived
1162     const ByteRange,  // Value
1163     boost::forward_traversal_tag  // Category or traversal
1164   > {
1165   friend class boost::iterator_core_access;
1166  public:
1167   // Note that IOBufs are stored as a circular list without a guard node,
1168   // so pos == end is ambiguous (it may mean "begin" or "end").  To solve
1169   // the ambiguity (at the cost of one extra comparison in the "increment"
1170   // code path), we define end iterators as having pos_ == end_ == nullptr
1171   // and we only allow forward iteration.
1172   explicit Iterator(const IOBuf* pos, const IOBuf* end)
1173     : pos_(pos),
1174       end_(end) {
1175     // Sadly, we must return by const reference, not by value.
1176     if (pos_) {
1177       setVal();
1178     }
1179   }
1180
1181  private:
1182   void setVal() {
1183     val_ = ByteRange(pos_->data(), pos_->tail());
1184   }
1185
1186   void adjustForEnd() {
1187     if (pos_ == end_) {
1188       pos_ = end_ = nullptr;
1189       val_ = ByteRange();
1190     } else {
1191       setVal();
1192     }
1193   }
1194
1195   const ByteRange& dereference() const {
1196     return val_;
1197   }
1198
1199   bool equal(const Iterator& other) const {
1200     // We must compare end_ in addition to pos_, because forward traversal
1201     // requires that if two iterators are equal (a == b) and dereferenceable,
1202     // then ++a == ++b.
1203     return pos_ == other.pos_ && end_ == other.end_;
1204   }
1205
1206   void increment() {
1207     pos_ = pos_->next();
1208     adjustForEnd();
1209   }
1210
1211   const IOBuf* pos_;
1212   const IOBuf* end_;
1213   ByteRange val_;
1214 };
1215
1216 inline IOBuf::Iterator IOBuf::begin() const { return cbegin(); }
1217 inline IOBuf::Iterator IOBuf::end() const { return cend(); }
1218
1219 } // folly
1220
1221 #pragma GCC diagnostic pop
1222
1223 #endif // FOLLY_IO_IOBUF_H_