2 * Copyright 2017 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 __STDC_LIMIT_MACROS
18 #define __STDC_LIMIT_MACROS
21 #include <folly/io/IOBuf.h>
23 #include <folly/Conv.h>
24 #include <folly/Likely.h>
25 #include <folly/Malloc.h>
26 #include <folly/Memory.h>
27 #include <folly/ScopeGuard.h>
28 #include <folly/SpookyHashV2.h>
29 #include <folly/io/Cursor.h>
36 using std::unique_ptr;
42 // This memory segment contains an IOBuf that is still in use
44 // This memory segment contains buffer data that is still in use
49 // When create() is called for buffers less than kDefaultCombinedBufSize,
50 // we allocate a single combined memory segment for the IOBuf and the data
51 // together. See the comments for createCombined()/createSeparate() for more
54 // (The size of 1k is largely just a guess here. We could could probably do
55 // benchmarks of real applications to see if adjusting this number makes a
56 // difference. Callers that know their exact use case can also explicitly
57 // call createCombined() or createSeparate().)
58 kDefaultCombinedBufSize = 1024
61 // Helper function for IOBuf::takeOwnership()
62 void takeOwnershipError(bool freeOnError, void* buf,
63 folly::IOBuf::FreeFunction freeFn,
73 freeFn(buf, userData);
75 // The user's free function is not allowed to throw.
76 // (We are already in the middle of throwing an exception, so
77 // we cannot let this exception go unhandled.)
82 } // unnamed namespace
86 struct IOBuf::HeapPrefix {
87 HeapPrefix(uint16_t flg)
91 // Reset magic to 0 on destruction. This is solely for debugging purposes
92 // to help catch bugs where someone tries to use HeapStorage after it has
98 std::atomic<uint16_t> flags;
101 struct IOBuf::HeapStorage {
103 // The IOBuf is last in the HeapStorage object.
104 // This way operator new will work even if allocating a subclass of IOBuf
105 // that requires more space.
109 struct IOBuf::HeapFullStorage {
110 // Make sure jemalloc allocates from the 64-byte class. Putting this here
111 // because HeapStorage is private so it can't be at namespace level.
112 static_assert(sizeof(HeapStorage) <= 64,
113 "IOBuf may not grow over 56 bytes!");
117 std::max_align_t align;
120 IOBuf::SharedInfo::SharedInfo()
123 // Use relaxed memory ordering here. Since we are creating a new SharedInfo,
124 // no other threads should be referring to it yet.
125 refcount.store(1, std::memory_order_relaxed);
128 IOBuf::SharedInfo::SharedInfo(FreeFunction fn, void* arg)
131 // Use relaxed memory ordering here. Since we are creating a new SharedInfo,
132 // no other threads should be referring to it yet.
133 refcount.store(1, std::memory_order_relaxed);
136 void* IOBuf::operator new(size_t size) {
137 size_t fullSize = offsetof(HeapStorage, buf) + size;
138 auto* storage = static_cast<HeapStorage*>(malloc(fullSize));
139 // operator new is not allowed to return NULL
140 if (UNLIKELY(storage == nullptr)) {
141 throw std::bad_alloc();
144 new (&storage->prefix) HeapPrefix(kIOBufInUse);
145 return &(storage->buf);
148 void* IOBuf::operator new(size_t /* size */, void* ptr) { return ptr; }
150 void IOBuf::operator delete(void* ptr) {
151 auto* storageAddr = static_cast<uint8_t*>(ptr) - offsetof(HeapStorage, buf);
152 auto* storage = reinterpret_cast<HeapStorage*>(storageAddr);
153 releaseStorage(storage, kIOBufInUse);
156 void IOBuf::releaseStorage(HeapStorage* storage, uint16_t freeFlags) {
157 CHECK_EQ(storage->prefix.magic, static_cast<uint16_t>(kHeapMagic));
159 // Use relaxed memory order here. If we are unlucky and happen to get
160 // out-of-date data the compare_exchange_weak() call below will catch
161 // it and load new data with memory_order_acq_rel.
162 auto flags = storage->prefix.flags.load(std::memory_order_acquire);
163 DCHECK_EQ((flags & freeFlags), freeFlags);
166 uint16_t newFlags = uint16_t(flags & ~freeFlags);
168 // The storage space is now unused. Free it.
169 storage->prefix.HeapPrefix::~HeapPrefix();
174 // This storage segment still contains portions that are in use.
175 // Just clear the flags specified in freeFlags for now.
176 auto ret = storage->prefix.flags.compare_exchange_weak(
177 flags, newFlags, std::memory_order_acq_rel);
179 // We successfully updated the flags.
183 // We failed to update the flags. Some other thread probably updated them
184 // and cleared some of the other bits. Continue around the loop to see if
185 // we are the last user now, or if we need to try updating the flags again.
189 void IOBuf::freeInternalBuf(void* /* buf */, void* userData) {
190 auto* storage = static_cast<HeapStorage*>(userData);
191 releaseStorage(storage, kDataInUse);
194 IOBuf::IOBuf(CreateOp, uint64_t capacity)
199 flagsAndSharedInfo_(0) {
201 allocExtBuffer(capacity, &buf_, &info, &capacity_);
206 IOBuf::IOBuf(CopyBufferOp /* op */,
210 uint64_t minTailroom)
211 : IOBuf(CREATE, headroom + size + minTailroom) {
214 assert(buf != nullptr);
215 memcpy(writableData(), buf, size);
220 IOBuf::IOBuf(CopyBufferOp op, ByteRange br,
221 uint64_t headroom, uint64_t minTailroom)
222 : IOBuf(op, br.data(), br.size(), headroom, minTailroom) {
225 unique_ptr<IOBuf> IOBuf::create(uint64_t capacity) {
226 // For smaller-sized buffers, allocate the IOBuf, SharedInfo, and the buffer
227 // all with a single allocation.
229 // We don't do this for larger buffers since it can be wasteful if the user
230 // needs to reallocate the buffer but keeps using the same IOBuf object.
231 // In this case we can't free the data space until the IOBuf is also
232 // destroyed. Callers can explicitly call createCombined() or
233 // createSeparate() if they know their use case better, and know if they are
234 // likely to reallocate the buffer later.
235 if (capacity <= kDefaultCombinedBufSize) {
236 return createCombined(capacity);
238 return createSeparate(capacity);
241 unique_ptr<IOBuf> IOBuf::createCombined(uint64_t capacity) {
242 // To save a memory allocation, allocate space for the IOBuf object, the
243 // SharedInfo struct, and the data itself all with a single call to malloc().
244 size_t requiredStorage = offsetof(HeapFullStorage, align) + capacity;
245 size_t mallocSize = goodMallocSize(requiredStorage);
246 auto* storage = static_cast<HeapFullStorage*>(malloc(mallocSize));
248 new (&storage->hs.prefix) HeapPrefix(kIOBufInUse | kDataInUse);
249 new (&storage->shared) SharedInfo(freeInternalBuf, storage);
251 uint8_t* bufAddr = reinterpret_cast<uint8_t*>(&storage->align);
252 uint8_t* storageEnd = reinterpret_cast<uint8_t*>(storage) + mallocSize;
253 size_t actualCapacity = size_t(storageEnd - bufAddr);
254 unique_ptr<IOBuf> ret(new (&storage->hs.buf) IOBuf(
255 InternalConstructor(), packFlagsAndSharedInfo(0, &storage->shared),
256 bufAddr, actualCapacity, bufAddr, 0));
260 unique_ptr<IOBuf> IOBuf::createSeparate(uint64_t capacity) {
261 return make_unique<IOBuf>(CREATE, capacity);
264 unique_ptr<IOBuf> IOBuf::createChain(
265 size_t totalCapacity, uint64_t maxBufCapacity) {
266 unique_ptr<IOBuf> out = create(
267 std::min(totalCapacity, size_t(maxBufCapacity)));
268 size_t allocatedCapacity = out->capacity();
270 while (allocatedCapacity < totalCapacity) {
271 unique_ptr<IOBuf> newBuf = create(
272 std::min(totalCapacity - allocatedCapacity, size_t(maxBufCapacity)));
273 allocatedCapacity += newBuf->capacity();
274 out->prependChain(std::move(newBuf));
280 IOBuf::IOBuf(TakeOwnershipOp, void* buf, uint64_t capacity, uint64_t length,
281 FreeFunction freeFn, void* userData,
285 data_(static_cast<uint8_t*>(buf)),
286 buf_(static_cast<uint8_t*>(buf)),
289 flagsAndSharedInfo_(packFlagsAndSharedInfo(kFlagFreeSharedInfo, nullptr)) {
291 setSharedInfo(new SharedInfo(freeFn, userData));
293 takeOwnershipError(freeOnError, buf, freeFn, userData);
298 unique_ptr<IOBuf> IOBuf::takeOwnership(void* buf, uint64_t capacity,
304 // TODO: We could allocate the IOBuf object and SharedInfo all in a single
305 // memory allocation. We could use the existing HeapStorage class, and
306 // define a new kSharedInfoInUse flag. We could change our code to call
307 // releaseStorage(kFlagFreeSharedInfo) when this kFlagFreeSharedInfo,
308 // rather than directly calling delete.
310 // Note that we always pass freeOnError as false to the constructor.
311 // If the constructor throws we'll handle it below. (We have to handle
312 // allocation failures from make_unique too.)
313 return make_unique<IOBuf>(TAKE_OWNERSHIP, buf, capacity, length,
314 freeFn, userData, false);
316 takeOwnershipError(freeOnError, buf, freeFn, userData);
321 IOBuf::IOBuf(WrapBufferOp, const void* buf, uint64_t capacity)
322 : IOBuf(InternalConstructor(), 0,
323 // We cast away the const-ness of the buffer here.
324 // This is okay since IOBuf users must use unshare() to create a copy
325 // of this buffer before writing to the buffer.
326 static_cast<uint8_t*>(const_cast<void*>(buf)), capacity,
327 static_cast<uint8_t*>(const_cast<void*>(buf)), capacity) {
330 IOBuf::IOBuf(WrapBufferOp op, ByteRange br)
331 : IOBuf(op, br.data(), br.size()) {
334 unique_ptr<IOBuf> IOBuf::wrapBuffer(const void* buf, uint64_t capacity) {
335 return make_unique<IOBuf>(WRAP_BUFFER, buf, capacity);
338 IOBuf IOBuf::wrapBufferAsValue(const void* buf, uint64_t capacity) {
339 return IOBuf(WrapBufferOp::WRAP_BUFFER, buf, capacity);
342 IOBuf::IOBuf() noexcept {
345 IOBuf::IOBuf(IOBuf&& other) noexcept
346 : data_(other.data_),
348 length_(other.length_),
349 capacity_(other.capacity_),
350 flagsAndSharedInfo_(other.flagsAndSharedInfo_) {
351 // Reset other so it is a clean state to be destroyed.
352 other.data_ = nullptr;
353 other.buf_ = nullptr;
356 other.flagsAndSharedInfo_ = 0;
358 // If other was part of the chain, assume ownership of the rest of its chain.
359 // (It's only valid to perform move assignment on the head of a chain.)
360 if (other.next_ != &other) {
363 other.next_ = &other;
367 other.prev_ = &other;
370 // Sanity check to make sure that other is in a valid state to be destroyed.
371 DCHECK_EQ(other.prev_, &other);
372 DCHECK_EQ(other.next_, &other);
375 IOBuf::IOBuf(const IOBuf& other) {
376 *this = other.cloneAsValue();
379 IOBuf::IOBuf(InternalConstructor,
380 uintptr_t flagsAndSharedInfo,
391 flagsAndSharedInfo_(flagsAndSharedInfo) {
393 assert(data + length <= buf + capacity);
397 // Destroying an IOBuf destroys the entire chain.
398 // Users of IOBuf should only explicitly delete the head of any chain.
399 // The other elements in the chain will be automatically destroyed.
400 while (next_ != this) {
401 // Since unlink() returns unique_ptr() and we don't store it,
402 // it will automatically delete the unlinked element.
403 (void)next_->unlink();
409 IOBuf& IOBuf::operator=(IOBuf&& other) noexcept {
410 if (this == &other) {
414 // If we are part of a chain, delete the rest of the chain.
415 while (next_ != this) {
416 // Since unlink() returns unique_ptr() and we don't store it,
417 // it will automatically delete the unlinked element.
418 (void)next_->unlink();
421 // Decrement our refcount on the current buffer
424 // Take ownership of the other buffer's data
427 length_ = other.length_;
428 capacity_ = other.capacity_;
429 flagsAndSharedInfo_ = other.flagsAndSharedInfo_;
430 // Reset other so it is a clean state to be destroyed.
431 other.data_ = nullptr;
432 other.buf_ = nullptr;
435 other.flagsAndSharedInfo_ = 0;
437 // If other was part of the chain, assume ownership of the rest of its chain.
438 // (It's only valid to perform move assignment on the head of a chain.)
439 if (other.next_ != &other) {
442 other.next_ = &other;
446 other.prev_ = &other;
449 // Sanity check to make sure that other is in a valid state to be destroyed.
450 DCHECK_EQ(other.prev_, &other);
451 DCHECK_EQ(other.next_, &other);
456 IOBuf& IOBuf::operator=(const IOBuf& other) {
457 if (this != &other) {
458 *this = IOBuf(other);
463 bool IOBuf::empty() const {
464 const IOBuf* current = this;
466 if (current->length() != 0) {
469 current = current->next_;
470 } while (current != this);
474 size_t IOBuf::countChainElements() const {
475 size_t numElements = 1;
476 for (IOBuf* current = next_; current != this; current = current->next_) {
482 uint64_t IOBuf::computeChainDataLength() const {
483 uint64_t fullLength = length_;
484 for (IOBuf* current = next_; current != this; current = current->next_) {
485 fullLength += current->length_;
490 void IOBuf::prependChain(unique_ptr<IOBuf>&& iobuf) {
491 // Take ownership of the specified IOBuf
492 IOBuf* other = iobuf.release();
494 // Remember the pointer to the tail of the other chain
495 IOBuf* otherTail = other->prev_;
497 // Hook up prev_->next_ to point at the start of the other chain,
498 // and other->prev_ to point at prev_
499 prev_->next_ = other;
500 other->prev_ = prev_;
502 // Hook up otherTail->next_ to point at us,
503 // and prev_ to point back at otherTail,
504 otherTail->next_ = this;
508 unique_ptr<IOBuf> IOBuf::clone() const {
509 return make_unique<IOBuf>(cloneAsValue());
512 unique_ptr<IOBuf> IOBuf::cloneOne() const {
513 return make_unique<IOBuf>(cloneOneAsValue());
516 IOBuf IOBuf::cloneAsValue() const {
517 auto tmp = cloneOneAsValue();
519 for (IOBuf* current = next_; current != this; current = current->next_) {
520 tmp.prependChain(current->cloneOne());
526 IOBuf IOBuf::cloneOneAsValue() const {
527 if (SharedInfo* info = sharedInfo()) {
528 setFlags(kFlagMaybeShared);
529 info->refcount.fetch_add(1, std::memory_order_acq_rel);
532 InternalConstructor(),
540 void IOBuf::unshareOneSlow() {
541 // Allocate a new buffer for the data
543 SharedInfo* sharedInfo;
544 uint64_t actualCapacity;
545 allocExtBuffer(capacity_, &buf, &sharedInfo, &actualCapacity);
548 // Maintain the same amount of headroom. Since we maintained the same
549 // minimum capacity we also maintain at least the same amount of tailroom.
550 uint64_t headlen = headroom();
552 assert(data_ != nullptr);
553 memcpy(buf + headlen, data_, length_);
556 // Release our reference on the old buffer
558 // Make sure kFlagMaybeShared and kFlagFreeSharedInfo are all cleared.
559 setFlagsAndSharedInfo(0, sharedInfo);
561 // Update the buffer pointers to point to the new buffer
562 data_ = buf + headlen;
566 void IOBuf::unshareChained() {
567 // unshareChained() should only be called if we are part of a chain of
568 // multiple IOBufs. The caller should have already verified this.
571 IOBuf* current = this;
573 if (current->isSharedOne()) {
574 // we have to unshare
578 current = current->next_;
579 if (current == this) {
580 // None of the IOBufs in the chain are shared,
581 // so return without doing anything
586 // We have to unshare. Let coalesceSlow() do the work.
590 void IOBuf::markExternallyShared() {
591 IOBuf* current = this;
593 current->markExternallySharedOne();
594 current = current->next_;
595 } while (current != this);
598 void IOBuf::makeManagedChained() {
601 IOBuf* current = this;
603 current->makeManagedOne();
604 current = current->next_;
605 if (current == this) {
611 void IOBuf::coalesceSlow() {
612 // coalesceSlow() should only be called if we are part of a chain of multiple
613 // IOBufs. The caller should have already verified this.
616 // Compute the length of the entire chain
617 uint64_t newLength = 0;
620 newLength += end->length_;
622 } while (end != this);
624 coalesceAndReallocate(newLength, end);
625 // We should be only element left in the chain now
626 DCHECK(!isChained());
629 void IOBuf::coalesceSlow(size_t maxLength) {
630 // coalesceSlow() should only be called if we are part of a chain of multiple
631 // IOBufs. The caller should have already verified this.
633 DCHECK_LT(length_, maxLength);
635 // Compute the length of the entire chain
636 uint64_t newLength = 0;
639 newLength += end->length_;
641 if (newLength >= maxLength) {
645 throw std::overflow_error("attempted to coalesce more data than "
650 coalesceAndReallocate(newLength, end);
651 // We should have the requested length now
652 DCHECK_GE(length_, maxLength);
655 void IOBuf::coalesceAndReallocate(size_t newHeadroom,
658 size_t newTailroom) {
659 uint64_t newCapacity = newLength + newHeadroom + newTailroom;
661 // Allocate space for the coalesced buffer.
662 // We always convert to an external buffer, even if we happened to be an
663 // internal buffer before.
666 uint64_t actualCapacity;
667 allocExtBuffer(newCapacity, &newBuf, &newInfo, &actualCapacity);
669 // Copy the data into the new buffer
670 uint8_t* newData = newBuf + newHeadroom;
671 uint8_t* p = newData;
672 IOBuf* current = this;
673 size_t remaining = newLength;
675 if (current->length_ > 0) {
676 assert(current->length_ <= remaining);
677 assert(current->data_ != nullptr);
678 remaining -= current->length_;
679 memcpy(p, current->data_, current->length_);
680 p += current->length_;
682 current = current->next_;
683 } while (current != end);
684 assert(remaining == 0);
686 // Point at the new buffer
689 // Make sure kFlagMaybeShared and kFlagFreeSharedInfo are all cleared.
690 setFlagsAndSharedInfo(0, newInfo);
692 capacity_ = actualCapacity;
697 // Separate from the rest of our chain.
698 // Since we don't store the unique_ptr returned by separateChain(),
699 // this will immediately delete the returned subchain.
701 (void)separateChain(next_, current->prev_);
705 void IOBuf::decrementRefcount() {
706 // Externally owned buffers don't have a SharedInfo object and aren't managed
707 // by the reference count
708 SharedInfo* info = sharedInfo();
713 // Decrement the refcount
714 uint32_t newcnt = info->refcount.fetch_sub(
715 1, std::memory_order_acq_rel);
716 // Note that fetch_sub() returns the value before we decremented.
717 // If it is 1, we were the only remaining user; if it is greater there are
718 // still other users.
723 // We were the last user. Free the buffer
726 // Free the SharedInfo if it was allocated separately.
728 // This is only used by takeOwnership().
730 // To avoid this special case handling in decrementRefcount(), we could have
731 // takeOwnership() set a custom freeFn() that calls the user's free function
732 // then frees the SharedInfo object. (This would require that
733 // takeOwnership() store the user's free function with its allocated
734 // SharedInfo object.) However, handling this specially with a flag seems
735 // like it shouldn't be problematic.
736 if (flags() & kFlagFreeSharedInfo) {
741 void IOBuf::reserveSlow(uint64_t minHeadroom, uint64_t minTailroom) {
742 size_t newCapacity = (size_t)length_ + minHeadroom + minTailroom;
743 DCHECK_LT(newCapacity, UINT32_MAX);
745 // reserveSlow() is dangerous if anyone else is sharing the buffer, as we may
746 // reallocate and free the original buffer. It should only ever be called if
747 // we are the only user of the buffer.
748 DCHECK(!isSharedOne());
750 // We'll need to reallocate the buffer.
751 // There are a few options.
752 // - If we have enough total room, move the data around in the buffer
753 // and adjust the data_ pointer.
754 // - If we're using an internal buffer, we'll switch to an external
755 // buffer with enough headroom and tailroom.
756 // - If we have enough headroom (headroom() >= minHeadroom) but not too much
757 // (so we don't waste memory), we can try one of two things, depending on
758 // whether we use jemalloc or not:
759 // - If using jemalloc, we can try to expand in place, avoiding a memcpy()
760 // - If not using jemalloc and we don't have too much to copy,
761 // we'll use realloc() (note that realloc might have to copy
762 // headroom + data + tailroom, see smartRealloc in folly/Malloc.h)
763 // - Otherwise, bite the bullet and reallocate.
764 if (headroom() + tailroom() >= minHeadroom + minTailroom) {
765 uint8_t* newData = writableBuffer() + minHeadroom;
766 memmove(newData, data_, length_);
771 size_t newAllocatedCapacity = 0;
772 uint8_t* newBuffer = nullptr;
773 uint64_t newHeadroom = 0;
774 uint64_t oldHeadroom = headroom();
776 // If we have a buffer allocated with malloc and we just need more tailroom,
777 // try to use realloc()/xallocx() to grow the buffer in place.
778 SharedInfo* info = sharedInfo();
779 if (info && (info->freeFn == nullptr) && length_ != 0 &&
780 oldHeadroom >= minHeadroom) {
781 size_t headSlack = oldHeadroom - minHeadroom;
782 newAllocatedCapacity = goodExtBufferSize(newCapacity + headSlack);
783 if (usingJEMalloc()) {
784 // We assume that tailroom is more useful and more important than
785 // headroom (not least because realloc / xallocx allow us to grow the
786 // buffer at the tail, but not at the head) So, if we have more headroom
787 // than we need, we consider that "wasted". We arbitrarily define "too
788 // much" headroom to be 25% of the capacity.
789 if (headSlack * 4 <= newCapacity) {
790 size_t allocatedCapacity = capacity() + sizeof(SharedInfo);
792 if (allocatedCapacity >= jemallocMinInPlaceExpandable) {
793 if (xallocx(p, newAllocatedCapacity, 0, 0) == newAllocatedCapacity) {
794 newBuffer = static_cast<uint8_t*>(p);
795 newHeadroom = oldHeadroom;
797 // if xallocx failed, do nothing, fall back to malloc/memcpy/free
800 } else { // Not using jemalloc
801 size_t copySlack = capacity() - length_;
802 if (copySlack * 2 <= length_) {
803 void* p = realloc(buf_, newAllocatedCapacity);
804 if (UNLIKELY(p == nullptr)) {
805 throw std::bad_alloc();
807 newBuffer = static_cast<uint8_t*>(p);
808 newHeadroom = oldHeadroom;
813 // None of the previous reallocation strategies worked (or we're using
814 // an internal buffer). malloc/copy/free.
815 if (newBuffer == nullptr) {
816 newAllocatedCapacity = goodExtBufferSize(newCapacity);
817 void* p = malloc(newAllocatedCapacity);
818 if (UNLIKELY(p == nullptr)) {
819 throw std::bad_alloc();
821 newBuffer = static_cast<uint8_t*>(p);
823 assert(data_ != nullptr);
824 memcpy(newBuffer + minHeadroom, data_, length_);
829 newHeadroom = minHeadroom;
833 initExtBuffer(newBuffer, newAllocatedCapacity, &info, &cap);
835 if (flags() & kFlagFreeSharedInfo) {
839 setFlagsAndSharedInfo(0, info);
842 data_ = newBuffer + newHeadroom;
843 // length_ is unchanged
846 void IOBuf::freeExtBuffer() {
847 SharedInfo* info = sharedInfo();
852 info->freeFn(buf_, info->userData);
854 // The user's free function should never throw. Otherwise we might
855 // throw from the IOBuf destructor. Other code paths like coalesce()
856 // also assume that decrementRefcount() cannot throw.
864 void IOBuf::allocExtBuffer(uint64_t minCapacity,
866 SharedInfo** infoReturn,
867 uint64_t* capacityReturn) {
868 size_t mallocSize = goodExtBufferSize(minCapacity);
869 uint8_t* buf = static_cast<uint8_t*>(malloc(mallocSize));
870 if (UNLIKELY(buf == nullptr)) {
871 throw std::bad_alloc();
873 initExtBuffer(buf, mallocSize, infoReturn, capacityReturn);
877 size_t IOBuf::goodExtBufferSize(uint64_t minCapacity) {
878 // Determine how much space we should allocate. We'll store the SharedInfo
879 // for the external buffer just after the buffer itself. (We store it just
880 // after the buffer rather than just before so that the code can still just
881 // use free(buf_) to free the buffer.)
882 size_t minSize = static_cast<size_t>(minCapacity) + sizeof(SharedInfo);
883 // Add room for padding so that the SharedInfo will be aligned on an 8-byte
885 minSize = (minSize + 7) & ~7;
887 // Use goodMallocSize() to bump up the capacity to a decent size to request
888 // from malloc, so we can use all of the space that malloc will probably give
890 return goodMallocSize(minSize);
893 void IOBuf::initExtBuffer(uint8_t* buf, size_t mallocSize,
894 SharedInfo** infoReturn,
895 uint64_t* capacityReturn) {
896 // Find the SharedInfo storage at the end of the buffer
897 // and construct the SharedInfo.
898 uint8_t* infoStart = (buf + mallocSize) - sizeof(SharedInfo);
899 SharedInfo* sharedInfo = new(infoStart) SharedInfo;
901 *capacityReturn = uint64_t(infoStart - buf);
902 *infoReturn = sharedInfo;
905 fbstring IOBuf::moveToFbString() {
906 // malloc-allocated buffers are just fine, everything else needs
907 // to be turned into one.
908 if (!sharedInfo() || // user owned, not ours to give up
909 sharedInfo()->freeFn || // not malloc()-ed
910 headroom() != 0 || // malloc()-ed block doesn't start at beginning
911 tailroom() == 0 || // no room for NUL terminator
912 isShared() || // shared
913 isChained()) { // chained
914 // We might as well get rid of all head and tailroom if we're going
915 // to reallocate; we need 1 byte for NUL terminator.
916 coalesceAndReallocate(0, computeChainDataLength(), this, 1);
919 // Ensure NUL terminated
921 fbstring str(reinterpret_cast<char*>(writableData()),
922 length(), capacity(),
923 AcquireMallocatedString());
925 if (flags() & kFlagFreeSharedInfo) {
929 // Reset to a state where we can be deleted cleanly
930 flagsAndSharedInfo_ = 0;
936 IOBuf::Iterator IOBuf::cbegin() const {
937 return Iterator(this, this);
940 IOBuf::Iterator IOBuf::cend() const {
941 return Iterator(nullptr, nullptr);
944 folly::fbvector<struct iovec> IOBuf::getIov() const {
945 folly::fbvector<struct iovec> iov;
946 iov.reserve(countChainElements());
951 void IOBuf::appendToIov(folly::fbvector<struct iovec>* iov) const {
952 IOBuf const* p = this;
954 // some code can get confused by empty iovs, so skip them
955 if (p->length() > 0) {
956 iov->push_back({(void*)p->data(), folly::to<size_t>(p->length())});
962 size_t IOBuf::fillIov(struct iovec* iov, size_t len) const {
963 IOBuf const* p = this;
966 // some code can get confused by empty iovs, so skip them
967 if (p->length() > 0) {
968 iov[i].iov_base = const_cast<uint8_t*>(p->data());
969 iov[i].iov_len = p->length();
980 size_t IOBufHash::operator()(const IOBuf& buf) const {
981 folly::hash::SpookyHashV2 hasher;
983 io::Cursor cursor(&buf);
985 auto b = cursor.peekBytes();
989 hasher.Update(b.data(), b.size());
990 cursor.skip(b.size());
994 hasher.Final(&h1, &h2);
998 bool IOBufEqual::operator()(const IOBuf& a, const IOBuf& b) const {
1002 auto ba = ca.peekBytes();
1003 auto bb = cb.peekBytes();
1004 if (ba.empty() && bb.empty()) {
1006 } else if (ba.empty() || bb.empty()) {
1009 size_t n = std::min(ba.size(), bb.size());
1011 if (memcmp(ba.data(), bb.data(), n)) {