2 * Copyright 2013 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>
28 #include <type_traits>
30 #include <boost/iterator/iterator_facade.hpp>
32 #include "folly/FBString.h"
33 #include "folly/Range.h"
38 * An IOBuf is a pointer to a buffer of data.
40 * IOBuf objects are intended to be used primarily for networking code, and are
41 * modelled somewhat after FreeBSD's mbuf data structure, and Linux's sk_buff
44 * IOBuf objects facilitate zero-copy network programming, by allowing multiple
45 * IOBuf objects to point to the same underlying buffer of data, using a
46 * reference count to track when the buffer is no longer needed and can be
53 * The IOBuf itself is a small object containing a pointer to the buffer and
54 * information about which segment of the buffer contains valid data.
56 * The data layout looks like this:
64 * +------------+--------------------+-----------+
65 * | headroom | data | tailroom |
66 * +------------+--------------------+-----------+
68 * buffer() data() tail() bufferEnd()
70 * The length() method returns the length of the valid data; capacity()
71 * returns the entire capacity of the buffer (from buffer() to bufferEnd()).
72 * The headroom() and tailroom() methods return the amount of unused capacity
73 * available before and after the data.
79 * The buffer itself is reference counted, and multiple IOBuf objects may point
80 * to the same buffer. Each IOBuf may point to a different section of valid
81 * data within the underlying buffer. For example, if multiple protocol
82 * requests are read from the network into a single buffer, a separate IOBuf
83 * may be created for each request, all sharing the same underlying buffer.
85 * In other words, when multiple IOBufs share the same underlying buffer, the
86 * data() and tail() methods on each IOBuf may point to a different segment of
87 * the data. However, the buffer() and bufferEnd() methods will point to the
88 * same location for all IOBufs sharing the same underlying buffer.
90 * +-----------+ +---------+
91 * | IOBuf 1 | | IOBuf 2 |
92 * +-----------+ +---------+
94 * data | tail |/ data | tail
96 * +-------------------------------------+
98 * +-------------------------------------+
100 * If you only read data from an IOBuf, you don't need to worry about other
101 * IOBuf objects possibly sharing the same underlying buffer. However, if you
102 * ever write to the buffer you need to first ensure that no other IOBufs point
103 * to the same buffer. The unshare() method may be used to ensure that you
104 * have an unshared buffer.
110 * IOBuf objects also contain pointers to next and previous IOBuf objects.
111 * This can be used to represent a single logical piece of data that its stored
112 * in non-contiguous chunks in separate buffers.
114 * A single IOBuf object can only belong to one chain at a time.
116 * IOBuf chains are always circular. The "prev" pointer in the head of the
117 * chain points to the tail of the chain. However, it is up to the user to
118 * decide which IOBuf is the head. Internally the IOBuf code does not care
119 * which element is the head.
121 * The lifetime of all IOBufs in the chain are linked: when one element in the
122 * chain is deleted, all other chained elements are also deleted. Conceptually
123 * it is simplest to treat this as if the head of the chain owns all other
124 * IOBufs in the chain. When you delete the head of the chain, it will delete
125 * the other elements as well. For this reason, prependChain() and
126 * appendChain() take ownership of of the new elements being added to this
129 * When the coalesce() method is used to coalesce an entire IOBuf chain into a
130 * single IOBuf, all other IOBufs in the chain are eliminated and automatically
131 * deleted. The unshare() method may coalesce the chain; if it does it will
132 * similarly delete all IOBufs eliminated from the chain.
134 * As discussed in the following section, it is up to the user to maintain a
135 * lock around the entire IOBuf chain if multiple threads need to access the
136 * chain. IOBuf does not provide any internal locking.
142 * When used in multithread programs, a single IOBuf object should only be used
143 * in a single thread at a time. If a caller uses a single IOBuf across
144 * multiple threads the caller is responsible for using an external lock to
145 * synchronize access to the IOBuf.
147 * Two separate IOBuf objects may be accessed concurrently in separate threads
148 * without locking, even if they point to the same underlying buffer. The
149 * buffer reference count is always accessed atomically, and no other
150 * operations should affect other IOBufs that point to the same data segment.
151 * The caller is responsible for using unshare() to ensure that the data buffer
152 * is not shared by other IOBufs before writing to it, and this ensures that
153 * the data itself is not modified in one thread while also being accessed from
156 * For IOBuf chains, no two IOBufs in the same chain should be accessed
157 * simultaneously in separate threads. The caller must maintain a lock around
158 * the entire chain if the chain, or individual IOBufs in the chain, may be
159 * accessed by multiple threads.
162 * IOBuf Object Allocation/Sharing
163 * -------------------------------
165 * IOBuf objects themselves are always allocated on the heap. The IOBuf
166 * constructors are private, so IOBuf objects may not be created on the stack.
167 * In part this is done since some IOBuf objects use small-buffer optimization
168 * and contain the buffer data immediately after the IOBuf object itself. The
169 * coalesce() and unshare() methods also expect to be able to delete subsequent
170 * IOBuf objects in the chain if they are no longer needed due to coalescing.
172 * The IOBuf structure also does not provide room for an intrusive refcount on
173 * the IOBuf object itself, only the underlying data buffer is reference
174 * counted. If users want to share the same IOBuf object between multiple
175 * parts of the code, they are responsible for managing this sharing on their
176 * own. (For example, by using a shared_ptr. Alternatively, users always have
177 * the option of using clone() to create a second IOBuf that points to the same
178 * underlying buffer.)
180 * With jemalloc, allocating small objects like IOBuf objects should be
181 * relatively fast, and the cost of allocating IOBuf objects on the heap and
182 * cloning new IOBufs should be relatively cheap.
185 // Is T a unique_ptr<> to a standard-layout type?
186 template <class T, class Enable=void> struct IsUniquePtrToSL
187 : public std::false_type { };
188 template <class T, class D>
189 struct IsUniquePtrToSL<
190 std::unique_ptr<T, D>,
191 typename std::enable_if<std::is_standard_layout<T>::value>::type>
192 : public std::true_type { };
193 } // namespace detail
199 typedef ByteRange value_type;
200 typedef Iterator iterator;
201 typedef Iterator const_iterator;
203 typedef void (*FreeFunction)(void* buf, void* userData);
206 * Allocate a new IOBuf object with the requested capacity.
208 * Returns a new IOBuf object that must be (eventually) deleted by the
209 * caller. The returned IOBuf may actually have slightly more capacity than
212 * The data pointer will initially point to the start of the newly allocated
213 * buffer, and will have a data length of 0.
215 * Throws std::bad_alloc on error.
217 static std::unique_ptr<IOBuf> create(uint32_t capacity);
220 * Create a new IOBuf pointing to an existing data buffer.
222 * The new IOBuffer will assume ownership of the buffer, and free it by
223 * calling the specified FreeFunction when the last IOBuf pointing to this
224 * buffer is destroyed. The function will be called with a pointer to the
225 * buffer as the first argument, and the supplied userData value as the
226 * second argument. The free function must never throw exceptions.
228 * If no FreeFunction is specified, the buffer will be freed using free().
230 * The IOBuf data pointer will initially point to the start of the buffer,
232 * In the first version of this function, the length of data is unspecified
233 * and is initialized to the capacity of the buffer
235 * In the second version, the user specifies the valid length of data
238 * On error, std::bad_alloc will be thrown. If freeOnError is true (the
239 * default) the buffer will be freed before throwing the error.
241 static std::unique_ptr<IOBuf> takeOwnership(void* buf, uint32_t capacity,
242 FreeFunction freeFn = NULL,
243 void* userData = NULL,
244 bool freeOnError = true) {
245 return takeOwnership(buf, capacity, capacity, freeFn,
246 userData, freeOnError);
249 static std::unique_ptr<IOBuf> takeOwnership(void* buf, uint32_t capacity,
251 FreeFunction freeFn = NULL,
252 void* userData = NULL,
253 bool freeOnError = true);
256 * Create a new IOBuf pointing to an existing data buffer made up of
257 * count objects of a given standard-layout type.
259 * This is dangerous -- it is essentially equivalent to doing
260 * reinterpret_cast<unsigned char*> on your data -- but it's often useful
261 * for serialization / deserialization.
263 * The new IOBuffer will assume ownership of the buffer, and free it
264 * appropriately (by calling the UniquePtr's custom deleter, or by calling
265 * delete or delete[] appropriately if there is no custom deleter)
266 * when the buffer is destroyed. The custom deleter, if any, must never
269 * The IOBuf data pointer will initially point to the start of the buffer,
270 * and the length will be the full capacity of the buffer (count *
273 * On error, std::bad_alloc will be thrown, and the buffer will be freed
274 * before throwing the error.
276 template <class UniquePtr>
277 static typename std::enable_if<detail::IsUniquePtrToSL<UniquePtr>::value,
278 std::unique_ptr<IOBuf>>::type
279 takeOwnership(UniquePtr&& buf, size_t count=1);
282 * Create a new IOBuf object that points to an existing user-owned buffer.
284 * This should only be used when the caller knows the lifetime of the IOBuf
285 * object ahead of time and can ensure that all IOBuf objects that will point
286 * to this buffer will be destroyed before the buffer itself is destroyed.
288 * This buffer will not be freed automatically when the last IOBuf
289 * referencing it is destroyed. It is the caller's responsibility to free
290 * the buffer after the last IOBuf has been destroyed.
292 * The IOBuf data pointer will initially point to the start of the buffer,
293 * and the length will be the full capacity of the buffer.
295 * An IOBuf created using wrapBuffer() will always be reported as shared.
296 * unshare() may be used to create a writable copy of the buffer.
298 * On error, std::bad_alloc will be thrown.
300 static std::unique_ptr<IOBuf> wrapBuffer(const void* buf, uint32_t capacity);
303 * Convenience function to create a new IOBuf object that copies data from a
304 * user-supplied buffer, optionally allocating a given amount of
305 * headroom and tailroom.
307 static std::unique_ptr<IOBuf> copyBuffer(const void* buf, uint32_t size,
309 uint32_t minTailroom=0);
312 * Convenience function to create a new IOBuf object that copies data from a
313 * user-supplied string, optionally allocating a given amount of
314 * headroom and tailroom.
316 * Beware when attempting to invoke this function with a constant string
317 * literal and a headroom argument: you will likely end up invoking the
318 * version of copyBuffer() above. IOBuf::copyBuffer("hello", 3) will treat
319 * the first argument as a const void*, and will invoke the version of
320 * copyBuffer() above, with the size argument of 3.
322 static std::unique_ptr<IOBuf> copyBuffer(const std::string& buf,
324 uint32_t minTailroom=0);
327 * A version of copyBuffer() that returns a null pointer if the input string
330 static std::unique_ptr<IOBuf> maybeCopyBuffer(const std::string& buf,
332 uint32_t minTailroom=0);
335 * Convenience function to free a chain of IOBufs held by a unique_ptr.
337 static void destroy(std::unique_ptr<IOBuf>&& data) {
338 auto destroyer = std::move(data);
342 * Destroy this IOBuf.
344 * Deleting an IOBuf will automatically destroy all IOBufs in the chain.
345 * (See the comments above regarding the ownership model of IOBuf chains.
346 * All subsequent IOBufs in the chain are considered to be owned by the head
347 * of the chain. Users should only explicitly delete the head of a chain.)
349 * When each individual IOBuf is destroyed, it will release its reference
350 * count on the underlying buffer. If it was the last user of the buffer,
351 * the buffer will be freed.
356 * Check whether the chain is empty (i.e., whether the IOBufs in the
357 * chain have a total data length of zero).
359 * This method is semantically equivalent to
360 * i->computeChainDataLength()==0
361 * but may run faster because it can short-circuit as soon as it
362 * encounters a buffer with length()!=0
367 * Get the pointer to the start of the data.
369 const uint8_t* data() const {
374 * Get a writable pointer to the start of the data.
376 * The caller is responsible for calling unshare() first to ensure that it is
377 * actually safe to write to the buffer.
379 uint8_t* writableData() {
384 * Get the pointer to the end of the data.
386 const uint8_t* tail() const {
387 return data_ + length_;
391 * Get a writable pointer to the end of the data.
393 * The caller is responsible for calling unshare() first to ensure that it is
394 * actually safe to write to the buffer.
396 uint8_t* writableTail() {
397 return data_ + length_;
401 * Get the data length.
403 uint32_t length() const {
408 * Get the amount of head room.
410 * Returns the number of bytes in the buffer before the start of the data.
412 uint32_t headroom() const {
413 return data_ - buffer();
417 * Get the amount of tail room.
419 * Returns the number of bytes in the buffer after the end of the data.
421 uint32_t tailroom() const {
422 return bufferEnd() - tail();
426 * Get the pointer to the start of the buffer.
428 * Note that this is the pointer to the very beginning of the usable buffer,
429 * not the start of valid data within the buffer. Use the data() method to
430 * get a pointer to the start of the data within the buffer.
432 const uint8_t* buffer() const {
433 return (flags_ & kFlagExt) ? ext_.buf : int_.buf;
437 * Get a writable pointer to the start of the buffer.
439 * The caller is responsible for calling unshare() first to ensure that it is
440 * actually safe to write to the buffer.
442 uint8_t* writableBuffer() {
443 return (flags_ & kFlagExt) ? ext_.buf : int_.buf;
447 * Get the pointer to the end of the buffer.
449 * Note that this is the pointer to the very end of the usable buffer,
450 * not the end of valid data within the buffer. Use the tail() method to
451 * get a pointer to the end of the data within the buffer.
453 const uint8_t* bufferEnd() const {
454 return (flags_ & kFlagExt) ?
455 ext_.buf + ext_.capacity :
456 int_.buf + kMaxInternalDataSize;
460 * Get the total size of the buffer.
462 * This returns the total usable length of the buffer. Use the length()
463 * method to get the length of the actual valid data in this IOBuf.
465 uint32_t capacity() const {
466 return (flags_ & kFlagExt) ? ext_.capacity : kMaxInternalDataSize;
470 * Get a pointer to the next IOBuf in this chain.
475 const IOBuf* next() const {
480 * Get a pointer to the previous IOBuf in this chain.
485 const IOBuf* prev() const {
490 * Shift the data forwards in the buffer.
492 * This shifts the data pointer forwards in the buffer to increase the
493 * headroom. This is commonly used to increase the headroom in a newly
496 * The caller is responsible for ensuring that there is sufficient
497 * tailroom in the buffer before calling advance().
499 * If there is a non-zero data length, advance() will use memmove() to shift
500 * the data forwards in the buffer. In this case, the caller is responsible
501 * for making sure the buffer is unshared, so it will not affect other IOBufs
502 * that may be sharing the same underlying buffer.
504 void advance(uint32_t amount) {
505 // In debug builds, assert if there is a problem.
506 assert(amount <= tailroom());
509 memmove(data_ + amount, data_, length_);
515 * Shift the data backwards in the buffer.
517 * The caller is responsible for ensuring that there is sufficient headroom
518 * in the buffer before calling retreat().
520 * If there is a non-zero data length, retreat() will use memmove() to shift
521 * the data backwards in the buffer. In this case, the caller is responsible
522 * for making sure the buffer is unshared, so it will not affect other IOBufs
523 * that may be sharing the same underlying buffer.
525 void retreat(uint32_t amount) {
526 // In debug builds, assert if there is a problem.
527 assert(amount <= headroom());
530 memmove(data_ - amount, data_, length_);
536 * Adjust the data pointer to include more valid data at the beginning.
538 * This moves the data pointer backwards to include more of the available
539 * buffer. The caller is responsible for ensuring that there is sufficient
540 * headroom for the new data. The caller is also responsible for populating
541 * this section with valid data.
543 * This does not modify any actual data in the buffer.
545 void prepend(uint32_t amount) {
546 CHECK(amount <= headroom());
552 * Adjust the tail pointer to include more valid data at the end.
554 * This moves the tail pointer forwards to include more of the available
555 * buffer. The caller is responsible for ensuring that there is sufficient
556 * tailroom for the new data. The caller is also responsible for populating
557 * this section with valid data.
559 * This does not modify any actual data in the buffer.
561 void append(uint32_t amount) {
562 CHECK(amount <= tailroom());
567 * Adjust the data pointer forwards to include less valid data.
569 * This moves the data pointer forwards so that the first amount bytes are no
570 * longer considered valid data. The caller is responsible for ensuring that
571 * amount is less than or equal to the actual data length.
573 * This does not modify any actual data in the buffer.
575 void trimStart(uint32_t amount) {
576 CHECK(amount <= length_);
582 * Adjust the tail pointer backwards to include less valid data.
584 * This moves the tail pointer backwards so that the last amount bytes are no
585 * longer considered valid data. The caller is responsible for ensuring that
586 * amount is less than or equal to the actual data length.
588 * This does not modify any actual data in the buffer.
590 void trimEnd(uint32_t amount) {
591 CHECK(amount <= length_);
598 * Postcondition: headroom() == 0, length() == 0, tailroom() == capacity()
601 data_ = writableBuffer();
606 * Ensure that this buffer has at least minHeadroom headroom bytes and at
607 * least minTailroom tailroom bytes. The buffer must be writable
608 * (you must call unshare() before this, if necessary).
610 * Postcondition: headroom() >= minHeadroom, tailroom() >= minTailroom,
611 * the data (between data() and data() + length()) is preserved.
613 void reserve(uint32_t minHeadroom, uint32_t minTailroom) {
614 // Maybe we don't need to do anything.
615 if (headroom() >= minHeadroom && tailroom() >= minTailroom) {
618 // If the buffer is empty but we have enough total room (head + tail),
619 // move the data_ pointer around.
621 headroom() + tailroom() >= minHeadroom + minTailroom) {
622 data_ = writableBuffer() + minHeadroom;
625 // Bah, we have to do actual work.
626 reserveSlow(minHeadroom, minTailroom);
630 * Return true if this IOBuf is part of a chain of multiple IOBufs, or false
631 * if this is the only IOBuf in its chain.
633 bool isChained() const {
634 assert((next_ == this) == (prev_ == this));
635 return next_ != this;
639 * Get the number of IOBufs in this chain.
641 * Beware that this method has to walk the entire chain.
642 * Use isChained() if you just want to check if this IOBuf is part of a chain
645 uint32_t countChainElements() const;
648 * Get the length of all the data in this IOBuf chain.
650 * Beware that this method has to walk the entire chain.
652 uint64_t computeChainDataLength() const;
655 * Insert another IOBuf chain immediately before this IOBuf.
657 * For example, if there are two IOBuf chains (A, B, C) and (D, E, F),
658 * and B->prependChain(D) is called, the (D, E, F) chain will be subsumed
659 * and become part of the chain starting at A, which will now look like
662 * Note that since IOBuf chains are circular, head->prependChain(other) can
663 * be used to append the other chain at the very end of the chain pointed to
664 * by head. For example, if there are two IOBuf chains (A, B, C) and
665 * (D, E, F), and A->prependChain(D) is called, the chain starting at A will
666 * now consist of (A, B, C, D, E, F)
668 * The elements in the specified IOBuf chain will become part of this chain,
669 * and will be owned by the head of this chain. When this chain is
670 * destroyed, all elements in the supplied chain will also be destroyed.
672 * For this reason, appendChain() only accepts an rvalue-reference to a
673 * unique_ptr(), to make it clear that it is taking ownership of the supplied
674 * chain. If you have a raw pointer, you can pass in a new temporary
675 * unique_ptr around the raw pointer. If you have an existing,
676 * non-temporary unique_ptr, you must call std::move(ptr) to make it clear
677 * that you are destroying the original pointer.
679 void prependChain(std::unique_ptr<IOBuf>&& iobuf);
682 * Append another IOBuf chain immediately after this IOBuf.
684 * For example, if there are two IOBuf chains (A, B, C) and (D, E, F),
685 * and B->appendChain(D) is called, the (D, E, F) chain will be subsumed
686 * and become part of the chain starting at A, which will now look like
689 * The elements in the specified IOBuf chain will become part of this chain,
690 * and will be owned by the head of this chain. When this chain is
691 * destroyed, all elements in the supplied chain will also be destroyed.
693 * For this reason, appendChain() only accepts an rvalue-reference to a
694 * unique_ptr(), to make it clear that it is taking ownership of the supplied
695 * chain. If you have a raw pointer, you can pass in a new temporary
696 * unique_ptr around the raw pointer. If you have an existing,
697 * non-temporary unique_ptr, you must call std::move(ptr) to make it clear
698 * that you are destroying the original pointer.
700 void appendChain(std::unique_ptr<IOBuf>&& iobuf) {
701 // Just use prependChain() on the next element in our chain
702 next_->prependChain(std::move(iobuf));
706 * Remove this IOBuf from its current chain.
708 * Since ownership of all elements an IOBuf chain is normally maintained by
709 * the head of the chain, unlink() transfers ownership of this IOBuf from the
710 * chain and gives it to the caller. A new unique_ptr to the IOBuf is
711 * returned to the caller. The caller must store the returned unique_ptr (or
712 * call release() on it) to take ownership, otherwise the IOBuf will be
713 * immediately destroyed.
715 * Since unlink transfers ownership of the IOBuf to the caller, be careful
716 * not to call unlink() on the head of a chain if you already maintain
717 * ownership on the head of the chain via other means. The pop() method
718 * is a better choice for that situation.
720 std::unique_ptr<IOBuf> unlink() {
721 next_->prev_ = prev_;
722 prev_->next_ = next_;
725 return std::unique_ptr<IOBuf>(this);
729 * Remove this IOBuf from its current chain and return a unique_ptr to
730 * the IOBuf that formerly followed it in the chain.
732 std::unique_ptr<IOBuf> pop() {
734 next_->prev_ = prev_;
735 prev_->next_ = next_;
738 return std::unique_ptr<IOBuf>((next == this) ? NULL : next);
742 * Remove a subchain from this chain.
744 * Remove the subchain starting at head and ending at tail from this chain.
746 * Returns a unique_ptr pointing to head. (In other words, ownership of the
747 * head of the subchain is transferred to the caller.) If the caller ignores
748 * the return value and lets the unique_ptr be destroyed, the subchain will
749 * be immediately destroyed.
751 * The subchain referenced by the specified head and tail must be part of the
752 * same chain as the current IOBuf, but must not contain the current IOBuf.
753 * However, the specified head and tail may be equal to each other (i.e.,
754 * they may be a subchain of length 1).
756 std::unique_ptr<IOBuf> separateChain(IOBuf* head, IOBuf* tail) {
757 assert(head != this);
758 assert(tail != this);
760 head->prev_->next_ = tail->next_;
761 tail->next_->prev_ = head->prev_;
766 return std::unique_ptr<IOBuf>(head);
770 * Return true if at least one of the IOBufs in this chain are shared,
771 * or false if all of the IOBufs point to unique buffers.
773 * Use isSharedOne() to only check this IOBuf rather than the entire chain.
775 bool isShared() const {
776 const IOBuf* current = this;
778 if (current->isSharedOne()) {
781 current = current->next_;
782 if (current == this) {
789 * Return true if other IOBufs are also pointing to the buffer used by this
790 * IOBuf, and false otherwise.
792 * If this IOBuf points at a buffer owned by another (non-IOBuf) part of the
793 * code (i.e., if the IOBuf was created using wrapBuffer(), or was cloned
794 * from such an IOBuf), it is always considered shared.
796 * This only checks the current IOBuf, and not other IOBufs in the chain.
798 bool isSharedOne() const {
799 // If this is a user-owned buffer, it is always considered shared
800 if (flags_ & kFlagUserOwned) {
804 if (flags_ & kFlagExt) {
805 return ext_.sharedInfo->refcount.load(std::memory_order_acquire) > 1;
812 * Ensure that this IOBuf has a unique buffer that is not shared by other
815 * unshare() operates on an entire chain of IOBuf objects. If the chain is
816 * shared, it may also coalesce the chain when making it unique. If the
817 * chain is coalesced, subsequent IOBuf objects in the current chain will be
818 * automatically deleted.
820 * Note that buffers owned by other (non-IOBuf) users are automatically
823 * Throws std::bad_alloc on error. On error the IOBuf chain will be
826 * Currently unshare may also throw std::overflow_error if it tries to
827 * coalesce. (TODO: In the future it would be nice if unshare() were smart
828 * enough not to coalesce the entire buffer if the data is too large.
829 * However, in practice this seems unlikely to become an issue.)
840 * Ensure that this IOBuf has a unique buffer that is not shared by other
843 * unshareOne() operates on a single IOBuf object. This IOBuf will have a
844 * unique buffer after unshareOne() returns, but other IOBufs in the chain
845 * may still be shared after unshareOne() returns.
847 * Throws std::bad_alloc on error. On error the IOBuf will be unmodified.
856 * Coalesce this IOBuf chain into a single buffer.
858 * This method moves all of the data in this IOBuf chain into a single
859 * contiguous buffer, if it is not already in one buffer. After coalesce()
860 * returns, this IOBuf will be a chain of length one. Other IOBufs in the
861 * chain will be automatically deleted.
863 * After coalescing, the IOBuf will have at least as much headroom as the
864 * first IOBuf in the chain, and at least as much tailroom as the last IOBuf
867 * Throws std::bad_alloc on error. On error the IOBuf chain will be
868 * unmodified. Throws std::overflow_error if the length of the entire chain
869 * larger than can be described by a uint32_t capacity.
879 * Ensure that this chain has at least maxLength bytes available as a
880 * contiguous memory range.
882 * This method coalesces whole buffers in the chain into this buffer as
883 * necessary until this buffer's length() is at least maxLength.
885 * After coalescing, the IOBuf will have at least as much headroom as the
886 * first IOBuf in the chain, and at least as much tailroom as the last IOBuf
887 * that was coalesced.
889 * Throws std::bad_alloc on error. On error the IOBuf chain will be
890 * unmodified. Throws std::overflow_error if the length of the coalesced
891 * portion of the chain is larger than can be described by a uint32_t
892 * capacity. (Although maxLength is uint32_t, gather() doesn't split
893 * buffers, so coalescing whole buffers may result in a capacity that can't
894 * be described in uint32_t.
896 * Upon return, either enough of the chain was coalesced into a contiguous
897 * region, or the entire chain was coalesced. That is,
898 * length() >= maxLength || !isChained() is true.
900 void gather(uint32_t maxLength) {
901 if (!isChained() || length_ >= maxLength) {
904 coalesceSlow(maxLength);
908 * Return a new IOBuf chain sharing the same data as this chain.
910 * The new IOBuf chain will normally point to the same underlying data
911 * buffers as the original chain. (The one exception to this is if some of
912 * the IOBufs in this chain contain small internal data buffers which cannot
915 std::unique_ptr<IOBuf> clone() const;
918 * Return a new IOBuf with the same data as this IOBuf.
920 * The new IOBuf returned will not be part of a chain (even if this IOBuf is
921 * part of a larger chain).
923 std::unique_ptr<IOBuf> cloneOne() const;
925 // Overridden operator new and delete.
926 // These directly use malloc() and free() to allocate the space for IOBuf
927 // objects. This is needed since IOBuf::create() manually uses malloc when
928 // allocating IOBuf objects with an internal buffer.
929 void* operator new(size_t size);
930 void* operator new(size_t size, void* ptr);
931 void operator delete(void* ptr);
934 * Destructively convert this IOBuf to a fbstring efficiently.
935 * We rely on fbstring's AcquireMallocatedString constructor to
938 fbstring moveToFbString();
941 * Iteration support: a chain of IOBufs may be iterated through using
942 * STL-style iterators over const ByteRanges. Iterators are only invalidated
943 * if the IOBuf that they currently point to is removed.
945 Iterator cbegin() const;
946 Iterator cend() const;
947 Iterator begin() const;
948 Iterator end() const;
953 kFlagUserOwned = 0x2,
954 kFlagFreeSharedInfo = 0x4,
957 // Values for the ExternalBuf type field.
958 // We currently don't really use this for anything, other than to have it
959 // around for debugging purposes. We store it at the moment just because we
960 // have the 4 extra bytes in the ExternalBuf struct that would just be
961 // padding otherwise.
962 enum ExtBufTypeEnum {
964 kExtUserSupplied = 1,
970 SharedInfo(FreeFunction fn, void* arg);
972 // A pointer to a function to call to free the buffer when the refcount
973 // hits 0. If this is NULL, free() will be used instead.
976 std::atomic<uint32_t> refcount;
982 // SharedInfo may be NULL if kFlagUserOwned is set. It is non-NULL
983 // in all other cases.
984 SharedInfo* sharedInfo;
987 uint8_t buf[] __attribute__((aligned));
990 // The maximum size for an IOBuf object, including any internal data buffer
991 static const uint32_t kMaxIOBufSize = 256;
992 static const uint32_t kMaxInternalDataSize;
994 // Forbidden copy constructor and assignment opererator
995 IOBuf(IOBuf const &);
996 IOBuf& operator=(IOBuf const &);
999 * Create a new IOBuf with internal data.
1001 * end is a pointer to the end of the IOBuf's internal data buffer.
1003 explicit IOBuf(uint8_t* end);
1006 * Create a new IOBuf pointing to an external buffer.
1008 * The caller is responsible for holding a reference count for this new
1009 * IOBuf. The IOBuf constructor does not automatically increment the
1012 IOBuf(ExtBufTypeEnum type, uint32_t flags,
1013 uint8_t* buf, uint32_t capacity,
1014 uint8_t* data, uint32_t length,
1015 SharedInfo* sharedInfo);
1017 void unshareOneSlow();
1018 void unshareChained();
1019 void coalesceSlow(size_t maxLength=std::numeric_limits<size_t>::max());
1020 // newLength must be the entire length of the buffers between this and
1021 // end (no truncation)
1022 void coalesceAndReallocate(
1026 size_t newTailroom);
1027 void decrementRefcount();
1028 void reserveSlow(uint32_t minHeadroom, uint32_t minTailroom);
1030 static size_t goodExtBufferSize(uint32_t minCapacity);
1031 static void initExtBuffer(uint8_t* buf, size_t mallocSize,
1032 SharedInfo** infoReturn,
1033 uint32_t* capacityReturn);
1034 static void allocExtBuffer(uint32_t minCapacity,
1035 uint8_t** bufReturn,
1036 SharedInfo** infoReturn,
1037 uint32_t* capacityReturn);
1044 * Links to the next and the previous IOBuf in this chain.
1046 * The chain is circularly linked (the last element in the chain points back
1047 * at the head), and next_ and prev_ can never be NULL. If this IOBuf is the
1048 * only element in the chain, next_ and prev_ will both point to this.
1054 * A pointer to the start of the data referenced by this IOBuf, and the
1055 * length of the data.
1057 * This may refer to any subsection of the actual buffer capacity.
1068 struct DeleterBase {
1069 virtual ~DeleterBase() { }
1070 virtual void dispose(void* p) = 0;
1073 template <class UniquePtr>
1074 struct UniquePtrDeleter : public DeleterBase {
1075 typedef typename UniquePtr::pointer Pointer;
1076 typedef typename UniquePtr::deleter_type Deleter;
1078 explicit UniquePtrDeleter(Deleter deleter) : deleter_(std::move(deleter)){ }
1079 void dispose(void* p) {
1081 deleter_(static_cast<Pointer>(p));
1092 static void freeUniquePtrBuffer(void* ptr, void* userData) {
1093 static_cast<DeleterBase*>(userData)->dispose(ptr);
1097 template <class UniquePtr>
1098 typename std::enable_if<detail::IsUniquePtrToSL<UniquePtr>::value,
1099 std::unique_ptr<IOBuf>>::type
1100 IOBuf::takeOwnership(UniquePtr&& buf, size_t count) {
1101 size_t size = count * sizeof(typename UniquePtr::element_type);
1102 CHECK_LT(size, size_t(std::numeric_limits<uint32_t>::max()));
1103 auto deleter = new UniquePtrDeleter<UniquePtr>(buf.get_deleter());
1104 return takeOwnership(buf.release(),
1106 &IOBuf::freeUniquePtrBuffer,
1110 inline std::unique_ptr<IOBuf> IOBuf::copyBuffer(
1111 const void* data, uint32_t size, uint32_t headroom,
1112 uint32_t minTailroom) {
1113 uint32_t capacity = headroom + size + minTailroom;
1114 std::unique_ptr<IOBuf> buf = create(capacity);
1115 buf->advance(headroom);
1116 memcpy(buf->writableData(), data, size);
1121 inline std::unique_ptr<IOBuf> IOBuf::copyBuffer(const std::string& buf,
1123 uint32_t minTailroom) {
1124 return copyBuffer(buf.data(), buf.size(), headroom, minTailroom);
1127 inline std::unique_ptr<IOBuf> IOBuf::maybeCopyBuffer(const std::string& buf,
1129 uint32_t minTailroom) {
1133 return copyBuffer(buf.data(), buf.size(), headroom, minTailroom);
1136 class IOBuf::Iterator : public boost::iterator_facade<
1137 IOBuf::Iterator, // Derived
1138 const ByteRange, // Value
1139 boost::forward_traversal_tag // Category or traversal
1141 friend class boost::iterator_core_access;
1143 // Note that IOBufs are stored as a circular list without a guard node,
1144 // so pos == end is ambiguous (it may mean "begin" or "end"). To solve
1145 // the ambiguity (at the cost of one extra comparison in the "increment"
1146 // code path), we define end iterators as having pos_ == end_ == nullptr
1147 // and we only allow forward iteration.
1148 explicit Iterator(const IOBuf* pos, const IOBuf* end)
1151 // Sadly, we must return by const reference, not by value.
1159 val_ = ByteRange(pos_->data(), pos_->tail());
1162 void adjustForEnd() {
1164 pos_ = end_ = nullptr;
1171 const ByteRange& dereference() const {
1175 bool equal(const Iterator& other) const {
1176 // We must compare end_ in addition to pos_, because forward traversal
1177 // requires that if two iterators are equal (a == b) and dereferenceable,
1179 return pos_ == other.pos_ && end_ == other.end_;
1183 pos_ = pos_->next();
1192 inline IOBuf::Iterator IOBuf::begin() const { return cbegin(); }
1193 inline IOBuf::Iterator IOBuf::end() const { return cend(); }
1197 #endif // FOLLY_IO_IOBUF_H_