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