apply clang-tidy modernize-use-override
[folly.git] / folly / io / IOBuf.h
1 /*
2  * Copyright 2017 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 #pragma once
18
19 #include <glog/logging.h>
20 #include <atomic>
21 #include <cassert>
22 #include <cinttypes>
23 #include <cstddef>
24 #include <cstring>
25 #include <memory>
26 #include <limits>
27 #include <type_traits>
28
29 #include <boost/iterator/iterator_facade.hpp>
30
31 #include <folly/FBString.h>
32 #include <folly/FBVector.h>
33 #include <folly/Portability.h>
34 #include <folly/Range.h>
35 #include <folly/portability/SysUio.h>
36
37 // Ignore shadowing warnings within this file, so includers can use -Wshadow.
38 FOLLY_PUSH_WARNING
39 FOLLY_GCC_DISABLE_WARNING("-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
169  * -----------------------
170  *
171  * IOBuf objects themselves exist separately from the data buffer they point
172  * to.  Therefore one must also consider how to allocate and manage the IOBuf
173  * objects.
174  *
175  * It is more common to allocate IOBuf objects on the heap, using the create(),
176  * takeOwnership(), or wrapBuffer() factory functions.  The clone()/cloneOne()
177  * functions also return new heap-allocated IOBufs.  The createCombined()
178  * function allocates the IOBuf object and data storage space together, in a
179  * single memory allocation.  This can improve performance, particularly if you
180  * know that the data buffer and the IOBuf itself will have similar lifetimes.
181  *
182  * That said, it is also possible to allocate IOBufs on the stack or inline
183  * inside another object as well.  This is useful for cases where the IOBuf is
184  * short-lived, or when the overhead of allocating the IOBuf on the heap is
185  * undesirable.
186  *
187  * However, note that stack-allocated IOBufs may only be used as the head of a
188  * chain (or standalone as the only IOBuf in a chain).  All non-head members of
189  * an IOBuf chain must be heap allocated.  (All functions to add nodes to a
190  * chain require a std::unique_ptr<IOBuf>, which enforces this requrement.)
191  *
192  * Copying IOBufs is only meaningful for the head of a chain. The entire chain
193  * is cloned; the IOBufs will become shared, and the old and new IOBufs will
194  * refer to the same underlying memory.
195  *
196  * IOBuf Sharing
197  * -------------
198  *
199  * The IOBuf class manages sharing of the underlying buffer that it points to,
200  * maintaining a reference count if multiple IOBufs are pointing at the same
201  * buffer.
202  *
203  * However, it is the callers responsibility to manage sharing and ownership of
204  * IOBuf objects themselves.  The IOBuf structure does not provide room for an
205  * intrusive refcount on the IOBuf object itself, only the underlying data
206  * buffer is reference counted.  If users want to share the same IOBuf object
207  * between multiple parts of the code, they are responsible for managing this
208  * sharing on their own.  (For example, by using a shared_ptr.  Alternatively,
209  * users always have the option of using clone() to create a second IOBuf that
210  * points to the same underlying buffer.)
211  */
212 namespace detail {
213 // Is T a unique_ptr<> to a standard-layout type?
214 template <class T, class Enable=void> struct IsUniquePtrToSL
215   : public std::false_type { };
216 template <class T, class D>
217 struct IsUniquePtrToSL<
218   std::unique_ptr<T, D>,
219   typename std::enable_if<std::is_standard_layout<T>::value>::type>
220   : public std::true_type { };
221 }  // namespace detail
222
223 class IOBuf {
224  public:
225   class Iterator;
226
227   enum CreateOp { CREATE };
228   enum WrapBufferOp { WRAP_BUFFER };
229   enum TakeOwnershipOp { TAKE_OWNERSHIP };
230   enum CopyBufferOp { COPY_BUFFER };
231
232   typedef ByteRange value_type;
233   typedef Iterator iterator;
234   typedef Iterator const_iterator;
235
236   typedef void (*FreeFunction)(void* buf, void* userData);
237
238   /**
239    * Allocate a new IOBuf object with the requested capacity.
240    *
241    * Returns a new IOBuf object that must be (eventually) deleted by the
242    * caller.  The returned IOBuf may actually have slightly more capacity than
243    * requested.
244    *
245    * The data pointer will initially point to the start of the newly allocated
246    * buffer, and will have a data length of 0.
247    *
248    * Throws std::bad_alloc on error.
249    */
250   static std::unique_ptr<IOBuf> create(uint64_t capacity);
251   IOBuf(CreateOp, uint64_t capacity);
252
253   /**
254    * Create a new IOBuf, using a single memory allocation to allocate space
255    * for both the IOBuf object and the data storage space.
256    *
257    * This saves one memory allocation.  However, it can be wasteful if you
258    * later need to grow the buffer using reserve().  If the buffer needs to be
259    * reallocated, the space originally allocated will not be freed() until the
260    * IOBuf object itself is also freed.  (It can also be slightly wasteful in
261    * some cases where you clone this IOBuf and then free the original IOBuf.)
262    */
263   static std::unique_ptr<IOBuf> createCombined(uint64_t capacity);
264
265   /**
266    * Create a new IOBuf, using separate memory allocations for the IOBuf object
267    * for the IOBuf and the data storage space.
268    *
269    * This requires two memory allocations, but saves space in the long run
270    * if you know that you will need to reallocate the data buffer later.
271    */
272   static std::unique_ptr<IOBuf> createSeparate(uint64_t capacity);
273
274   /**
275    * Allocate a new IOBuf chain with the requested total capacity, allocating
276    * no more than maxBufCapacity to each buffer.
277    */
278   static std::unique_ptr<IOBuf> createChain(
279       size_t totalCapacity, uint64_t maxBufCapacity);
280
281   /**
282    * Create a new IOBuf pointing to an existing data buffer.
283    *
284    * The new IOBuffer will assume ownership of the buffer, and free it by
285    * calling the specified FreeFunction when the last IOBuf pointing to this
286    * buffer is destroyed.  The function will be called with a pointer to the
287    * buffer as the first argument, and the supplied userData value as the
288    * second argument.  The free function must never throw exceptions.
289    *
290    * If no FreeFunction is specified, the buffer will be freed using free()
291    * which will result in undefined behavior if the memory was allocated
292    * using 'new'.
293    *
294    * The IOBuf data pointer will initially point to the start of the buffer,
295    *
296    * In the first version of this function, the length of data is unspecified
297    * and is initialized to the capacity of the buffer
298    *
299    * In the second version, the user specifies the valid length of data
300    * in the buffer
301    *
302    * On error, std::bad_alloc will be thrown.  If freeOnError is true (the
303    * default) the buffer will be freed before throwing the error.
304    */
305   static std::unique_ptr<IOBuf> takeOwnership(void* buf, uint64_t capacity,
306                                               FreeFunction freeFn = nullptr,
307                                               void* userData = nullptr,
308                                               bool freeOnError = true) {
309     return takeOwnership(buf, capacity, capacity, freeFn,
310                          userData, freeOnError);
311   }
312   IOBuf(TakeOwnershipOp op, void* buf, uint64_t capacity,
313         FreeFunction freeFn = nullptr, void* userData = nullptr,
314         bool freeOnError = true)
315     : IOBuf(op, buf, capacity, capacity, freeFn, userData, freeOnError) {}
316
317   static std::unique_ptr<IOBuf> takeOwnership(void* buf, uint64_t capacity,
318                                               uint64_t length,
319                                               FreeFunction freeFn = nullptr,
320                                               void* userData = nullptr,
321                                               bool freeOnError = true);
322   IOBuf(TakeOwnershipOp, void* buf, uint64_t capacity, uint64_t length,
323         FreeFunction freeFn = nullptr, void* userData = nullptr,
324         bool freeOnError = true);
325
326   /**
327    * Create a new IOBuf pointing to an existing data buffer made up of
328    * count objects of a given standard-layout type.
329    *
330    * This is dangerous -- it is essentially equivalent to doing
331    * reinterpret_cast<unsigned char*> on your data -- but it's often useful
332    * for serialization / deserialization.
333    *
334    * The new IOBuffer will assume ownership of the buffer, and free it
335    * appropriately (by calling the UniquePtr's custom deleter, or by calling
336    * delete or delete[] appropriately if there is no custom deleter)
337    * when the buffer is destroyed.  The custom deleter, if any, must never
338    * throw exceptions.
339    *
340    * The IOBuf data pointer will initially point to the start of the buffer,
341    * and the length will be the full capacity of the buffer (count *
342    * sizeof(T)).
343    *
344    * On error, std::bad_alloc will be thrown, and the buffer will be freed
345    * before throwing the error.
346    */
347   template <class UniquePtr>
348   static typename std::enable_if<detail::IsUniquePtrToSL<UniquePtr>::value,
349                                  std::unique_ptr<IOBuf>>::type
350   takeOwnership(UniquePtr&& buf, size_t count=1);
351
352   /**
353    * Create a new IOBuf object that points to an existing user-owned buffer.
354    *
355    * This should only be used when the caller knows the lifetime of the IOBuf
356    * object ahead of time and can ensure that all IOBuf objects that will point
357    * to this buffer will be destroyed before the buffer itself is destroyed.
358    *
359    * This buffer will not be freed automatically when the last IOBuf
360    * referencing it is destroyed.  It is the caller's responsibility to free
361    * the buffer after the last IOBuf has been destroyed.
362    *
363    * The IOBuf data pointer will initially point to the start of the buffer,
364    * and the length will be the full capacity of the buffer.
365    *
366    * An IOBuf created using wrapBuffer() will always be reported as shared.
367    * unshare() may be used to create a writable copy of the buffer.
368    *
369    * On error, std::bad_alloc will be thrown.
370    */
371   static std::unique_ptr<IOBuf> wrapBuffer(const void* buf, uint64_t capacity);
372   static std::unique_ptr<IOBuf> wrapBuffer(ByteRange br) {
373     return wrapBuffer(br.data(), br.size());
374   }
375
376   /**
377    * Similar to wrapBuffer(), but returns IOBuf by value rather than
378    * heap-allocating it.
379    */
380   static IOBuf wrapBufferAsValue(const void* buf, uint64_t capacity);
381   static IOBuf wrapBufferAsValue(ByteRange br) {
382     return wrapBufferAsValue(br.data(), br.size());
383   }
384
385   IOBuf(WrapBufferOp op, const void* buf, uint64_t capacity);
386   IOBuf(WrapBufferOp op, ByteRange br);
387
388   /**
389    * Convenience function to create a new IOBuf object that copies data from a
390    * user-supplied buffer, optionally allocating a given amount of
391    * headroom and tailroom.
392    */
393   static std::unique_ptr<IOBuf> copyBuffer(const void* buf, uint64_t size,
394                                            uint64_t headroom=0,
395                                            uint64_t minTailroom=0);
396   static std::unique_ptr<IOBuf> copyBuffer(ByteRange br,
397                                            uint64_t headroom=0,
398                                            uint64_t minTailroom=0) {
399     return copyBuffer(br.data(), br.size(), headroom, minTailroom);
400   }
401   IOBuf(CopyBufferOp op, const void* buf, uint64_t size,
402         uint64_t headroom=0, uint64_t minTailroom=0);
403   IOBuf(CopyBufferOp op, ByteRange br,
404         uint64_t headroom=0, uint64_t minTailroom=0);
405
406   /**
407    * Convenience function to create a new IOBuf object that copies data from a
408    * user-supplied string, optionally allocating a given amount of
409    * headroom and tailroom.
410    *
411    * Beware when attempting to invoke this function with a constant string
412    * literal and a headroom argument: you will likely end up invoking the
413    * version of copyBuffer() above.  IOBuf::copyBuffer("hello", 3) will treat
414    * the first argument as a const void*, and will invoke the version of
415    * copyBuffer() above, with the size argument of 3.
416    */
417   static std::unique_ptr<IOBuf> copyBuffer(const std::string& buf,
418                                            uint64_t headroom=0,
419                                            uint64_t minTailroom=0);
420   IOBuf(CopyBufferOp op, const std::string& buf,
421         uint64_t headroom=0, uint64_t minTailroom=0)
422     : IOBuf(op, buf.data(), buf.size(), headroom, minTailroom) {}
423
424   /**
425    * A version of copyBuffer() that returns a null pointer if the input string
426    * is empty.
427    */
428   static std::unique_ptr<IOBuf> maybeCopyBuffer(const std::string& buf,
429                                                 uint64_t headroom=0,
430                                                 uint64_t minTailroom=0);
431
432   /**
433    * Convenience function to free a chain of IOBufs held by a unique_ptr.
434    */
435   static void destroy(std::unique_ptr<IOBuf>&& data) {
436     auto destroyer = std::move(data);
437   }
438
439   /**
440    * Destroy this IOBuf.
441    *
442    * Deleting an IOBuf will automatically destroy all IOBufs in the chain.
443    * (See the comments above regarding the ownership model of IOBuf chains.
444    * All subsequent IOBufs in the chain are considered to be owned by the head
445    * of the chain.  Users should only explicitly delete the head of a chain.)
446    *
447    * When each individual IOBuf is destroyed, it will release its reference
448    * count on the underlying buffer.  If it was the last user of the buffer,
449    * the buffer will be freed.
450    */
451   ~IOBuf();
452
453   /**
454    * Check whether the chain is empty (i.e., whether the IOBufs in the
455    * chain have a total data length of zero).
456    *
457    * This method is semantically equivalent to
458    *   i->computeChainDataLength()==0
459    * but may run faster because it can short-circuit as soon as it
460    * encounters a buffer with length()!=0
461    */
462   bool empty() const;
463
464   /**
465    * Get the pointer to the start of the data.
466    */
467   const uint8_t* data() const {
468     return data_;
469   }
470
471   /**
472    * Get a writable pointer to the start of the data.
473    *
474    * The caller is responsible for calling unshare() first to ensure that it is
475    * actually safe to write to the buffer.
476    */
477   uint8_t* writableData() {
478     return data_;
479   }
480
481   /**
482    * Get the pointer to the end of the data.
483    */
484   const uint8_t* tail() const {
485     return data_ + length_;
486   }
487
488   /**
489    * Get a writable pointer to the end of the data.
490    *
491    * The caller is responsible for calling unshare() first to ensure that it is
492    * actually safe to write to the buffer.
493    */
494   uint8_t* writableTail() {
495     return data_ + length_;
496   }
497
498   /**
499    * Get the data length.
500    */
501   uint64_t length() const {
502     return length_;
503   }
504
505   /**
506    * Get the amount of head room.
507    *
508    * Returns the number of bytes in the buffer before the start of the data.
509    */
510   uint64_t headroom() const {
511     return uint64_t(data_ - buffer());
512   }
513
514   /**
515    * Get the amount of tail room.
516    *
517    * Returns the number of bytes in the buffer after the end of the data.
518    */
519   uint64_t tailroom() const {
520     return uint64_t(bufferEnd() - tail());
521   }
522
523   /**
524    * Get the pointer to the start of the buffer.
525    *
526    * Note that this is the pointer to the very beginning of the usable buffer,
527    * not the start of valid data within the buffer.  Use the data() method to
528    * get a pointer to the start of the data within the buffer.
529    */
530   const uint8_t* buffer() const {
531     return buf_;
532   }
533
534   /**
535    * Get a writable pointer to the start of the buffer.
536    *
537    * The caller is responsible for calling unshare() first to ensure that it is
538    * actually safe to write to the buffer.
539    */
540   uint8_t* writableBuffer() {
541     return buf_;
542   }
543
544   /**
545    * Get the pointer to the end of the buffer.
546    *
547    * Note that this is the pointer to the very end of the usable buffer,
548    * not the end of valid data within the buffer.  Use the tail() method to
549    * get a pointer to the end of the data within the buffer.
550    */
551   const uint8_t* bufferEnd() const {
552     return buf_ + capacity_;
553   }
554
555   /**
556    * Get the total size of the buffer.
557    *
558    * This returns the total usable length of the buffer.  Use the length()
559    * method to get the length of the actual valid data in this IOBuf.
560    */
561   uint64_t capacity() const {
562     return capacity_;
563   }
564
565   /**
566    * Get a pointer to the next IOBuf in this chain.
567    */
568   IOBuf* next() {
569     return next_;
570   }
571   const IOBuf* next() const {
572     return next_;
573   }
574
575   /**
576    * Get a pointer to the previous IOBuf in this chain.
577    */
578   IOBuf* prev() {
579     return prev_;
580   }
581   const IOBuf* prev() const {
582     return prev_;
583   }
584
585   /**
586    * Shift the data forwards in the buffer.
587    *
588    * This shifts the data pointer forwards in the buffer to increase the
589    * headroom.  This is commonly used to increase the headroom in a newly
590    * allocated buffer.
591    *
592    * The caller is responsible for ensuring that there is sufficient
593    * tailroom in the buffer before calling advance().
594    *
595    * If there is a non-zero data length, advance() will use memmove() to shift
596    * the data forwards in the buffer.  In this case, the caller is responsible
597    * for making sure the buffer is unshared, so it will not affect other IOBufs
598    * that may be sharing the same underlying buffer.
599    */
600   void advance(uint64_t amount) {
601     // In debug builds, assert if there is a problem.
602     assert(amount <= tailroom());
603
604     if (length_ > 0) {
605       memmove(data_ + amount, data_, length_);
606     }
607     data_ += amount;
608   }
609
610   /**
611    * Shift the data backwards in the buffer.
612    *
613    * The caller is responsible for ensuring that there is sufficient headroom
614    * in the buffer before calling retreat().
615    *
616    * If there is a non-zero data length, retreat() will use memmove() to shift
617    * the data backwards in the buffer.  In this case, the caller is responsible
618    * for making sure the buffer is unshared, so it will not affect other IOBufs
619    * that may be sharing the same underlying buffer.
620    */
621   void retreat(uint64_t amount) {
622     // In debug builds, assert if there is a problem.
623     assert(amount <= headroom());
624
625     if (length_ > 0) {
626       memmove(data_ - amount, data_, length_);
627     }
628     data_ -= amount;
629   }
630
631   /**
632    * Adjust the data pointer to include more valid data at the beginning.
633    *
634    * This moves the data pointer backwards to include more of the available
635    * buffer.  The caller is responsible for ensuring that there is sufficient
636    * headroom for the new data.  The caller is also responsible for populating
637    * this section with valid data.
638    *
639    * This does not modify any actual data in the buffer.
640    */
641   void prepend(uint64_t amount) {
642     DCHECK_LE(amount, headroom());
643     data_ -= amount;
644     length_ += amount;
645   }
646
647   /**
648    * Adjust the tail pointer to include more valid data at the end.
649    *
650    * This moves the tail pointer forwards to include more of the available
651    * buffer.  The caller is responsible for ensuring that there is sufficient
652    * tailroom for the new data.  The caller is also responsible for populating
653    * this section with valid data.
654    *
655    * This does not modify any actual data in the buffer.
656    */
657   void append(uint64_t amount) {
658     DCHECK_LE(amount, tailroom());
659     length_ += amount;
660   }
661
662   /**
663    * Adjust the data pointer forwards to include less valid data.
664    *
665    * This moves the data pointer forwards so that the first amount bytes are no
666    * longer considered valid data.  The caller is responsible for ensuring that
667    * amount is less than or equal to the actual data length.
668    *
669    * This does not modify any actual data in the buffer.
670    */
671   void trimStart(uint64_t amount) {
672     DCHECK_LE(amount, length_);
673     data_ += amount;
674     length_ -= amount;
675   }
676
677   /**
678    * Adjust the tail pointer backwards to include less valid data.
679    *
680    * This moves the tail pointer backwards so that the last amount bytes are no
681    * longer considered valid data.  The caller is responsible for ensuring that
682    * amount is less than or equal to the actual data length.
683    *
684    * This does not modify any actual data in the buffer.
685    */
686   void trimEnd(uint64_t amount) {
687     DCHECK_LE(amount, length_);
688     length_ -= amount;
689   }
690
691   /**
692    * Clear the buffer.
693    *
694    * Postcondition: headroom() == 0, length() == 0, tailroom() == capacity()
695    */
696   void clear() {
697     data_ = writableBuffer();
698     length_ = 0;
699   }
700
701   /**
702    * Ensure that this buffer has at least minHeadroom headroom bytes and at
703    * least minTailroom tailroom bytes.  The buffer must be writable
704    * (you must call unshare() before this, if necessary).
705    *
706    * Postcondition: headroom() >= minHeadroom, tailroom() >= minTailroom,
707    * the data (between data() and data() + length()) is preserved.
708    */
709   void reserve(uint64_t minHeadroom, uint64_t minTailroom) {
710     // Maybe we don't need to do anything.
711     if (headroom() >= minHeadroom && tailroom() >= minTailroom) {
712       return;
713     }
714     // If the buffer is empty but we have enough total room (head + tail),
715     // move the data_ pointer around.
716     if (length() == 0 &&
717         headroom() + tailroom() >= minHeadroom + minTailroom) {
718       data_ = writableBuffer() + minHeadroom;
719       return;
720     }
721     // Bah, we have to do actual work.
722     reserveSlow(minHeadroom, minTailroom);
723   }
724
725   /**
726    * Return true if this IOBuf is part of a chain of multiple IOBufs, or false
727    * if this is the only IOBuf in its chain.
728    */
729   bool isChained() const {
730     assert((next_ == this) == (prev_ == this));
731     return next_ != this;
732   }
733
734   /**
735    * Get the number of IOBufs in this chain.
736    *
737    * Beware that this method has to walk the entire chain.
738    * Use isChained() if you just want to check if this IOBuf is part of a chain
739    * or not.
740    */
741   size_t countChainElements() const;
742
743   /**
744    * Get the length of all the data in this IOBuf chain.
745    *
746    * Beware that this method has to walk the entire chain.
747    */
748   uint64_t computeChainDataLength() const;
749
750   /**
751    * Insert another IOBuf chain immediately before this IOBuf.
752    *
753    * For example, if there are two IOBuf chains (A, B, C) and (D, E, F),
754    * and B->prependChain(D) is called, the (D, E, F) chain will be subsumed
755    * and become part of the chain starting at A, which will now look like
756    * (A, D, E, F, B, C)
757    *
758    * Note that since IOBuf chains are circular, head->prependChain(other) can
759    * be used to append the other chain at the very end of the chain pointed to
760    * by head.  For example, if there are two IOBuf chains (A, B, C) and
761    * (D, E, F), and A->prependChain(D) is called, the chain starting at A will
762    * now consist of (A, B, C, D, E, F)
763    *
764    * The elements in the specified IOBuf chain will become part of this chain,
765    * and will be owned by the head of this chain.  When this chain is
766    * destroyed, all elements in the supplied chain will also be destroyed.
767    *
768    * For this reason, appendChain() only accepts an rvalue-reference to a
769    * unique_ptr(), to make it clear that it is taking ownership of the supplied
770    * chain.  If you have a raw pointer, you can pass in a new temporary
771    * unique_ptr around the raw pointer.  If you have an existing,
772    * non-temporary unique_ptr, you must call std::move(ptr) to make it clear
773    * that you are destroying the original pointer.
774    */
775   void prependChain(std::unique_ptr<IOBuf>&& iobuf);
776
777   /**
778    * Append another IOBuf chain immediately after this IOBuf.
779    *
780    * For example, if there are two IOBuf chains (A, B, C) and (D, E, F),
781    * and B->appendChain(D) is called, the (D, E, F) chain will be subsumed
782    * and become part of the chain starting at A, which will now look like
783    * (A, B, D, E, F, C)
784    *
785    * The elements in the specified IOBuf chain will become part of this chain,
786    * and will be owned by the head of this chain.  When this chain is
787    * destroyed, all elements in the supplied chain will also be destroyed.
788    *
789    * For this reason, appendChain() only accepts an rvalue-reference to a
790    * unique_ptr(), to make it clear that it is taking ownership of the supplied
791    * chain.  If you have a raw pointer, you can pass in a new temporary
792    * unique_ptr around the raw pointer.  If you have an existing,
793    * non-temporary unique_ptr, you must call std::move(ptr) to make it clear
794    * that you are destroying the original pointer.
795    */
796   void appendChain(std::unique_ptr<IOBuf>&& iobuf) {
797     // Just use prependChain() on the next element in our chain
798     next_->prependChain(std::move(iobuf));
799   }
800
801   /**
802    * Remove this IOBuf from its current chain.
803    *
804    * Since ownership of all elements an IOBuf chain is normally maintained by
805    * the head of the chain, unlink() transfers ownership of this IOBuf from the
806    * chain and gives it to the caller.  A new unique_ptr to the IOBuf is
807    * returned to the caller.  The caller must store the returned unique_ptr (or
808    * call release() on it) to take ownership, otherwise the IOBuf will be
809    * immediately destroyed.
810    *
811    * Since unlink transfers ownership of the IOBuf to the caller, be careful
812    * not to call unlink() on the head of a chain if you already maintain
813    * ownership on the head of the chain via other means.  The pop() method
814    * is a better choice for that situation.
815    */
816   std::unique_ptr<IOBuf> unlink() {
817     next_->prev_ = prev_;
818     prev_->next_ = next_;
819     prev_ = this;
820     next_ = this;
821     return std::unique_ptr<IOBuf>(this);
822   }
823
824   /**
825    * Remove this IOBuf from its current chain and return a unique_ptr to
826    * the IOBuf that formerly followed it in the chain.
827    */
828   std::unique_ptr<IOBuf> pop() {
829     IOBuf *next = next_;
830     next_->prev_ = prev_;
831     prev_->next_ = next_;
832     prev_ = this;
833     next_ = this;
834     return std::unique_ptr<IOBuf>((next == this) ? nullptr : next);
835   }
836
837   /**
838    * Remove a subchain from this chain.
839    *
840    * Remove the subchain starting at head and ending at tail from this chain.
841    *
842    * Returns a unique_ptr pointing to head.  (In other words, ownership of the
843    * head of the subchain is transferred to the caller.)  If the caller ignores
844    * the return value and lets the unique_ptr be destroyed, the subchain will
845    * be immediately destroyed.
846    *
847    * The subchain referenced by the specified head and tail must be part of the
848    * same chain as the current IOBuf, but must not contain the current IOBuf.
849    * However, the specified head and tail may be equal to each other (i.e.,
850    * they may be a subchain of length 1).
851    */
852   std::unique_ptr<IOBuf> separateChain(IOBuf* head, IOBuf* tail) {
853     assert(head != this);
854     assert(tail != this);
855
856     head->prev_->next_ = tail->next_;
857     tail->next_->prev_ = head->prev_;
858
859     head->prev_ = tail;
860     tail->next_ = head;
861
862     return std::unique_ptr<IOBuf>(head);
863   }
864
865   /**
866    * Return true if at least one of the IOBufs in this chain are shared,
867    * or false if all of the IOBufs point to unique buffers.
868    *
869    * Use isSharedOne() to only check this IOBuf rather than the entire chain.
870    */
871   bool isShared() const {
872     const IOBuf* current = this;
873     while (true) {
874       if (current->isSharedOne()) {
875         return true;
876       }
877       current = current->next_;
878       if (current == this) {
879         return false;
880       }
881     }
882   }
883
884   /**
885    * Return true if all IOBufs in this chain are managed by the usual
886    * refcounting mechanism (and so the lifetime of the underlying memory
887    * can be extended by clone()).
888    */
889   bool isManaged() const {
890     const IOBuf* current = this;
891     while (true) {
892       if (!current->isManagedOne()) {
893         return false;
894       }
895       current = current->next_;
896       if (current == this) {
897         return true;
898       }
899     }
900   }
901
902   /**
903    * Return true if this IOBuf is managed by the usual refcounting mechanism
904    * (and so the lifetime of the underlying memory can be extended by
905    * cloneOne()).
906    */
907   bool isManagedOne() const {
908     return sharedInfo();
909   }
910
911   /**
912    * Return true if other IOBufs are also pointing to the buffer used by this
913    * IOBuf, and false otherwise.
914    *
915    * If this IOBuf points at a buffer owned by another (non-IOBuf) part of the
916    * code (i.e., if the IOBuf was created using wrapBuffer(), or was cloned
917    * from such an IOBuf), it is always considered shared.
918    *
919    * This only checks the current IOBuf, and not other IOBufs in the chain.
920    */
921   bool isSharedOne() const {
922     // If this is a user-owned buffer, it is always considered shared
923     if (UNLIKELY(!sharedInfo())) {
924       return true;
925     }
926
927     if (UNLIKELY(sharedInfo()->externallyShared)) {
928       return true;
929     }
930
931     if (LIKELY(!(flags() & kFlagMaybeShared))) {
932       return false;
933     }
934
935     // kFlagMaybeShared is set, so we need to check the reference count.
936     // (Checking the reference count requires an atomic operation, which is why
937     // we prefer to only check kFlagMaybeShared if possible.)
938     bool shared = sharedInfo()->refcount.load(std::memory_order_acquire) > 1;
939     if (!shared) {
940       // we're the last one left
941       clearFlags(kFlagMaybeShared);
942     }
943     return shared;
944   }
945
946   /**
947    * Ensure that this IOBuf has a unique buffer that is not shared by other
948    * IOBufs.
949    *
950    * unshare() operates on an entire chain of IOBuf objects.  If the chain is
951    * shared, it may also coalesce the chain when making it unique.  If the
952    * chain is coalesced, subsequent IOBuf objects in the current chain will be
953    * automatically deleted.
954    *
955    * Note that buffers owned by other (non-IOBuf) users are automatically
956    * considered shared.
957    *
958    * Throws std::bad_alloc on error.  On error the IOBuf chain will be
959    * unmodified.
960    *
961    * Currently unshare may also throw std::overflow_error if it tries to
962    * coalesce.  (TODO: In the future it would be nice if unshare() were smart
963    * enough not to coalesce the entire buffer if the data is too large.
964    * However, in practice this seems unlikely to become an issue.)
965    */
966   void unshare() {
967     if (isChained()) {
968       unshareChained();
969     } else {
970       unshareOne();
971     }
972   }
973
974   /**
975    * Ensure that this IOBuf has a unique buffer that is not shared by other
976    * IOBufs.
977    *
978    * unshareOne() operates on a single IOBuf object.  This IOBuf will have a
979    * unique buffer after unshareOne() returns, but other IOBufs in the chain
980    * may still be shared after unshareOne() returns.
981    *
982    * Throws std::bad_alloc on error.  On error the IOBuf will be unmodified.
983    */
984   void unshareOne() {
985     if (isSharedOne()) {
986       unshareOneSlow();
987     }
988   }
989
990   /**
991    * Mark the underlying buffers in this chain as shared with external memory
992    * management mechanism. This will make isShared() always returns true.
993    *
994    * This function is not thread-safe, and only safe to call immediately after
995    * creating an IOBuf, before it has been shared with other threads.
996    */
997   void markExternallyShared();
998
999   /**
1000    * Mark the underlying buffer that this IOBuf refers to as shared with
1001    * external memory management mechanism. This will make isSharedOne() always
1002    * returns true.
1003    *
1004    * This function is not thread-safe, and only safe to call immediately after
1005    * creating an IOBuf, before it has been shared with other threads.
1006    */
1007   void markExternallySharedOne() {
1008     SharedInfo* info = sharedInfo();
1009     if (info) {
1010       info->externallyShared = true;
1011     }
1012   }
1013
1014   /**
1015    * Ensure that the memory that IOBufs in this chain refer to will continue to
1016    * be allocated for as long as the IOBufs of the chain (or any clone()s
1017    * created from this point onwards) is alive.
1018    *
1019    * This only has an effect for user-owned buffers (created with the
1020    * WRAP_BUFFER constructor or wrapBuffer factory function), in which case
1021    * those buffers are unshared.
1022    */
1023   void makeManaged() {
1024     if (isChained()) {
1025       makeManagedChained();
1026     } else {
1027       makeManagedOne();
1028     }
1029   }
1030
1031   /**
1032    * Ensure that the memory that this IOBuf refers to will continue to be
1033    * allocated for as long as this IOBuf (or any clone()s created from this
1034    * point onwards) is alive.
1035    *
1036    * This only has an effect for user-owned buffers (created with the
1037    * WRAP_BUFFER constructor or wrapBuffer factory function), in which case
1038    * those buffers are unshared.
1039    */
1040   void makeManagedOne() {
1041     if (!isManagedOne()) {
1042       // We can call the internal function directly; unmanaged implies shared.
1043       unshareOneSlow();
1044     }
1045   }
1046
1047   /**
1048    * Coalesce this IOBuf chain into a single buffer.
1049    *
1050    * This method moves all of the data in this IOBuf chain into a single
1051    * contiguous buffer, if it is not already in one buffer.  After coalesce()
1052    * returns, this IOBuf will be a chain of length one.  Other IOBufs in the
1053    * chain will be automatically deleted.
1054    *
1055    * After coalescing, the IOBuf will have at least as much headroom as the
1056    * first IOBuf in the chain, and at least as much tailroom as the last IOBuf
1057    * in the chain.
1058    *
1059    * Throws std::bad_alloc on error.  On error the IOBuf chain will be
1060    * unmodified.
1061    *
1062    * Returns ByteRange that points to the data IOBuf stores.
1063    */
1064   ByteRange coalesce() {
1065     if (isChained()) {
1066       coalesceSlow();
1067     }
1068     return ByteRange(data_, length_);
1069   }
1070
1071   /**
1072    * Ensure that this chain has at least maxLength bytes available as a
1073    * contiguous memory range.
1074    *
1075    * This method coalesces whole buffers in the chain into this buffer as
1076    * necessary until this buffer's length() is at least maxLength.
1077    *
1078    * After coalescing, the IOBuf will have at least as much headroom as the
1079    * first IOBuf in the chain, and at least as much tailroom as the last IOBuf
1080    * that was coalesced.
1081    *
1082    * Throws std::bad_alloc or std::overflow_error on error.  On error the IOBuf
1083    * chain will be unmodified.  Throws std::overflow_error if maxLength is
1084    * longer than the total chain length.
1085    *
1086    * Upon return, either enough of the chain was coalesced into a contiguous
1087    * region, or the entire chain was coalesced.  That is,
1088    * length() >= maxLength || !isChained() is true.
1089    */
1090   void gather(uint64_t maxLength) {
1091     if (!isChained() || length_ >= maxLength) {
1092       return;
1093     }
1094     coalesceSlow(maxLength);
1095   }
1096
1097   /**
1098    * Return a new IOBuf chain sharing the same data as this chain.
1099    *
1100    * The new IOBuf chain will normally point to the same underlying data
1101    * buffers as the original chain.  (The one exception to this is if some of
1102    * the IOBufs in this chain contain small internal data buffers which cannot
1103    * be shared.)
1104    */
1105   std::unique_ptr<IOBuf> clone() const;
1106
1107   /**
1108    * Similar to clone(). But returns IOBuf by value rather than heap-allocating
1109    * it.
1110    */
1111   IOBuf cloneAsValue() const;
1112
1113   /**
1114    * Return a new IOBuf with the same data as this IOBuf.
1115    *
1116    * The new IOBuf returned will not be part of a chain (even if this IOBuf is
1117    * part of a larger chain).
1118    */
1119   std::unique_ptr<IOBuf> cloneOne() const;
1120
1121   /**
1122    * Similar to cloneOne(). But returns IOBuf by value rather than
1123    * heap-allocating it.
1124    */
1125   IOBuf cloneOneAsValue() const;
1126
1127   /**
1128    * Return a new unchained IOBuf that may share the same data as this chain.
1129    *
1130    * If the IOBuf chain is not chained then the new IOBuf will point to the same
1131    * underlying data buffer as the original chain. Otherwise, it will clone and
1132    * coalesce the IOBuf chain.
1133    *
1134    * The new IOBuf will have at least as much headroom as the first IOBuf in the
1135    * chain, and at least as much tailroom as the last IOBuf in the chain.
1136    *
1137    * Throws std::bad_alloc on error.
1138    */
1139   std::unique_ptr<IOBuf> cloneCoalesced() const;
1140
1141   /**
1142    * Similar to cloneCoalesced(). But returns IOBuf by value rather than
1143    * heap-allocating it.
1144    */
1145   IOBuf cloneCoalescedAsValue() const;
1146
1147   /**
1148    * Similar to Clone(). But use other as the head node. Other nodes in the
1149    * chain (if any) will be allocted on heap.
1150    */
1151   void cloneInto(IOBuf& other) const {
1152     other = cloneAsValue();
1153   }
1154
1155   /**
1156    * Similar to CloneOne(). But to fill an existing IOBuf instead of a new
1157    * IOBuf.
1158    */
1159   void cloneOneInto(IOBuf& other) const {
1160     other = cloneOneAsValue();
1161   }
1162
1163   /**
1164    * Return an iovector suitable for e.g. writev()
1165    *
1166    *   auto iov = buf->getIov();
1167    *   auto xfer = writev(fd, iov.data(), iov.size());
1168    *
1169    * Naturally, the returned iovector is invalid if you modify the buffer
1170    * chain.
1171    */
1172   folly::fbvector<struct iovec> getIov() const;
1173
1174   /**
1175    * Update an existing iovec array with the IOBuf data.
1176    *
1177    * New iovecs will be appended to the existing vector; anything already
1178    * present in the vector will be left unchanged.
1179    *
1180    * Naturally, the returned iovec data will be invalid if you modify the
1181    * buffer chain.
1182    */
1183   void appendToIov(folly::fbvector<struct iovec>* iov) const;
1184
1185   /**
1186    * Fill an iovec array with the IOBuf data.
1187    *
1188    * Returns the number of iovec filled. If there are more buffer than
1189    * iovec, returns 0. This version is suitable to use with stack iovec
1190    * arrays.
1191    *
1192    * Naturally, the filled iovec data will be invalid if you modify the
1193    * buffer chain.
1194    */
1195   size_t fillIov(struct iovec* iov, size_t len) const;
1196
1197   /*
1198    * Overridden operator new and delete.
1199    * These perform specialized memory management to help support
1200    * createCombined(), which allocates IOBuf objects together with the buffer
1201    * data.
1202    */
1203   void* operator new(size_t size);
1204   void* operator new(size_t size, void* ptr);
1205   void operator delete(void* ptr);
1206
1207   /**
1208    * Destructively convert this IOBuf to a fbstring efficiently.
1209    * We rely on fbstring's AcquireMallocatedString constructor to
1210    * transfer memory.
1211    */
1212   fbstring moveToFbString();
1213
1214   /**
1215    * Iteration support: a chain of IOBufs may be iterated through using
1216    * STL-style iterators over const ByteRanges.  Iterators are only invalidated
1217    * if the IOBuf that they currently point to is removed.
1218    */
1219   Iterator cbegin() const;
1220   Iterator cend() const;
1221   Iterator begin() const;
1222   Iterator end() const;
1223
1224   /**
1225    * Allocate a new null buffer.
1226    *
1227    * This can be used to allocate an empty IOBuf on the stack.  It will have no
1228    * space allocated for it.  This is generally useful only to later use move
1229    * assignment to fill out the IOBuf.
1230    */
1231   IOBuf() noexcept;
1232
1233   /**
1234    * Move constructor and assignment operator.
1235    *
1236    * In general, you should only ever move the head of an IOBuf chain.
1237    * Internal nodes in an IOBuf chain are owned by the head of the chain, and
1238    * should not be moved from.  (Technically, nothing prevents you from moving
1239    * a non-head node, but the moved-to node will replace the moved-from node in
1240    * the chain.  This has implications for ownership, since non-head nodes are
1241    * owned by the chain head.  You are then responsible for relinquishing
1242    * ownership of the moved-to node, and manually deleting the moved-from
1243    * node.)
1244    *
1245    * With the move assignment operator, the destination of the move should be
1246    * the head of an IOBuf chain or a solitary IOBuf not part of a chain.  If
1247    * the move destination is part of a chain, all other IOBufs in the chain
1248    * will be deleted.
1249    */
1250   IOBuf(IOBuf&& other) noexcept;
1251   IOBuf& operator=(IOBuf&& other) noexcept;
1252
1253   IOBuf(const IOBuf& other);
1254   IOBuf& operator=(const IOBuf& other);
1255
1256  private:
1257   enum FlagsEnum : uintptr_t {
1258     // Adding any more flags would not work on 32-bit architectures,
1259     // as these flags are stashed in the least significant 2 bits of a
1260     // max-align-aligned pointer.
1261     kFlagFreeSharedInfo = 0x1,
1262     kFlagMaybeShared = 0x2,
1263     kFlagMask = kFlagFreeSharedInfo | kFlagMaybeShared
1264   };
1265
1266   struct SharedInfo {
1267     SharedInfo();
1268     SharedInfo(FreeFunction fn, void* arg);
1269
1270     // A pointer to a function to call to free the buffer when the refcount
1271     // hits 0.  If this is null, free() will be used instead.
1272     FreeFunction freeFn;
1273     void* userData;
1274     std::atomic<uint32_t> refcount;
1275     bool externallyShared{false};
1276   };
1277   // Helper structs for use by operator new and delete
1278   struct HeapPrefix;
1279   struct HeapStorage;
1280   struct HeapFullStorage;
1281
1282   /**
1283    * Create a new IOBuf pointing to an external buffer.
1284    *
1285    * The caller is responsible for holding a reference count for this new
1286    * IOBuf.  The IOBuf constructor does not automatically increment the
1287    * reference count.
1288    */
1289   struct InternalConstructor {};  // avoid conflicts
1290   IOBuf(InternalConstructor, uintptr_t flagsAndSharedInfo,
1291         uint8_t* buf, uint64_t capacity,
1292         uint8_t* data, uint64_t length);
1293
1294   void unshareOneSlow();
1295   void unshareChained();
1296   void makeManagedChained();
1297   void coalesceSlow();
1298   void coalesceSlow(size_t maxLength);
1299   // newLength must be the entire length of the buffers between this and
1300   // end (no truncation)
1301   void coalesceAndReallocate(
1302       size_t newHeadroom,
1303       size_t newLength,
1304       IOBuf* end,
1305       size_t newTailroom);
1306   void coalesceAndReallocate(size_t newLength, IOBuf* end) {
1307     coalesceAndReallocate(headroom(), newLength, end, end->prev_->tailroom());
1308   }
1309   void decrementRefcount();
1310   void reserveSlow(uint64_t minHeadroom, uint64_t minTailroom);
1311   void freeExtBuffer();
1312
1313   static size_t goodExtBufferSize(uint64_t minCapacity);
1314   static void initExtBuffer(uint8_t* buf, size_t mallocSize,
1315                             SharedInfo** infoReturn,
1316                             uint64_t* capacityReturn);
1317   static void allocExtBuffer(uint64_t minCapacity,
1318                              uint8_t** bufReturn,
1319                              SharedInfo** infoReturn,
1320                              uint64_t* capacityReturn);
1321   static void releaseStorage(HeapStorage* storage, uint16_t freeFlags);
1322   static void freeInternalBuf(void* buf, void* userData);
1323
1324   /*
1325    * Member variables
1326    */
1327
1328   /*
1329    * Links to the next and the previous IOBuf in this chain.
1330    *
1331    * The chain is circularly linked (the last element in the chain points back
1332    * at the head), and next_ and prev_ can never be null.  If this IOBuf is the
1333    * only element in the chain, next_ and prev_ will both point to this.
1334    */
1335   IOBuf* next_{this};
1336   IOBuf* prev_{this};
1337
1338   /*
1339    * A pointer to the start of the data referenced by this IOBuf, and the
1340    * length of the data.
1341    *
1342    * This may refer to any subsection of the actual buffer capacity.
1343    */
1344   uint8_t* data_{nullptr};
1345   uint8_t* buf_{nullptr};
1346   uint64_t length_{0};
1347   uint64_t capacity_{0};
1348
1349   // Pack flags in least significant 2 bits, sharedInfo in the rest
1350   mutable uintptr_t flagsAndSharedInfo_{0};
1351
1352   static inline uintptr_t packFlagsAndSharedInfo(uintptr_t flags,
1353                                                  SharedInfo* info) {
1354     uintptr_t uinfo = reinterpret_cast<uintptr_t>(info);
1355     DCHECK_EQ(flags & ~kFlagMask, 0u);
1356     DCHECK_EQ(uinfo & kFlagMask, 0u);
1357     return flags | uinfo;
1358   }
1359
1360   inline SharedInfo* sharedInfo() const {
1361     return reinterpret_cast<SharedInfo*>(flagsAndSharedInfo_ & ~kFlagMask);
1362   }
1363
1364   inline void setSharedInfo(SharedInfo* info) {
1365     uintptr_t uinfo = reinterpret_cast<uintptr_t>(info);
1366     DCHECK_EQ(uinfo & kFlagMask, 0u);
1367     flagsAndSharedInfo_ = (flagsAndSharedInfo_ & kFlagMask) | uinfo;
1368   }
1369
1370   inline uintptr_t flags() const {
1371     return flagsAndSharedInfo_ & kFlagMask;
1372   }
1373
1374   // flags_ are changed from const methods
1375   inline void setFlags(uintptr_t flags) const {
1376     DCHECK_EQ(flags & ~kFlagMask, 0u);
1377     flagsAndSharedInfo_ |= flags;
1378   }
1379
1380   inline void clearFlags(uintptr_t flags) const {
1381     DCHECK_EQ(flags & ~kFlagMask, 0u);
1382     flagsAndSharedInfo_ &= ~flags;
1383   }
1384
1385   inline void setFlagsAndSharedInfo(uintptr_t flags, SharedInfo* info) {
1386     flagsAndSharedInfo_ = packFlagsAndSharedInfo(flags, info);
1387   }
1388
1389   struct DeleterBase {
1390     virtual ~DeleterBase() { }
1391     virtual void dispose(void* p) = 0;
1392   };
1393
1394   template <class UniquePtr>
1395   struct UniquePtrDeleter : public DeleterBase {
1396     typedef typename UniquePtr::pointer Pointer;
1397     typedef typename UniquePtr::deleter_type Deleter;
1398
1399     explicit UniquePtrDeleter(Deleter deleter) : deleter_(std::move(deleter)){ }
1400     void dispose(void* p) override {
1401       try {
1402         deleter_(static_cast<Pointer>(p));
1403         delete this;
1404       } catch (...) {
1405         abort();
1406       }
1407     }
1408
1409    private:
1410     Deleter deleter_;
1411   };
1412
1413   static void freeUniquePtrBuffer(void* ptr, void* userData) {
1414     static_cast<DeleterBase*>(userData)->dispose(ptr);
1415   }
1416 };
1417
1418 /**
1419  * Hasher for IOBuf objects. Hashes the entire chain using SpookyHashV2.
1420  */
1421 struct IOBufHash {
1422   size_t operator()(const IOBuf& buf) const;
1423   size_t operator()(const std::unique_ptr<IOBuf>& buf) const {
1424     return buf ? (*this)(*buf) : 0;
1425   }
1426 };
1427
1428 /**
1429  * Equality predicate for IOBuf objects. Compares data in the entire chain.
1430  */
1431 struct IOBufEqual {
1432   bool operator()(const IOBuf& a, const IOBuf& b) const;
1433   bool operator()(const std::unique_ptr<IOBuf>& a,
1434                   const std::unique_ptr<IOBuf>& b) const {
1435     if (!a && !b) {
1436       return true;
1437     } else if (!a || !b) {
1438       return false;
1439     } else {
1440       return (*this)(*a, *b);
1441     }
1442   }
1443 };
1444
1445 template <class UniquePtr>
1446 typename std::enable_if<detail::IsUniquePtrToSL<UniquePtr>::value,
1447                         std::unique_ptr<IOBuf>>::type
1448 IOBuf::takeOwnership(UniquePtr&& buf, size_t count) {
1449   size_t size = count * sizeof(typename UniquePtr::element_type);
1450   auto deleter = new UniquePtrDeleter<UniquePtr>(buf.get_deleter());
1451   return takeOwnership(buf.release(),
1452                        size,
1453                        &IOBuf::freeUniquePtrBuffer,
1454                        deleter);
1455 }
1456
1457 inline std::unique_ptr<IOBuf> IOBuf::copyBuffer(
1458     const void* data, uint64_t size, uint64_t headroom,
1459     uint64_t minTailroom) {
1460   uint64_t capacity = headroom + size + minTailroom;
1461   std::unique_ptr<IOBuf> buf = create(capacity);
1462   buf->advance(headroom);
1463   if (size != 0) {
1464     memcpy(buf->writableData(), data, size);
1465   }
1466   buf->append(size);
1467   return buf;
1468 }
1469
1470 inline std::unique_ptr<IOBuf> IOBuf::copyBuffer(const std::string& buf,
1471                                                 uint64_t headroom,
1472                                                 uint64_t minTailroom) {
1473   return copyBuffer(buf.data(), buf.size(), headroom, minTailroom);
1474 }
1475
1476 inline std::unique_ptr<IOBuf> IOBuf::maybeCopyBuffer(const std::string& buf,
1477                                                      uint64_t headroom,
1478                                                      uint64_t minTailroom) {
1479   if (buf.empty()) {
1480     return nullptr;
1481   }
1482   return copyBuffer(buf.data(), buf.size(), headroom, minTailroom);
1483 }
1484
1485 class IOBuf::Iterator : public boost::iterator_facade<
1486     IOBuf::Iterator,  // Derived
1487     const ByteRange,  // Value
1488     boost::forward_traversal_tag  // Category or traversal
1489   > {
1490   friend class boost::iterator_core_access;
1491  public:
1492   // Note that IOBufs are stored as a circular list without a guard node,
1493   // so pos == end is ambiguous (it may mean "begin" or "end").  To solve
1494   // the ambiguity (at the cost of one extra comparison in the "increment"
1495   // code path), we define end iterators as having pos_ == end_ == nullptr
1496   // and we only allow forward iteration.
1497   explicit Iterator(const IOBuf* pos, const IOBuf* end)
1498     : pos_(pos),
1499       end_(end) {
1500     // Sadly, we must return by const reference, not by value.
1501     if (pos_) {
1502       setVal();
1503     }
1504   }
1505
1506   Iterator() {}
1507
1508  private:
1509   void setVal() {
1510     val_ = ByteRange(pos_->data(), pos_->tail());
1511   }
1512
1513   void adjustForEnd() {
1514     if (pos_ == end_) {
1515       pos_ = end_ = nullptr;
1516       val_ = ByteRange();
1517     } else {
1518       setVal();
1519     }
1520   }
1521
1522   const ByteRange& dereference() const {
1523     return val_;
1524   }
1525
1526   bool equal(const Iterator& other) const {
1527     // We must compare end_ in addition to pos_, because forward traversal
1528     // requires that if two iterators are equal (a == b) and dereferenceable,
1529     // then ++a == ++b.
1530     return pos_ == other.pos_ && end_ == other.end_;
1531   }
1532
1533   void increment() {
1534     pos_ = pos_->next();
1535     adjustForEnd();
1536   }
1537
1538   const IOBuf* pos_{nullptr};
1539   const IOBuf* end_{nullptr};
1540   ByteRange val_;
1541 };
1542
1543 inline IOBuf::Iterator IOBuf::begin() const { return cbegin(); }
1544 inline IOBuf::Iterator IOBuf::end() const { return cend(); }
1545
1546 } // folly
1547
1548 FOLLY_POP_WARNING