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