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 #define __STDC_LIMIT_MACROS
19 #include <folly/io/IOBuf.h>
21 #include <folly/Conv.h>
22 #include <folly/Likely.h>
23 #include <folly/Malloc.h>
24 #include <folly/Memory.h>
25 #include <folly/ScopeGuard.h>
26 #include <folly/SpookyHashV2.h>
27 #include <folly/io/Cursor.h>
34 using std::unique_ptr;
40 // This memory segment contains an IOBuf that is still in use
42 // This memory segment contains buffer data that is still in use
47 // When create() is called for buffers less than kDefaultCombinedBufSize,
48 // we allocate a single combined memory segment for the IOBuf and the data
49 // together. See the comments for createCombined()/createSeparate() for more
52 // (The size of 1k is largely just a guess here. We could could probably do
53 // benchmarks of real applications to see if adjusting this number makes a
54 // difference. Callers that know their exact use case can also explicitly
55 // call createCombined() or createSeparate().)
56 kDefaultCombinedBufSize = 1024
59 // Helper function for IOBuf::takeOwnership()
60 void takeOwnershipError(bool freeOnError, void* buf,
61 folly::IOBuf::FreeFunction freeFn,
71 freeFn(buf, userData);
73 // The user's free function is not allowed to throw.
74 // (We are already in the middle of throwing an exception, so
75 // we cannot let this exception go unhandled.)
80 } // unnamed namespace
84 struct IOBuf::HeapPrefix {
85 HeapPrefix(uint16_t flg)
89 // Reset magic to 0 on destruction. This is solely for debugging purposes
90 // to help catch bugs where someone tries to use HeapStorage after it has
96 std::atomic<uint16_t> flags;
99 struct IOBuf::HeapStorage {
101 // The IOBuf is last in the HeapStorage object.
102 // This way operator new will work even if allocating a subclass of IOBuf
103 // that requires more space.
107 struct IOBuf::HeapFullStorage {
108 // Make sure jemalloc allocates from the 64-byte class. Putting this here
109 // because HeapStorage is private so it can't be at namespace level.
110 static_assert(sizeof(HeapStorage) <= 64,
111 "IOBuf may not grow over 56 bytes!");
118 IOBuf::SharedInfo::SharedInfo()
121 // Use relaxed memory ordering here. Since we are creating a new SharedInfo,
122 // no other threads should be referring to it yet.
123 refcount.store(1, std::memory_order_relaxed);
126 IOBuf::SharedInfo::SharedInfo(FreeFunction fn, void* arg)
129 // Use relaxed memory ordering here. Since we are creating a new SharedInfo,
130 // no other threads should be referring to it yet.
131 refcount.store(1, std::memory_order_relaxed);
134 void* IOBuf::operator new(size_t size) {
135 size_t fullSize = offsetof(HeapStorage, buf) + size;
136 auto* storage = static_cast<HeapStorage*>(malloc(fullSize));
137 // operator new is not allowed to return NULL
138 if (UNLIKELY(storage == nullptr)) {
139 throw std::bad_alloc();
142 new (&storage->prefix) HeapPrefix(kIOBufInUse);
143 return &(storage->buf);
146 void* IOBuf::operator new(size_t size, void* 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 = (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, const void* buf, uint64_t size,
207 uint64_t headroom, uint64_t minTailroom)
208 : IOBuf(CREATE, headroom + size + minTailroom) {
210 memcpy(writableData(), buf, size);
214 IOBuf::IOBuf(CopyBufferOp op, ByteRange br,
215 uint64_t headroom, uint64_t minTailroom)
216 : IOBuf(op, br.data(), br.size(), headroom, minTailroom) {
219 unique_ptr<IOBuf> IOBuf::create(uint64_t capacity) {
220 // For smaller-sized buffers, allocate the IOBuf, SharedInfo, and the buffer
221 // all with a single allocation.
223 // We don't do this for larger buffers since it can be wasteful if the user
224 // needs to reallocate the buffer but keeps using the same IOBuf object.
225 // In this case we can't free the data space until the IOBuf is also
226 // destroyed. Callers can explicitly call createCombined() or
227 // createSeparate() if they know their use case better, and know if they are
228 // likely to reallocate the buffer later.
229 if (capacity <= kDefaultCombinedBufSize) {
230 return createCombined(capacity);
232 return createSeparate(capacity);
235 unique_ptr<IOBuf> IOBuf::createCombined(uint64_t capacity) {
236 // To save a memory allocation, allocate space for the IOBuf object, the
237 // SharedInfo struct, and the data itself all with a single call to malloc().
238 size_t requiredStorage = offsetof(HeapFullStorage, align) + capacity;
239 size_t mallocSize = goodMallocSize(requiredStorage);
240 auto* storage = static_cast<HeapFullStorage*>(malloc(mallocSize));
242 new (&storage->hs.prefix) HeapPrefix(kIOBufInUse | kDataInUse);
243 new (&storage->shared) SharedInfo(freeInternalBuf, storage);
245 uint8_t* bufAddr = reinterpret_cast<uint8_t*>(&storage->align);
246 uint8_t* storageEnd = reinterpret_cast<uint8_t*>(storage) + mallocSize;
247 size_t actualCapacity = storageEnd - bufAddr;
248 unique_ptr<IOBuf> ret(new (&storage->hs.buf) IOBuf(
249 InternalConstructor(), packFlagsAndSharedInfo(0, &storage->shared),
250 bufAddr, actualCapacity, bufAddr, 0));
254 unique_ptr<IOBuf> IOBuf::createSeparate(uint64_t capacity) {
255 return make_unique<IOBuf>(CREATE, capacity);
258 unique_ptr<IOBuf> IOBuf::createChain(
259 size_t totalCapacity, uint64_t maxBufCapacity) {
260 unique_ptr<IOBuf> out = create(
261 std::min(totalCapacity, size_t(maxBufCapacity)));
262 size_t allocatedCapacity = out->capacity();
264 while (allocatedCapacity < totalCapacity) {
265 unique_ptr<IOBuf> newBuf = create(
266 std::min(totalCapacity - allocatedCapacity, size_t(maxBufCapacity)));
267 allocatedCapacity += newBuf->capacity();
268 out->prependChain(std::move(newBuf));
274 IOBuf::IOBuf(TakeOwnershipOp, void* buf, uint64_t capacity, uint64_t length,
275 FreeFunction freeFn, void* userData,
279 data_(static_cast<uint8_t*>(buf)),
280 buf_(static_cast<uint8_t*>(buf)),
283 flagsAndSharedInfo_(packFlagsAndSharedInfo(kFlagFreeSharedInfo, nullptr)) {
285 setSharedInfo(new SharedInfo(freeFn, userData));
287 takeOwnershipError(freeOnError, buf, freeFn, userData);
292 unique_ptr<IOBuf> IOBuf::takeOwnership(void* buf, uint64_t capacity,
298 // TODO: We could allocate the IOBuf object and SharedInfo all in a single
299 // memory allocation. We could use the existing HeapStorage class, and
300 // define a new kSharedInfoInUse flag. We could change our code to call
301 // releaseStorage(kFlagFreeSharedInfo) when this kFlagFreeSharedInfo,
302 // rather than directly calling delete.
304 // Note that we always pass freeOnError as false to the constructor.
305 // If the constructor throws we'll handle it below. (We have to handle
306 // allocation failures from make_unique too.)
307 return make_unique<IOBuf>(TAKE_OWNERSHIP, buf, capacity, length,
308 freeFn, userData, false);
310 takeOwnershipError(freeOnError, buf, freeFn, userData);
315 IOBuf::IOBuf(WrapBufferOp, const void* buf, uint64_t capacity)
316 : IOBuf(InternalConstructor(), 0,
317 // We cast away the const-ness of the buffer here.
318 // This is okay since IOBuf users must use unshare() to create a copy
319 // of this buffer before writing to the buffer.
320 static_cast<uint8_t*>(const_cast<void*>(buf)), capacity,
321 static_cast<uint8_t*>(const_cast<void*>(buf)), capacity) {
324 IOBuf::IOBuf(WrapBufferOp op, ByteRange br)
325 : IOBuf(op, br.data(), br.size()) {
328 unique_ptr<IOBuf> IOBuf::wrapBuffer(const void* buf, uint64_t capacity) {
329 return make_unique<IOBuf>(WRAP_BUFFER, buf, capacity);
332 IOBuf::IOBuf() noexcept {
335 IOBuf::IOBuf(IOBuf&& other) noexcept {
336 *this = std::move(other);
339 IOBuf::IOBuf(const IOBuf& other) {
340 other.cloneInto(*this);
343 IOBuf::IOBuf(InternalConstructor,
344 uintptr_t flagsAndSharedInfo,
355 flagsAndSharedInfo_(flagsAndSharedInfo) {
357 assert(data + length <= buf + capacity);
361 // Destroying an IOBuf destroys the entire chain.
362 // Users of IOBuf should only explicitly delete the head of any chain.
363 // The other elements in the chain will be automatically destroyed.
364 while (next_ != this) {
365 // Since unlink() returns unique_ptr() and we don't store it,
366 // it will automatically delete the unlinked element.
367 (void)next_->unlink();
373 IOBuf& IOBuf::operator=(IOBuf&& other) noexcept {
374 if (this == &other) {
378 // If we are part of a chain, delete the rest of the chain.
379 while (next_ != this) {
380 // Since unlink() returns unique_ptr() and we don't store it,
381 // it will automatically delete the unlinked element.
382 (void)next_->unlink();
385 // Decrement our refcount on the current buffer
388 // Take ownership of the other buffer's data
391 length_ = other.length_;
392 capacity_ = other.capacity_;
393 flagsAndSharedInfo_ = other.flagsAndSharedInfo_;
394 // Reset other so it is a clean state to be destroyed.
395 other.data_ = nullptr;
396 other.buf_ = nullptr;
399 other.flagsAndSharedInfo_ = 0;
401 // If other was part of the chain, assume ownership of the rest of its chain.
402 // (It's only valid to perform move assignment on the head of a chain.)
403 if (other.next_ != &other) {
406 other.next_ = &other;
410 other.prev_ = &other;
413 // Sanity check to make sure that other is in a valid state to be destroyed.
414 DCHECK_EQ(other.prev_, &other);
415 DCHECK_EQ(other.next_, &other);
420 IOBuf& IOBuf::operator=(const IOBuf& other) {
421 if (this != &other) {
422 *this = IOBuf(other);
427 bool IOBuf::empty() const {
428 const IOBuf* current = this;
430 if (current->length() != 0) {
433 current = current->next_;
434 } while (current != this);
438 size_t IOBuf::countChainElements() const {
439 size_t numElements = 1;
440 for (IOBuf* current = next_; current != this; current = current->next_) {
446 uint64_t IOBuf::computeChainDataLength() const {
447 uint64_t fullLength = length_;
448 for (IOBuf* current = next_; current != this; current = current->next_) {
449 fullLength += current->length_;
454 void IOBuf::prependChain(unique_ptr<IOBuf>&& iobuf) {
455 // Take ownership of the specified IOBuf
456 IOBuf* other = iobuf.release();
458 // Remember the pointer to the tail of the other chain
459 IOBuf* otherTail = other->prev_;
461 // Hook up prev_->next_ to point at the start of the other chain,
462 // and other->prev_ to point at prev_
463 prev_->next_ = other;
464 other->prev_ = prev_;
466 // Hook up otherTail->next_ to point at us,
467 // and prev_ to point back at otherTail,
468 otherTail->next_ = this;
472 unique_ptr<IOBuf> IOBuf::clone() const {
473 unique_ptr<IOBuf> ret = make_unique<IOBuf>();
478 unique_ptr<IOBuf> IOBuf::cloneOne() const {
479 unique_ptr<IOBuf> ret = make_unique<IOBuf>();
484 void IOBuf::cloneInto(IOBuf& other) const {
488 for (IOBuf* current = next_; current != this; current = current->next_) {
489 tmp.prependChain(current->cloneOne());
492 other = std::move(tmp);
495 void IOBuf::cloneOneInto(IOBuf& other) const {
496 SharedInfo* info = sharedInfo();
498 setFlags(kFlagMaybeShared);
500 other = IOBuf(InternalConstructor(),
501 flagsAndSharedInfo_, buf_, capacity_,
504 info->refcount.fetch_add(1, std::memory_order_acq_rel);
508 void IOBuf::unshareOneSlow() {
509 // Allocate a new buffer for the data
511 SharedInfo* sharedInfo;
512 uint64_t actualCapacity;
513 allocExtBuffer(capacity_, &buf, &sharedInfo, &actualCapacity);
516 // Maintain the same amount of headroom. Since we maintained the same
517 // minimum capacity we also maintain at least the same amount of tailroom.
518 uint64_t headlen = headroom();
519 memcpy(buf + headlen, data_, length_);
521 // Release our reference on the old buffer
523 // Make sure kFlagMaybeShared and kFlagFreeSharedInfo are all cleared.
524 setFlagsAndSharedInfo(0, sharedInfo);
526 // Update the buffer pointers to point to the new buffer
527 data_ = buf + headlen;
531 void IOBuf::unshareChained() {
532 // unshareChained() should only be called if we are part of a chain of
533 // multiple IOBufs. The caller should have already verified this.
536 IOBuf* current = this;
538 if (current->isSharedOne()) {
539 // we have to unshare
543 current = current->next_;
544 if (current == this) {
545 // None of the IOBufs in the chain are shared,
546 // so return without doing anything
551 // We have to unshare. Let coalesceSlow() do the work.
555 void IOBuf::makeManagedChained() {
558 IOBuf* current = this;
560 current->makeManagedOne();
561 current = current->next_;
562 if (current == this) {
568 void IOBuf::coalesceSlow() {
569 // coalesceSlow() should only be called if we are part of a chain of multiple
570 // IOBufs. The caller should have already verified this.
573 // Compute the length of the entire chain
574 uint64_t newLength = 0;
577 newLength += end->length_;
579 } while (end != this);
581 coalesceAndReallocate(newLength, end);
582 // We should be only element left in the chain now
583 DCHECK(!isChained());
586 void IOBuf::coalesceSlow(size_t maxLength) {
587 // coalesceSlow() should only be called if we are part of a chain of multiple
588 // IOBufs. The caller should have already verified this.
590 DCHECK_LT(length_, maxLength);
592 // Compute the length of the entire chain
593 uint64_t newLength = 0;
596 newLength += end->length_;
598 if (newLength >= maxLength) {
602 throw std::overflow_error("attempted to coalesce more data than "
607 coalesceAndReallocate(newLength, end);
608 // We should have the requested length now
609 DCHECK_GE(length_, maxLength);
612 void IOBuf::coalesceAndReallocate(size_t newHeadroom,
615 size_t newTailroom) {
616 uint64_t newCapacity = newLength + newHeadroom + newTailroom;
618 // Allocate space for the coalesced buffer.
619 // We always convert to an external buffer, even if we happened to be an
620 // internal buffer before.
623 uint64_t actualCapacity;
624 allocExtBuffer(newCapacity, &newBuf, &newInfo, &actualCapacity);
626 // Copy the data into the new buffer
627 uint8_t* newData = newBuf + newHeadroom;
628 uint8_t* p = newData;
629 IOBuf* current = this;
630 size_t remaining = newLength;
632 assert(current->length_ <= remaining);
633 remaining -= current->length_;
634 memcpy(p, current->data_, current->length_);
635 p += current->length_;
636 current = current->next_;
637 } while (current != end);
638 assert(remaining == 0);
640 // Point at the new buffer
643 // Make sure kFlagMaybeShared and kFlagFreeSharedInfo are all cleared.
644 setFlagsAndSharedInfo(0, newInfo);
646 capacity_ = actualCapacity;
651 // Separate from the rest of our chain.
652 // Since we don't store the unique_ptr returned by separateChain(),
653 // this will immediately delete the returned subchain.
655 (void)separateChain(next_, current->prev_);
659 void IOBuf::decrementRefcount() {
660 // Externally owned buffers don't have a SharedInfo object and aren't managed
661 // by the reference count
662 SharedInfo* info = sharedInfo();
667 // Decrement the refcount
668 uint32_t newcnt = info->refcount.fetch_sub(
669 1, std::memory_order_acq_rel);
670 // Note that fetch_sub() returns the value before we decremented.
671 // If it is 1, we were the only remaining user; if it is greater there are
672 // still other users.
677 // We were the last user. Free the buffer
680 // Free the SharedInfo if it was allocated separately.
682 // This is only used by takeOwnership().
684 // To avoid this special case handling in decrementRefcount(), we could have
685 // takeOwnership() set a custom freeFn() that calls the user's free function
686 // then frees the SharedInfo object. (This would require that
687 // takeOwnership() store the user's free function with its allocated
688 // SharedInfo object.) However, handling this specially with a flag seems
689 // like it shouldn't be problematic.
690 if (flags() & kFlagFreeSharedInfo) {
695 void IOBuf::reserveSlow(uint64_t minHeadroom, uint64_t minTailroom) {
696 size_t newCapacity = (size_t)length_ + minHeadroom + minTailroom;
697 DCHECK_LT(newCapacity, UINT32_MAX);
699 // reserveSlow() is dangerous if anyone else is sharing the buffer, as we may
700 // reallocate and free the original buffer. It should only ever be called if
701 // we are the only user of the buffer.
702 DCHECK(!isSharedOne());
704 // We'll need to reallocate the buffer.
705 // There are a few options.
706 // - If we have enough total room, move the data around in the buffer
707 // and adjust the data_ pointer.
708 // - If we're using an internal buffer, we'll switch to an external
709 // buffer with enough headroom and tailroom.
710 // - If we have enough headroom (headroom() >= minHeadroom) but not too much
711 // (so we don't waste memory), we can try one of two things, depending on
712 // whether we use jemalloc or not:
713 // - If using jemalloc, we can try to expand in place, avoiding a memcpy()
714 // - If not using jemalloc and we don't have too much to copy,
715 // we'll use realloc() (note that realloc might have to copy
716 // headroom + data + tailroom, see smartRealloc in folly/Malloc.h)
717 // - Otherwise, bite the bullet and reallocate.
718 if (headroom() + tailroom() >= minHeadroom + minTailroom) {
719 uint8_t* newData = writableBuffer() + minHeadroom;
720 memmove(newData, data_, length_);
725 size_t newAllocatedCapacity = 0;
726 uint8_t* newBuffer = nullptr;
727 uint64_t newHeadroom = 0;
728 uint64_t oldHeadroom = headroom();
730 // If we have a buffer allocated with malloc and we just need more tailroom,
731 // try to use realloc()/xallocx() to grow the buffer in place.
732 SharedInfo* info = sharedInfo();
733 if (info && (info->freeFn == nullptr) && length_ != 0 &&
734 oldHeadroom >= minHeadroom) {
735 size_t headSlack = oldHeadroom - minHeadroom;
736 newAllocatedCapacity = goodExtBufferSize(newCapacity + headSlack);
737 if (usingJEMalloc()) {
738 // We assume that tailroom is more useful and more important than
739 // headroom (not least because realloc / xallocx allow us to grow the
740 // buffer at the tail, but not at the head) So, if we have more headroom
741 // than we need, we consider that "wasted". We arbitrarily define "too
742 // much" headroom to be 25% of the capacity.
743 if (headSlack * 4 <= newCapacity) {
744 size_t allocatedCapacity = capacity() + sizeof(SharedInfo);
746 if (allocatedCapacity >= jemallocMinInPlaceExpandable) {
747 if (xallocx(p, newAllocatedCapacity, 0, 0) == newAllocatedCapacity) {
748 newBuffer = static_cast<uint8_t*>(p);
749 newHeadroom = oldHeadroom;
751 // if xallocx failed, do nothing, fall back to malloc/memcpy/free
754 } else { // Not using jemalloc
755 size_t copySlack = capacity() - length_;
756 if (copySlack * 2 <= length_) {
757 void* p = realloc(buf_, newAllocatedCapacity);
758 if (UNLIKELY(p == nullptr)) {
759 throw std::bad_alloc();
761 newBuffer = static_cast<uint8_t*>(p);
762 newHeadroom = oldHeadroom;
767 // None of the previous reallocation strategies worked (or we're using
768 // an internal buffer). malloc/copy/free.
769 if (newBuffer == nullptr) {
770 newAllocatedCapacity = goodExtBufferSize(newCapacity);
771 void* p = malloc(newAllocatedCapacity);
772 if (UNLIKELY(p == nullptr)) {
773 throw std::bad_alloc();
775 newBuffer = static_cast<uint8_t*>(p);
776 memcpy(newBuffer + minHeadroom, data_, length_);
780 newHeadroom = minHeadroom;
784 initExtBuffer(newBuffer, newAllocatedCapacity, &info, &cap);
786 if (flags() & kFlagFreeSharedInfo) {
790 setFlagsAndSharedInfo(0, info);
793 data_ = newBuffer + newHeadroom;
794 // length_ is unchanged
797 void IOBuf::freeExtBuffer() {
798 SharedInfo* info = sharedInfo();
803 info->freeFn(buf_, info->userData);
805 // The user's free function should never throw. Otherwise we might
806 // throw from the IOBuf destructor. Other code paths like coalesce()
807 // also assume that decrementRefcount() cannot throw.
815 void IOBuf::allocExtBuffer(uint64_t minCapacity,
817 SharedInfo** infoReturn,
818 uint64_t* capacityReturn) {
819 size_t mallocSize = goodExtBufferSize(minCapacity);
820 uint8_t* buf = static_cast<uint8_t*>(malloc(mallocSize));
821 if (UNLIKELY(buf == nullptr)) {
822 throw std::bad_alloc();
824 initExtBuffer(buf, mallocSize, infoReturn, capacityReturn);
828 size_t IOBuf::goodExtBufferSize(uint64_t minCapacity) {
829 // Determine how much space we should allocate. We'll store the SharedInfo
830 // for the external buffer just after the buffer itself. (We store it just
831 // after the buffer rather than just before so that the code can still just
832 // use free(buf_) to free the buffer.)
833 size_t minSize = static_cast<size_t>(minCapacity) + sizeof(SharedInfo);
834 // Add room for padding so that the SharedInfo will be aligned on an 8-byte
836 minSize = (minSize + 7) & ~7;
838 // Use goodMallocSize() to bump up the capacity to a decent size to request
839 // from malloc, so we can use all of the space that malloc will probably give
841 return goodMallocSize(minSize);
844 void IOBuf::initExtBuffer(uint8_t* buf, size_t mallocSize,
845 SharedInfo** infoReturn,
846 uint64_t* capacityReturn) {
847 // Find the SharedInfo storage at the end of the buffer
848 // and construct the SharedInfo.
849 uint8_t* infoStart = (buf + mallocSize) - sizeof(SharedInfo);
850 SharedInfo* sharedInfo = new(infoStart) SharedInfo;
852 *capacityReturn = infoStart - buf;
853 *infoReturn = sharedInfo;
856 fbstring IOBuf::moveToFbString() {
857 // malloc-allocated buffers are just fine, everything else needs
858 // to be turned into one.
859 if (!sharedInfo() || // user owned, not ours to give up
860 sharedInfo()->freeFn || // not malloc()-ed
861 headroom() != 0 || // malloc()-ed block doesn't start at beginning
862 tailroom() == 0 || // no room for NUL terminator
863 isShared() || // shared
864 isChained()) { // chained
865 // We might as well get rid of all head and tailroom if we're going
866 // to reallocate; we need 1 byte for NUL terminator.
867 coalesceAndReallocate(0, computeChainDataLength(), this, 1);
870 // Ensure NUL terminated
872 fbstring str(reinterpret_cast<char*>(writableData()),
873 length(), capacity(),
874 AcquireMallocatedString());
876 if (flags() & kFlagFreeSharedInfo) {
880 // Reset to a state where we can be deleted cleanly
881 flagsAndSharedInfo_ = 0;
887 IOBuf::Iterator IOBuf::cbegin() const {
888 return Iterator(this, this);
891 IOBuf::Iterator IOBuf::cend() const {
892 return Iterator(nullptr, nullptr);
895 folly::fbvector<struct iovec> IOBuf::getIov() const {
896 folly::fbvector<struct iovec> iov;
897 iov.reserve(countChainElements());
902 void IOBuf::appendToIov(folly::fbvector<struct iovec>* iov) const {
903 IOBuf const* p = this;
905 // some code can get confused by empty iovs, so skip them
906 if (p->length() > 0) {
907 iov->push_back({(void*)p->data(), folly::to<size_t>(p->length())});
913 size_t IOBuf::fillIov(struct iovec* iov, size_t len) const {
914 IOBuf const* p = this;
917 // some code can get confused by empty iovs, so skip them
918 if (p->length() > 0) {
919 iov[i].iov_base = const_cast<uint8_t*>(p->data());
920 iov[i].iov_len = p->length();
931 size_t IOBufHash::operator()(const IOBuf& buf) const {
932 folly::hash::SpookyHashV2 hasher;
934 io::Cursor cursor(&buf);
936 auto p = cursor.peek();
940 hasher.Update(p.first, p.second);
941 cursor.skip(p.second);
945 hasher.Final(&h1, &h2);
949 bool IOBufEqual::operator()(const IOBuf& a, const IOBuf& b) const {
955 if (pa.second == 0 && pb.second == 0) {
957 } else if (pa.second == 0 || pb.second == 0) {
960 size_t n = std::min(pa.second, pb.second);
962 if (memcmp(pa.first, pb.first, n)) {