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