2 * Copyright 2015 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #ifndef FOLLY_IO_IOBUF_H_
18 #define FOLLY_IO_IOBUF_H_
20 #include <glog/logging.h>
29 #include <type_traits>
31 #include <boost/iterator/iterator_facade.hpp>
33 #include <folly/FBString.h>
34 #include <folly/Range.h>
35 #include <folly/FBVector.h>
37 // Ignore shadowing warnings within this file, so includers can use -Wshadow.
38 #pragma GCC diagnostic push
39 #pragma GCC diagnostic ignored "-Wshadow"
44 * An IOBuf is a pointer to a buffer of data.
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
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
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.
62 * The data layout looks like this:
70 * +------------+--------------------+-----------+
71 * | headroom | data | tailroom |
72 * +------------+--------------------+-----------+
74 * buffer() data() tail() bufferEnd()
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.
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.
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.
96 * +-----------+ +---------+
97 * | IOBuf 1 | | IOBuf 2 |
98 * +-----------+ +---------+
100 * data | tail |/ data | tail
102 * +-------------------------------------+
104 * +-------------------------------------+
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.
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.
120 * A single IOBuf object can only belong to one chain at a time.
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.
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
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.
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.
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.
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
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.
168 * IOBuf Object Allocation
169 * -----------------------
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
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.
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
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.)
192 * Additionally, no copy-constructor or assignment operator currently exists,
193 * so stack-allocated IOBufs may only be moved, not copied. (Technically
194 * nothing is preventing us from adding a copy constructor and assignment
195 * operator. However, it seems like this would add the possibility for some
196 * confusion. We would need to determine if these functions would copy just a
197 * single buffer, or the entire chain.)
203 * The IOBuf class manages sharing of the underlying buffer that it points to,
204 * maintaining a reference count if multiple IOBufs are pointing at the same
207 * However, it is the callers responsibility to manage sharing and ownership of
208 * IOBuf objects themselves. The IOBuf structure does not provide room for an
209 * intrusive refcount on the IOBuf object itself, only the underlying data
210 * buffer is reference counted. If users want to share the same IOBuf object
211 * between multiple parts of the code, they are responsible for managing this
212 * sharing on their own. (For example, by using a shared_ptr. Alternatively,
213 * users always have the option of using clone() to create a second IOBuf that
214 * points to the same underlying buffer.)
217 // Is T a unique_ptr<> to a standard-layout type?
218 template <class T, class Enable=void> struct IsUniquePtrToSL
219 : public std::false_type { };
220 template <class T, class D>
221 struct IsUniquePtrToSL<
222 std::unique_ptr<T, D>,
223 typename std::enable_if<std::is_standard_layout<T>::value>::type>
224 : public std::true_type { };
225 } // namespace detail
231 enum CreateOp { CREATE };
232 enum WrapBufferOp { WRAP_BUFFER };
233 enum TakeOwnershipOp { TAKE_OWNERSHIP };
234 enum CopyBufferOp { COPY_BUFFER };
235 enum CloneOp { CLONE };
237 typedef ByteRange value_type;
238 typedef Iterator iterator;
239 typedef Iterator const_iterator;
241 typedef void (*FreeFunction)(void* buf, void* userData);
244 * Allocate a new IOBuf object with the requested capacity.
246 * Returns a new IOBuf object that must be (eventually) deleted by the
247 * caller. The returned IOBuf may actually have slightly more capacity than
250 * The data pointer will initially point to the start of the newly allocated
251 * buffer, and will have a data length of 0.
253 * Throws std::bad_alloc on error.
255 static std::unique_ptr<IOBuf> create(uint64_t capacity);
256 IOBuf(CreateOp, uint64_t capacity);
259 * Create a new IOBuf, using a single memory allocation to allocate space
260 * for both the IOBuf object and the data storage space.
262 * This saves one memory allocation. However, it can be wasteful if you
263 * later need to grow the buffer using reserve(). If the buffer needs to be
264 * reallocated, the space originally allocated will not be freed() until the
265 * IOBuf object itself is also freed. (It can also be slightly wasteful in
266 * some cases where you clone this IOBuf and then free the original IOBuf.)
268 static std::unique_ptr<IOBuf> createCombined(uint64_t capacity);
271 * Create a new IOBuf, using separate memory allocations for the IOBuf object
272 * for the IOBuf and the data storage space.
274 * This requires two memory allocations, but saves space in the long run
275 * if you know that you will need to reallocate the data buffer later.
277 static std::unique_ptr<IOBuf> createSeparate(uint64_t capacity);
280 * Allocate a new IOBuf chain with the requested total capacity, allocating
281 * no more than maxBufCapacity to each buffer.
283 static std::unique_ptr<IOBuf> createChain(
284 size_t totalCapacity, uint64_t maxBufCapacity);
287 * Create a new IOBuf pointing to an existing data buffer.
289 * The new IOBuffer will assume ownership of the buffer, and free it by
290 * calling the specified FreeFunction when the last IOBuf pointing to this
291 * buffer is destroyed. The function will be called with a pointer to the
292 * buffer as the first argument, and the supplied userData value as the
293 * second argument. The free function must never throw exceptions.
295 * If no FreeFunction is specified, the buffer will be freed using free()
296 * which will result in undefined behavior if the memory was allocated
299 * The IOBuf data pointer will initially point to the start of the buffer,
301 * In the first version of this function, the length of data is unspecified
302 * and is initialized to the capacity of the buffer
304 * In the second version, the user specifies the valid length of data
307 * On error, std::bad_alloc will be thrown. If freeOnError is true (the
308 * default) the buffer will be freed before throwing the error.
310 static std::unique_ptr<IOBuf> takeOwnership(void* buf, uint64_t capacity,
311 FreeFunction freeFn = nullptr,
312 void* userData = nullptr,
313 bool freeOnError = true) {
314 return takeOwnership(buf, capacity, capacity, freeFn,
315 userData, freeOnError);
317 IOBuf(TakeOwnershipOp op, void* buf, uint64_t capacity,
318 FreeFunction freeFn = nullptr, void* userData = nullptr,
319 bool freeOnError = true)
320 : IOBuf(op, buf, capacity, capacity, freeFn, userData, freeOnError) {}
322 static std::unique_ptr<IOBuf> takeOwnership(void* buf, uint64_t capacity,
324 FreeFunction freeFn = nullptr,
325 void* userData = nullptr,
326 bool freeOnError = true);
327 IOBuf(TakeOwnershipOp, void* buf, uint64_t capacity, uint64_t length,
328 FreeFunction freeFn = nullptr, void* userData = nullptr,
329 bool freeOnError = true);
332 * Create a new IOBuf pointing to an existing data buffer made up of
333 * count objects of a given standard-layout type.
335 * This is dangerous -- it is essentially equivalent to doing
336 * reinterpret_cast<unsigned char*> on your data -- but it's often useful
337 * for serialization / deserialization.
339 * The new IOBuffer will assume ownership of the buffer, and free it
340 * appropriately (by calling the UniquePtr's custom deleter, or by calling
341 * delete or delete[] appropriately if there is no custom deleter)
342 * when the buffer is destroyed. The custom deleter, if any, must never
345 * The IOBuf data pointer will initially point to the start of the buffer,
346 * and the length will be the full capacity of the buffer (count *
349 * On error, std::bad_alloc will be thrown, and the buffer will be freed
350 * before throwing the error.
352 template <class UniquePtr>
353 static typename std::enable_if<detail::IsUniquePtrToSL<UniquePtr>::value,
354 std::unique_ptr<IOBuf>>::type
355 takeOwnership(UniquePtr&& buf, size_t count=1);
358 * Create a new IOBuf object that points to an existing user-owned buffer.
360 * This should only be used when the caller knows the lifetime of the IOBuf
361 * object ahead of time and can ensure that all IOBuf objects that will point
362 * to this buffer will be destroyed before the buffer itself is destroyed.
364 * This buffer will not be freed automatically when the last IOBuf
365 * referencing it is destroyed. It is the caller's responsibility to free
366 * the buffer after the last IOBuf has been destroyed.
368 * The IOBuf data pointer will initially point to the start of the buffer,
369 * and the length will be the full capacity of the buffer.
371 * An IOBuf created using wrapBuffer() will always be reported as shared.
372 * unshare() may be used to create a writable copy of the buffer.
374 * On error, std::bad_alloc will be thrown.
376 static std::unique_ptr<IOBuf> wrapBuffer(const void* buf, uint64_t capacity);
377 static std::unique_ptr<IOBuf> wrapBuffer(ByteRange br) {
378 return wrapBuffer(br.data(), br.size());
380 IOBuf(WrapBufferOp op, const void* buf, uint64_t capacity);
381 IOBuf(WrapBufferOp op, ByteRange br);
384 * Convenience function to create a new IOBuf object that copies data from a
385 * user-supplied buffer, optionally allocating a given amount of
386 * headroom and tailroom.
388 static std::unique_ptr<IOBuf> copyBuffer(const void* buf, uint64_t size,
390 uint64_t minTailroom=0);
391 static std::unique_ptr<IOBuf> copyBuffer(ByteRange br,
393 uint64_t minTailroom=0) {
394 return copyBuffer(br.data(), br.size(), headroom, minTailroom);
396 IOBuf(CopyBufferOp op, const void* buf, uint64_t size,
397 uint64_t headroom=0, uint64_t minTailroom=0);
398 IOBuf(CopyBufferOp op, ByteRange br,
399 uint64_t headroom=0, uint64_t minTailroom=0);
402 * Clone an IOBuf. See the notes for cloneInto().
404 IOBuf(CloneOp, const IOBuf& src) : IOBuf() {
405 src.cloneInto(*this);
409 * Convenience function to create a new IOBuf object that copies data from a
410 * user-supplied string, optionally allocating a given amount of
411 * headroom and tailroom.
413 * Beware when attempting to invoke this function with a constant string
414 * literal and a headroom argument: you will likely end up invoking the
415 * version of copyBuffer() above. IOBuf::copyBuffer("hello", 3) will treat
416 * the first argument as a const void*, and will invoke the version of
417 * copyBuffer() above, with the size argument of 3.
419 static std::unique_ptr<IOBuf> copyBuffer(const std::string& buf,
421 uint64_t minTailroom=0);
422 IOBuf(CopyBufferOp op, const std::string& buf,
423 uint64_t headroom=0, uint64_t minTailroom=0)
424 : IOBuf(op, buf.data(), buf.size(), headroom, minTailroom) {}
427 * A version of copyBuffer() that returns a null pointer if the input string
430 static std::unique_ptr<IOBuf> maybeCopyBuffer(const std::string& buf,
432 uint64_t minTailroom=0);
435 * Convenience function to free a chain of IOBufs held by a unique_ptr.
437 static void destroy(std::unique_ptr<IOBuf>&& data) {
438 auto destroyer = std::move(data);
442 * Destroy this IOBuf.
444 * Deleting an IOBuf will automatically destroy all IOBufs in the chain.
445 * (See the comments above regarding the ownership model of IOBuf chains.
446 * All subsequent IOBufs in the chain are considered to be owned by the head
447 * of the chain. Users should only explicitly delete the head of a chain.)
449 * When each individual IOBuf is destroyed, it will release its reference
450 * count on the underlying buffer. If it was the last user of the buffer,
451 * the buffer will be freed.
456 * Check whether the chain is empty (i.e., whether the IOBufs in the
457 * chain have a total data length of zero).
459 * This method is semantically equivalent to
460 * i->computeChainDataLength()==0
461 * but may run faster because it can short-circuit as soon as it
462 * encounters a buffer with length()!=0
467 * Get the pointer to the start of the data.
469 const uint8_t* data() const {
474 * Get a writable pointer to the start of the data.
476 * The caller is responsible for calling unshare() first to ensure that it is
477 * actually safe to write to the buffer.
479 uint8_t* writableData() {
484 * Get the pointer to the end of the data.
486 const uint8_t* tail() const {
487 return data_ + length_;
491 * Get a writable pointer to the end of the data.
493 * The caller is responsible for calling unshare() first to ensure that it is
494 * actually safe to write to the buffer.
496 uint8_t* writableTail() {
497 return data_ + length_;
501 * Get the data length.
503 uint64_t length() const {
508 * Get the amount of head room.
510 * Returns the number of bytes in the buffer before the start of the data.
512 uint64_t headroom() const {
513 return data_ - buffer();
517 * Get the amount of tail room.
519 * Returns the number of bytes in the buffer after the end of the data.
521 uint64_t tailroom() const {
522 return bufferEnd() - tail();
526 * Get the pointer to the start of the buffer.
528 * Note that this is the pointer to the very beginning of the usable buffer,
529 * not the start of valid data within the buffer. Use the data() method to
530 * get a pointer to the start of the data within the buffer.
532 const uint8_t* buffer() const {
537 * Get a writable pointer to the start of the buffer.
539 * The caller is responsible for calling unshare() first to ensure that it is
540 * actually safe to write to the buffer.
542 uint8_t* writableBuffer() {
547 * Get the pointer to the end of the buffer.
549 * Note that this is the pointer to the very end of the usable buffer,
550 * not the end of valid data within the buffer. Use the tail() method to
551 * get a pointer to the end of the data within the buffer.
553 const uint8_t* bufferEnd() const {
554 return buf_ + capacity_;
558 * Get the total size of the buffer.
560 * This returns the total usable length of the buffer. Use the length()
561 * method to get the length of the actual valid data in this IOBuf.
563 uint64_t capacity() const {
568 * Get a pointer to the next IOBuf in this chain.
573 const IOBuf* next() const {
578 * Get a pointer to the previous IOBuf in this chain.
583 const IOBuf* prev() const {
588 * Shift the data forwards in the buffer.
590 * This shifts the data pointer forwards in the buffer to increase the
591 * headroom. This is commonly used to increase the headroom in a newly
594 * The caller is responsible for ensuring that there is sufficient
595 * tailroom in the buffer before calling advance().
597 * If there is a non-zero data length, advance() will use memmove() to shift
598 * the data forwards in the buffer. In this case, the caller is responsible
599 * for making sure the buffer is unshared, so it will not affect other IOBufs
600 * that may be sharing the same underlying buffer.
602 void advance(uint64_t amount) {
603 // In debug builds, assert if there is a problem.
604 assert(amount <= tailroom());
607 memmove(data_ + amount, data_, length_);
613 * Shift the data backwards in the buffer.
615 * The caller is responsible for ensuring that there is sufficient headroom
616 * in the buffer before calling retreat().
618 * If there is a non-zero data length, retreat() will use memmove() to shift
619 * the data backwards in the buffer. In this case, the caller is responsible
620 * for making sure the buffer is unshared, so it will not affect other IOBufs
621 * that may be sharing the same underlying buffer.
623 void retreat(uint64_t amount) {
624 // In debug builds, assert if there is a problem.
625 assert(amount <= headroom());
628 memmove(data_ - amount, data_, length_);
634 * Adjust the data pointer to include more valid data at the beginning.
636 * This moves the data pointer backwards to include more of the available
637 * buffer. The caller is responsible for ensuring that there is sufficient
638 * headroom for the new data. The caller is also responsible for populating
639 * this section with valid data.
641 * This does not modify any actual data in the buffer.
643 void prepend(uint64_t amount) {
644 DCHECK_LE(amount, headroom());
650 * Adjust the tail pointer to include more valid data at the end.
652 * This moves the tail pointer forwards to include more of the available
653 * buffer. The caller is responsible for ensuring that there is sufficient
654 * tailroom for the new data. The caller is also responsible for populating
655 * this section with valid data.
657 * This does not modify any actual data in the buffer.
659 void append(uint64_t amount) {
660 DCHECK_LE(amount, tailroom());
665 * Adjust the data pointer forwards to include less valid data.
667 * This moves the data pointer forwards so that the first amount bytes are no
668 * longer considered valid data. The caller is responsible for ensuring that
669 * amount is less than or equal to the actual data length.
671 * This does not modify any actual data in the buffer.
673 void trimStart(uint64_t amount) {
674 DCHECK_LE(amount, length_);
680 * Adjust the tail pointer backwards to include less valid data.
682 * This moves the tail pointer backwards so that the last amount bytes are no
683 * longer considered valid data. The caller is responsible for ensuring that
684 * amount is less than or equal to the actual data length.
686 * This does not modify any actual data in the buffer.
688 void trimEnd(uint64_t amount) {
689 DCHECK_LE(amount, length_);
696 * Postcondition: headroom() == 0, length() == 0, tailroom() == capacity()
699 data_ = writableBuffer();
704 * Ensure that this buffer has at least minHeadroom headroom bytes and at
705 * least minTailroom tailroom bytes. The buffer must be writable
706 * (you must call unshare() before this, if necessary).
708 * Postcondition: headroom() >= minHeadroom, tailroom() >= minTailroom,
709 * the data (between data() and data() + length()) is preserved.
711 void reserve(uint64_t minHeadroom, uint64_t minTailroom) {
712 // Maybe we don't need to do anything.
713 if (headroom() >= minHeadroom && tailroom() >= minTailroom) {
716 // If the buffer is empty but we have enough total room (head + tail),
717 // move the data_ pointer around.
719 headroom() + tailroom() >= minHeadroom + minTailroom) {
720 data_ = writableBuffer() + minHeadroom;
723 // Bah, we have to do actual work.
724 reserveSlow(minHeadroom, minTailroom);
728 * Return true if this IOBuf is part of a chain of multiple IOBufs, or false
729 * if this is the only IOBuf in its chain.
731 bool isChained() const {
732 assert((next_ == this) == (prev_ == this));
733 return next_ != this;
737 * Get the number of IOBufs in this chain.
739 * Beware that this method has to walk the entire chain.
740 * Use isChained() if you just want to check if this IOBuf is part of a chain
743 size_t countChainElements() const;
746 * Get the length of all the data in this IOBuf chain.
748 * Beware that this method has to walk the entire chain.
750 uint64_t computeChainDataLength() const;
753 * Insert another IOBuf chain immediately before this IOBuf.
755 * For example, if there are two IOBuf chains (A, B, C) and (D, E, F),
756 * and B->prependChain(D) is called, the (D, E, F) chain will be subsumed
757 * and become part of the chain starting at A, which will now look like
760 * Note that since IOBuf chains are circular, head->prependChain(other) can
761 * be used to append the other chain at the very end of the chain pointed to
762 * by head. For example, if there are two IOBuf chains (A, B, C) and
763 * (D, E, F), and A->prependChain(D) is called, the chain starting at A will
764 * now consist of (A, B, C, D, E, F)
766 * The elements in the specified IOBuf chain will become part of this chain,
767 * and will be owned by the head of this chain. When this chain is
768 * destroyed, all elements in the supplied chain will also be destroyed.
770 * For this reason, appendChain() only accepts an rvalue-reference to a
771 * unique_ptr(), to make it clear that it is taking ownership of the supplied
772 * chain. If you have a raw pointer, you can pass in a new temporary
773 * unique_ptr around the raw pointer. If you have an existing,
774 * non-temporary unique_ptr, you must call std::move(ptr) to make it clear
775 * that you are destroying the original pointer.
777 void prependChain(std::unique_ptr<IOBuf>&& iobuf);
780 * Append another IOBuf chain immediately after this IOBuf.
782 * For example, if there are two IOBuf chains (A, B, C) and (D, E, F),
783 * and B->appendChain(D) is called, the (D, E, F) chain will be subsumed
784 * and become part of the chain starting at A, which will now look like
787 * The elements in the specified IOBuf chain will become part of this chain,
788 * and will be owned by the head of this chain. When this chain is
789 * destroyed, all elements in the supplied chain will also be destroyed.
791 * For this reason, appendChain() only accepts an rvalue-reference to a
792 * unique_ptr(), to make it clear that it is taking ownership of the supplied
793 * chain. If you have a raw pointer, you can pass in a new temporary
794 * unique_ptr around the raw pointer. If you have an existing,
795 * non-temporary unique_ptr, you must call std::move(ptr) to make it clear
796 * that you are destroying the original pointer.
798 void appendChain(std::unique_ptr<IOBuf>&& iobuf) {
799 // Just use prependChain() on the next element in our chain
800 next_->prependChain(std::move(iobuf));
804 * Remove this IOBuf from its current chain.
806 * Since ownership of all elements an IOBuf chain is normally maintained by
807 * the head of the chain, unlink() transfers ownership of this IOBuf from the
808 * chain and gives it to the caller. A new unique_ptr to the IOBuf is
809 * returned to the caller. The caller must store the returned unique_ptr (or
810 * call release() on it) to take ownership, otherwise the IOBuf will be
811 * immediately destroyed.
813 * Since unlink transfers ownership of the IOBuf to the caller, be careful
814 * not to call unlink() on the head of a chain if you already maintain
815 * ownership on the head of the chain via other means. The pop() method
816 * is a better choice for that situation.
818 std::unique_ptr<IOBuf> unlink() {
819 next_->prev_ = prev_;
820 prev_->next_ = next_;
823 return std::unique_ptr<IOBuf>(this);
827 * Remove this IOBuf from its current chain and return a unique_ptr to
828 * the IOBuf that formerly followed it in the chain.
830 std::unique_ptr<IOBuf> pop() {
832 next_->prev_ = prev_;
833 prev_->next_ = next_;
836 return std::unique_ptr<IOBuf>((next == this) ? nullptr : next);
840 * Remove a subchain from this chain.
842 * Remove the subchain starting at head and ending at tail from this chain.
844 * Returns a unique_ptr pointing to head. (In other words, ownership of the
845 * head of the subchain is transferred to the caller.) If the caller ignores
846 * the return value and lets the unique_ptr be destroyed, the subchain will
847 * be immediately destroyed.
849 * The subchain referenced by the specified head and tail must be part of the
850 * same chain as the current IOBuf, but must not contain the current IOBuf.
851 * However, the specified head and tail may be equal to each other (i.e.,
852 * they may be a subchain of length 1).
854 std::unique_ptr<IOBuf> separateChain(IOBuf* head, IOBuf* tail) {
855 assert(head != this);
856 assert(tail != this);
858 head->prev_->next_ = tail->next_;
859 tail->next_->prev_ = head->prev_;
864 return std::unique_ptr<IOBuf>(head);
868 * Return true if at least one of the IOBufs in this chain are shared,
869 * or false if all of the IOBufs point to unique buffers.
871 * Use isSharedOne() to only check this IOBuf rather than the entire chain.
873 bool isShared() const {
874 const IOBuf* current = this;
876 if (current->isSharedOne()) {
879 current = current->next_;
880 if (current == this) {
887 * Return true if other IOBufs are also pointing to the buffer used by this
888 * IOBuf, and false otherwise.
890 * If this IOBuf points at a buffer owned by another (non-IOBuf) part of the
891 * code (i.e., if the IOBuf was created using wrapBuffer(), or was cloned
892 * from such an IOBuf), it is always considered shared.
894 * This only checks the current IOBuf, and not other IOBufs in the chain.
896 bool isSharedOne() const {
897 // If this is a user-owned buffer, it is always considered shared
898 if (UNLIKELY(!sharedInfo())) {
902 if (LIKELY(!(flags() & kFlagMaybeShared))) {
906 // kFlagMaybeShared is set, so we need to check the reference count.
907 // (Checking the reference count requires an atomic operation, which is why
908 // we prefer to only check kFlagMaybeShared if possible.)
909 bool shared = sharedInfo()->refcount.load(std::memory_order_acquire) > 1;
911 // we're the last one left
912 clearFlags(kFlagMaybeShared);
918 * Ensure that this IOBuf has a unique buffer that is not shared by other
921 * unshare() operates on an entire chain of IOBuf objects. If the chain is
922 * shared, it may also coalesce the chain when making it unique. If the
923 * chain is coalesced, subsequent IOBuf objects in the current chain will be
924 * automatically deleted.
926 * Note that buffers owned by other (non-IOBuf) users are automatically
929 * Throws std::bad_alloc on error. On error the IOBuf chain will be
932 * Currently unshare may also throw std::overflow_error if it tries to
933 * coalesce. (TODO: In the future it would be nice if unshare() were smart
934 * enough not to coalesce the entire buffer if the data is too large.
935 * However, in practice this seems unlikely to become an issue.)
946 * Ensure that this IOBuf has a unique buffer that is not shared by other
949 * unshareOne() operates on a single IOBuf object. This IOBuf will have a
950 * unique buffer after unshareOne() returns, but other IOBufs in the chain
951 * may still be shared after unshareOne() returns.
953 * Throws std::bad_alloc on error. On error the IOBuf will be unmodified.
962 * Coalesce this IOBuf chain into a single buffer.
964 * This method moves all of the data in this IOBuf chain into a single
965 * contiguous buffer, if it is not already in one buffer. After coalesce()
966 * returns, this IOBuf will be a chain of length one. Other IOBufs in the
967 * chain will be automatically deleted.
969 * After coalescing, the IOBuf will have at least as much headroom as the
970 * first IOBuf in the chain, and at least as much tailroom as the last IOBuf
973 * Throws std::bad_alloc on error. On error the IOBuf chain will be
976 * Returns ByteRange that points to the data IOBuf stores.
978 ByteRange coalesce() {
982 return ByteRange(data_, length_);
986 * Ensure that this chain has at least maxLength bytes available as a
987 * contiguous memory range.
989 * This method coalesces whole buffers in the chain into this buffer as
990 * necessary until this buffer's length() is at least maxLength.
992 * After coalescing, the IOBuf will have at least as much headroom as the
993 * first IOBuf in the chain, and at least as much tailroom as the last IOBuf
994 * that was coalesced.
996 * Throws std::bad_alloc or std::overflow_error on error. On error the IOBuf
997 * chain will be unmodified. Throws std::overflow_error if maxLength is
998 * longer than the total chain length.
1000 * Upon return, either enough of the chain was coalesced into a contiguous
1001 * region, or the entire chain was coalesced. That is,
1002 * length() >= maxLength || !isChained() is true.
1004 void gather(uint64_t maxLength) {
1005 if (!isChained() || length_ >= maxLength) {
1008 coalesceSlow(maxLength);
1012 * Return a new IOBuf chain sharing the same data as this chain.
1014 * The new IOBuf chain will normally point to the same underlying data
1015 * buffers as the original chain. (The one exception to this is if some of
1016 * the IOBufs in this chain contain small internal data buffers which cannot
1019 std::unique_ptr<IOBuf> clone() const;
1022 * Return a new IOBuf with the same data as this IOBuf.
1024 * The new IOBuf returned will not be part of a chain (even if this IOBuf is
1025 * part of a larger chain).
1027 std::unique_ptr<IOBuf> cloneOne() const;
1030 * Similar to Clone(). But use other as the head node. Other nodes in the
1031 * chain (if any) will be allocted on heap.
1033 void cloneInto(IOBuf& other) const;
1036 * Similar to CloneOne(). But to fill an existing IOBuf instead of a new
1039 void cloneOneInto(IOBuf& other) const;
1042 * Return an iovector suitable for e.g. writev()
1044 * auto iov = buf->getIov();
1045 * auto xfer = writev(fd, iov.data(), iov.size());
1047 * Naturally, the returned iovector is invalid if you modify the buffer
1050 folly::fbvector<struct iovec> getIov() const;
1053 * Update an existing iovec array with the IOBuf data.
1055 * New iovecs will be appended to the existing vector; anything already
1056 * present in the vector will be left unchanged.
1058 * Naturally, the returned iovec data will be invalid if you modify the
1061 void appendToIov(folly::fbvector<struct iovec>* iov) const;
1064 * Fill an iovec array with the IOBuf data.
1066 * Returns the number of iovec filled. If there are more buffer than
1067 * iovec, returns 0. This version is suitable to use with stack iovec
1070 * Naturally, the filled iovec data will be invalid if you modify the
1073 size_t fillIov(struct iovec* iov, size_t len) const;
1076 * Overridden operator new and delete.
1077 * These perform specialized memory management to help support
1078 * createCombined(), which allocates IOBuf objects together with the buffer
1081 void* operator new(size_t size);
1082 void* operator new(size_t size, void* ptr);
1083 void operator delete(void* ptr);
1086 * Destructively convert this IOBuf to a fbstring efficiently.
1087 * We rely on fbstring's AcquireMallocatedString constructor to
1090 fbstring moveToFbString();
1093 * Iteration support: a chain of IOBufs may be iterated through using
1094 * STL-style iterators over const ByteRanges. Iterators are only invalidated
1095 * if the IOBuf that they currently point to is removed.
1097 Iterator cbegin() const;
1098 Iterator cend() const;
1099 Iterator begin() const;
1100 Iterator end() const;
1103 * Allocate a new null buffer.
1105 * This can be used to allocate an empty IOBuf on the stack. It will have no
1106 * space allocated for it. This is generally useful only to later use move
1107 * assignment to fill out the IOBuf.
1112 * Move constructor and assignment operator.
1114 * In general, you should only ever move the head of an IOBuf chain.
1115 * Internal nodes in an IOBuf chain are owned by the head of the chain, and
1116 * should not be moved from. (Technically, nothing prevents you from moving
1117 * a non-head node, but the moved-to node will replace the moved-from node in
1118 * the chain. This has implications for ownership, since non-head nodes are
1119 * owned by the chain head. You are then responsible for relinquishing
1120 * ownership of the moved-to node, and manually deleting the moved-from
1123 * With the move assignment operator, the destination of the move should be
1124 * the head of an IOBuf chain or a solitary IOBuf not part of a chain. If
1125 * the move destination is part of a chain, all other IOBufs in the chain
1128 * (We currently don't provide a copy constructor or assignment operator.
1129 * The main reason is because it is not clear these operations should copy
1130 * the entire chain or just the single IOBuf.)
1132 IOBuf(IOBuf&& other) noexcept;
1133 IOBuf& operator=(IOBuf&& other) noexcept;
1136 enum FlagsEnum : uintptr_t {
1137 // Adding any more flags would not work on 32-bit architectures,
1138 // as these flags are stashed in the least significant 2 bits of a
1139 // max-align-aligned pointer.
1140 kFlagFreeSharedInfo = 0x1,
1141 kFlagMaybeShared = 0x2,
1142 kFlagMask = kFlagFreeSharedInfo | kFlagMaybeShared
1147 SharedInfo(FreeFunction fn, void* arg);
1149 // A pointer to a function to call to free the buffer when the refcount
1150 // hits 0. If this is null, free() will be used instead.
1151 FreeFunction freeFn;
1153 std::atomic<uint32_t> refcount;
1155 // Helper structs for use by operator new and delete
1158 struct HeapFullStorage;
1160 // Forbidden copy constructor and assignment opererator
1161 IOBuf(IOBuf const &);
1162 IOBuf& operator=(IOBuf const &);
1165 * Create a new IOBuf pointing to an external buffer.
1167 * The caller is responsible for holding a reference count for this new
1168 * IOBuf. The IOBuf constructor does not automatically increment the
1171 struct InternalConstructor {}; // avoid conflicts
1172 IOBuf(InternalConstructor, uintptr_t flagsAndSharedInfo,
1173 uint8_t* buf, uint64_t capacity,
1174 uint8_t* data, uint64_t length);
1176 void unshareOneSlow();
1177 void unshareChained();
1178 void coalesceSlow();
1179 void coalesceSlow(size_t maxLength);
1180 // newLength must be the entire length of the buffers between this and
1181 // end (no truncation)
1182 void coalesceAndReallocate(
1186 size_t newTailroom);
1187 void coalesceAndReallocate(size_t newLength, IOBuf* end) {
1188 coalesceAndReallocate(headroom(), newLength, end, end->prev_->tailroom());
1190 void decrementRefcount();
1191 void reserveSlow(uint64_t minHeadroom, uint64_t minTailroom);
1192 void freeExtBuffer();
1194 static size_t goodExtBufferSize(uint64_t minCapacity);
1195 static void initExtBuffer(uint8_t* buf, size_t mallocSize,
1196 SharedInfo** infoReturn,
1197 uint64_t* capacityReturn);
1198 static void allocExtBuffer(uint64_t minCapacity,
1199 uint8_t** bufReturn,
1200 SharedInfo** infoReturn,
1201 uint64_t* capacityReturn);
1202 static void releaseStorage(HeapStorage* storage, uint16_t freeFlags);
1203 static void freeInternalBuf(void* buf, void* userData);
1210 * Links to the next and the previous IOBuf in this chain.
1212 * The chain is circularly linked (the last element in the chain points back
1213 * at the head), and next_ and prev_ can never be null. If this IOBuf is the
1214 * only element in the chain, next_ and prev_ will both point to this.
1220 * A pointer to the start of the data referenced by this IOBuf, and the
1221 * length of the data.
1223 * This may refer to any subsection of the actual buffer capacity.
1225 uint8_t* data_{nullptr};
1226 uint8_t* buf_{nullptr};
1227 uint64_t length_{0};
1228 uint64_t capacity_{0};
1230 // Pack flags in least significant 2 bits, sharedInfo in the rest
1231 mutable uintptr_t flagsAndSharedInfo_{0};
1233 static inline uintptr_t packFlagsAndSharedInfo(uintptr_t flags,
1235 uintptr_t uinfo = reinterpret_cast<uintptr_t>(info);
1236 DCHECK_EQ(flags & ~kFlagMask, 0);
1237 DCHECK_EQ(uinfo & kFlagMask, 0);
1238 return flags | uinfo;
1241 inline SharedInfo* sharedInfo() const {
1242 return reinterpret_cast<SharedInfo*>(flagsAndSharedInfo_ & ~kFlagMask);
1245 inline void setSharedInfo(SharedInfo* info) {
1246 uintptr_t uinfo = reinterpret_cast<uintptr_t>(info);
1247 DCHECK_EQ(uinfo & kFlagMask, 0);
1248 flagsAndSharedInfo_ = (flagsAndSharedInfo_ & kFlagMask) | uinfo;
1251 inline uintptr_t flags() const {
1252 return flagsAndSharedInfo_ & kFlagMask;
1255 // flags_ are changed from const methods
1256 inline void setFlags(uintptr_t flags) const {
1257 DCHECK_EQ(flags & ~kFlagMask, 0);
1258 flagsAndSharedInfo_ |= flags;
1261 inline void clearFlags(uintptr_t flags) const {
1262 DCHECK_EQ(flags & ~kFlagMask, 0);
1263 flagsAndSharedInfo_ &= ~flags;
1266 inline void setFlagsAndSharedInfo(uintptr_t flags, SharedInfo* info) {
1267 flagsAndSharedInfo_ = packFlagsAndSharedInfo(flags, info);
1270 struct DeleterBase {
1271 virtual ~DeleterBase() { }
1272 virtual void dispose(void* p) = 0;
1275 template <class UniquePtr>
1276 struct UniquePtrDeleter : public DeleterBase {
1277 typedef typename UniquePtr::pointer Pointer;
1278 typedef typename UniquePtr::deleter_type Deleter;
1280 explicit UniquePtrDeleter(Deleter deleter) : deleter_(std::move(deleter)){ }
1281 void dispose(void* p) {
1283 deleter_(static_cast<Pointer>(p));
1294 static void freeUniquePtrBuffer(void* ptr, void* userData) {
1295 static_cast<DeleterBase*>(userData)->dispose(ptr);
1300 * Hasher for IOBuf objects. Hashes the entire chain using SpookyHashV2.
1303 size_t operator()(const IOBuf& buf) const;
1304 size_t operator()(const std::unique_ptr<IOBuf>& buf) const {
1305 return buf ? (*this)(*buf) : 0;
1310 * Equality predicate for IOBuf objects. Compares data in the entire chain.
1313 bool operator()(const IOBuf& a, const IOBuf& b) const;
1314 bool operator()(const std::unique_ptr<IOBuf>& a,
1315 const std::unique_ptr<IOBuf>& b) const {
1318 } else if (!a || !b) {
1321 return (*this)(*a, *b);
1326 template <class UniquePtr>
1327 typename std::enable_if<detail::IsUniquePtrToSL<UniquePtr>::value,
1328 std::unique_ptr<IOBuf>>::type
1329 IOBuf::takeOwnership(UniquePtr&& buf, size_t count) {
1330 size_t size = count * sizeof(typename UniquePtr::element_type);
1331 auto deleter = new UniquePtrDeleter<UniquePtr>(buf.get_deleter());
1332 return takeOwnership(buf.release(),
1334 &IOBuf::freeUniquePtrBuffer,
1338 inline std::unique_ptr<IOBuf> IOBuf::copyBuffer(
1339 const void* data, uint64_t size, uint64_t headroom,
1340 uint64_t minTailroom) {
1341 uint64_t capacity = headroom + size + minTailroom;
1342 std::unique_ptr<IOBuf> buf = create(capacity);
1343 buf->advance(headroom);
1344 memcpy(buf->writableData(), data, size);
1349 inline std::unique_ptr<IOBuf> IOBuf::copyBuffer(const std::string& buf,
1351 uint64_t minTailroom) {
1352 return copyBuffer(buf.data(), buf.size(), headroom, minTailroom);
1355 inline std::unique_ptr<IOBuf> IOBuf::maybeCopyBuffer(const std::string& buf,
1357 uint64_t minTailroom) {
1361 return copyBuffer(buf.data(), buf.size(), headroom, minTailroom);
1364 class IOBuf::Iterator : public boost::iterator_facade<
1365 IOBuf::Iterator, // Derived
1366 const ByteRange, // Value
1367 boost::forward_traversal_tag // Category or traversal
1369 friend class boost::iterator_core_access;
1371 // Note that IOBufs are stored as a circular list without a guard node,
1372 // so pos == end is ambiguous (it may mean "begin" or "end"). To solve
1373 // the ambiguity (at the cost of one extra comparison in the "increment"
1374 // code path), we define end iterators as having pos_ == end_ == nullptr
1375 // and we only allow forward iteration.
1376 explicit Iterator(const IOBuf* pos, const IOBuf* end)
1379 // Sadly, we must return by const reference, not by value.
1387 val_ = ByteRange(pos_->data(), pos_->tail());
1390 void adjustForEnd() {
1392 pos_ = end_ = nullptr;
1399 const ByteRange& dereference() const {
1403 bool equal(const Iterator& other) const {
1404 // We must compare end_ in addition to pos_, because forward traversal
1405 // requires that if two iterators are equal (a == b) and dereferenceable,
1407 return pos_ == other.pos_ && end_ == other.end_;
1411 pos_ = pos_->next();
1420 inline IOBuf::Iterator IOBuf::begin() const { return cbegin(); }
1421 inline IOBuf::Iterator IOBuf::end() const { return cend(); }
1425 #pragma GCC diagnostic pop
1427 #endif // FOLLY_IO_IOBUF_H_