2 * Copyright 2016 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.
23 #include <type_traits>
26 #include <folly/Bits.h>
27 #include <folly/io/IOBuf.h>
28 #include <folly/io/IOBufQueue.h>
29 #include <folly/Likely.h>
30 #include <folly/Memory.h>
31 #include <folly/Portability.h>
32 #include <folly/Range.h>
35 * Cursor class for fast iteration over IOBuf chains.
37 * Cursor - Read-only access
39 * RWPrivateCursor - Read-write access, assumes private access to IOBuf chain
40 * RWUnshareCursor - Read-write access, calls unshare on write (COW)
41 * Appender - Write access, assumes private access to IOBuf chian
43 * Note that RW cursors write in the preallocated part of buffers (that is,
44 * between the buffer's data() and tail()), while Appenders append to the end
45 * of the buffer (between the buffer's tail() and bufferEnd()). Appenders
46 * automatically adjust the buffer pointers, so you may only use one
47 * Appender with a buffer chain; for this reason, Appenders assume private
48 * access to the buffer (you need to call unshare() yourself if necessary).
50 namespace folly { namespace io {
54 template <class Derived, class BufType>
56 // Make all the templated classes friends for copy constructor.
57 template <class D, typename B> friend class CursorBase;
59 explicit CursorBase(BufType* buf) : crtBuf_(buf), buffer_(buf) { }
64 * This also allows constructing a CursorBase from other derived types.
65 * For instance, this allows constructing a Cursor from an RWPrivateCursor.
67 template <class OtherDerived, class OtherBuf>
68 explicit CursorBase(const CursorBase<OtherDerived, OtherBuf>& cursor)
69 : crtBuf_(cursor.crtBuf_),
70 offset_(cursor.offset_),
71 buffer_(cursor.buffer_) { }
74 * Reset cursor to point to a new buffer.
76 void reset(BufType* buf) {
82 const uint8_t* data() const {
83 return crtBuf_->data() + offset_;
87 * Return the remaining space available in the current IOBuf.
89 * May return 0 if the cursor is at the end of an IOBuf. Use peek() instead
90 * if you want to avoid this. peek() will advance to the next non-empty
91 * IOBuf (up to the end of the chain) if the cursor is currently pointing at
92 * the end of a buffer.
94 size_t length() const {
95 return crtBuf_->length() - offset_;
99 * Return the space available until the end of the entire IOBuf chain.
101 size_t totalLength() const {
102 if (crtBuf_ == buffer_) {
103 return crtBuf_->computeChainDataLength() - offset_;
105 CursorBase end(buffer_->prev());
106 end.offset_ = end.buffer_->length();
111 * Return true if the cursor could advance the specified number of bytes
112 * from its current position.
113 * This is useful for applications that want to do checked reads instead of
114 * catching exceptions and is more efficient than using totalLength as it
115 * walks the minimal set of buffers in the chain to determine the result.
117 bool canAdvance(size_t amount) const {
118 const IOBuf* nextBuf = crtBuf_;
119 size_t available = length();
121 if (available >= amount) {
125 nextBuf = nextBuf->next();
126 available = nextBuf->length();
127 } while (nextBuf != buffer_);
132 * Return true if the cursor is at the end of the entire IOBuf chain.
134 bool isAtEnd() const {
135 // Check for the simple cases first.
136 if (offset_ != crtBuf_->length()) {
139 if (crtBuf_ == buffer_->prev()) {
142 // We are at the end of a buffer, but it isn't the last buffer.
143 // We might still be at the end if the remaining buffers in the chain are
145 const IOBuf* buf = crtBuf_->next();;
146 while (buf != buffer_) {
147 if (buf->length() > 0) {
155 Derived& operator+=(size_t offset) {
156 Derived* p = static_cast<Derived*>(this);
160 Derived operator+(size_t offset) const {
161 Derived other(*this);
167 * Compare cursors for equality/inequality.
169 * Two cursors are equal if they are pointing to the same location in the
172 bool operator==(const Derived& other) const {
173 return (offset_ == other.offset_) && (crtBuf_ == other.crtBuf_);
175 bool operator!=(const Derived& other) const {
176 return !operator==(other);
180 typename std::enable_if<std::is_arithmetic<T>::value, T>::type read() {
182 if (LIKELY(length() >= sizeof(T))) {
183 val = loadUnaligned<T>(data());
184 offset_ += sizeof(T);
185 advanceBufferIfEmpty();
187 pullSlow(&val, sizeof(T));
194 return Endian::big(read<T>());
199 return Endian::little(read<T>());
203 * Read a fixed-length string.
205 * The std::string-based APIs should probably be avoided unless you
206 * ultimately want the data to live in an std::string. You're better off
207 * using the pull() APIs to copy into a raw buffer otherwise.
209 std::string readFixedString(size_t len) {
212 if (LIKELY(length() >= len)) {
213 str.append(reinterpret_cast<const char*>(data()), len);
215 advanceBufferIfEmpty();
217 readFixedStringSlow(&str, len);
223 * Read a string consisting of bytes until the given terminator character is
224 * seen. Raises an std::length_error if maxLength bytes have been processed
225 * before the terminator is seen.
227 * See comments in readFixedString() about when it's appropriate to use this
230 std::string readTerminatedString(
231 char termChar = '\0',
232 size_t maxLength = std::numeric_limits<size_t>::max()) {
236 const uint8_t* buf = data();
237 size_t buflen = length();
240 while (i < buflen && buf[i] != termChar) {
243 // Do this check after incrementing 'i', as even though we start at the
244 // 0 byte, it still represents a single character
245 if (str.length() + i >= maxLength) {
246 throw std::length_error("string overflow");
250 str.append(reinterpret_cast<const char*>(buf), i);
258 throw std::out_of_range("terminator not found");
261 size_t skipAtMost(size_t len) {
262 if (LIKELY(length() >= len)) {
264 advanceBufferIfEmpty();
267 return skipAtMostSlow(len);
270 void skip(size_t len) {
271 if (LIKELY(length() >= len)) {
273 advanceBufferIfEmpty();
279 size_t pullAtMost(void* buf, size_t len) {
280 // Fast path: it all fits in one buffer.
281 if (LIKELY(length() >= len)) {
282 memcpy(buf, data(), len);
284 advanceBufferIfEmpty();
287 return pullAtMostSlow(buf, len);
290 void pull(void* buf, size_t len) {
291 if (LIKELY(length() >= len)) {
292 memcpy(buf, data(), len);
294 advanceBufferIfEmpty();
301 * Return the available data in the current buffer.
302 * If you want to gather more data from the chain into a contiguous region
303 * (for hopefully zero-copy access), use gather() before peek().
305 std::pair<const uint8_t*, size_t> peek() {
306 // Ensure that we're pointing to valid data
307 size_t available = length();
308 while (UNLIKELY(available == 0 && tryAdvanceBuffer())) {
309 available = length();
311 return std::make_pair(data(), available);
314 void clone(std::unique_ptr<folly::IOBuf>& buf, size_t len) {
315 if (UNLIKELY(cloneAtMost(buf, len) != len)) {
316 throw std::out_of_range("underflow");
320 void clone(folly::IOBuf& buf, size_t len) {
321 if (UNLIKELY(cloneAtMost(buf, len) != len)) {
322 throw std::out_of_range("underflow");
326 size_t cloneAtMost(folly::IOBuf& buf, size_t len) {
327 buf = folly::IOBuf();
329 std::unique_ptr<folly::IOBuf> tmp;
331 for (int loopCount = 0; true; ++loopCount) {
332 // Fast path: it all fits in one buffer.
333 size_t available = length();
334 if (LIKELY(available >= len)) {
335 if (loopCount == 0) {
336 crtBuf_->cloneOneInto(buf);
337 buf.trimStart(offset_);
338 buf.trimEnd(buf.length() - len);
340 tmp = crtBuf_->cloneOne();
341 tmp->trimStart(offset_);
342 tmp->trimEnd(tmp->length() - len);
343 buf.prependChain(std::move(tmp));
347 advanceBufferIfEmpty();
351 if (loopCount == 0) {
352 crtBuf_->cloneOneInto(buf);
353 buf.trimStart(offset_);
355 tmp = crtBuf_->cloneOne();
356 tmp->trimStart(offset_);
357 buf.prependChain(std::move(tmp));
361 if (UNLIKELY(!tryAdvanceBuffer())) {
368 size_t cloneAtMost(std::unique_ptr<folly::IOBuf>& buf, size_t len) {
370 buf = make_unique<folly::IOBuf>();
372 return cloneAtMost(*buf, len);
376 * Return the distance between two cursors.
378 size_t operator-(const CursorBase& other) const {
379 BufType *otherBuf = other.crtBuf_;
382 if (otherBuf != crtBuf_) {
383 len += otherBuf->length() - other.offset_;
385 for (otherBuf = otherBuf->next();
386 otherBuf != crtBuf_ && otherBuf != other.buffer_;
387 otherBuf = otherBuf->next()) {
388 len += otherBuf->length();
391 if (otherBuf == other.buffer_) {
392 throw std::out_of_range("wrap-around");
397 if (offset_ < other.offset_) {
398 throw std::out_of_range("underflow");
401 len += offset_ - other.offset_;
408 * Return the distance from the given IOBuf to the this cursor.
410 size_t operator-(const BufType* buf) const {
413 BufType *curBuf = buf;
414 while (curBuf != crtBuf_) {
415 len += curBuf->length();
416 curBuf = curBuf->next();
417 if (curBuf == buf || curBuf == buffer_) {
418 throw std::out_of_range("wrap-around");
433 bool tryAdvanceBuffer() {
434 BufType* nextBuf = crtBuf_->next();
435 if (UNLIKELY(nextBuf == buffer_)) {
436 offset_ = crtBuf_->length();
442 static_cast<Derived*>(this)->advanceDone();
446 void advanceBufferIfEmpty() {
456 void readFixedStringSlow(std::string* str, size_t len) {
457 for (size_t available; (available = length()) < len; ) {
458 str->append(reinterpret_cast<const char*>(data()), available);
459 if (UNLIKELY(!tryAdvanceBuffer())) {
460 throw std::out_of_range("string underflow");
464 str->append(reinterpret_cast<const char*>(data()), len);
466 advanceBufferIfEmpty();
469 size_t pullAtMostSlow(void* buf, size_t len) {
470 uint8_t* p = reinterpret_cast<uint8_t*>(buf);
472 for (size_t available; (available = length()) < len; ) {
473 memcpy(p, data(), available);
475 if (UNLIKELY(!tryAdvanceBuffer())) {
481 memcpy(p, data(), len);
483 advanceBufferIfEmpty();
487 void pullSlow(void* buf, size_t len) {
488 if (UNLIKELY(pullAtMostSlow(buf, len) != len)) {
489 throw std::out_of_range("underflow");
493 size_t skipAtMostSlow(size_t len) {
495 for (size_t available; (available = length()) < len; ) {
496 skipped += available;
497 if (UNLIKELY(!tryAdvanceBuffer())) {
503 advanceBufferIfEmpty();
504 return skipped + len;
507 void skipSlow(size_t len) {
508 if (UNLIKELY(skipAtMostSlow(len) != len)) {
509 throw std::out_of_range("underflow");
519 } // namespace detail
521 class Cursor : public detail::CursorBase<Cursor, const IOBuf> {
523 explicit Cursor(const IOBuf* buf)
524 : detail::CursorBase<Cursor, const IOBuf>(buf) {}
526 template <class OtherDerived, class OtherBuf>
527 explicit Cursor(const detail::CursorBase<OtherDerived, OtherBuf>& cursor)
528 : detail::CursorBase<Cursor, const IOBuf>(cursor) {}
533 template <class Derived>
537 typename std::enable_if<std::is_arithmetic<T>::value>::type
539 const uint8_t* u8 = reinterpret_cast<const uint8_t*>(&value);
540 Derived* d = static_cast<Derived*>(this);
541 d->push(u8, sizeof(T));
545 void writeBE(T value) {
546 Derived* d = static_cast<Derived*>(this);
547 d->write(Endian::big(value));
551 void writeLE(T value) {
552 Derived* d = static_cast<Derived*>(this);
553 d->write(Endian::little(value));
556 void push(const uint8_t* buf, size_t len) {
557 Derived* d = static_cast<Derived*>(this);
558 if (d->pushAtMost(buf, len) != len) {
559 throw std::out_of_range("overflow");
563 void push(ByteRange buf) {
564 if (this->pushAtMost(buf) != buf.size()) {
565 throw std::out_of_range("overflow");
569 size_t pushAtMost(ByteRange buf) {
570 Derived* d = static_cast<Derived*>(this);
571 return d->pushAtMost(buf.data(), buf.size());
575 * push len bytes of data from input cursor, data could be in an IOBuf chain.
576 * If input cursor contains less than len bytes, or this cursor has less than
577 * len bytes writable space, an out_of_range exception will be thrown.
579 void push(Cursor cursor, size_t len) {
580 if (this->pushAtMost(cursor, len) != len) {
581 throw std::out_of_range("overflow");
585 size_t pushAtMost(Cursor cursor, size_t len) {
588 auto currentBuffer = cursor.peek();
589 const uint8_t* crtData = currentBuffer.first;
590 size_t available = currentBuffer.second;
591 if (available == 0) {
592 // end of buffer chain
595 // all data is in current buffer
596 if (available >= len) {
597 this->push(crtData, len);
599 return written + len;
602 // write the whole current IOBuf
603 this->push(crtData, available);
604 cursor.skip(available);
605 written += available;
611 } // namespace detail
613 enum class CursorAccess {
618 template <CursorAccess access>
620 : public detail::CursorBase<RWCursor<access>, IOBuf>,
621 public detail::Writable<RWCursor<access>> {
622 friend class detail::CursorBase<RWCursor<access>, IOBuf>;
624 explicit RWCursor(IOBuf* buf)
625 : detail::CursorBase<RWCursor<access>, IOBuf>(buf),
626 maybeShared_(true) {}
628 template <class OtherDerived, class OtherBuf>
629 explicit RWCursor(const detail::CursorBase<OtherDerived, OtherBuf>& cursor)
630 : detail::CursorBase<RWCursor<access>, IOBuf>(cursor),
631 maybeShared_(true) {}
633 * Gather at least n bytes contiguously into the current buffer,
634 * by coalescing subsequent buffers from the chain as necessary.
636 void gather(size_t n) {
637 // Forbid attempts to gather beyond the end of this IOBuf chain.
638 // Otherwise we could try to coalesce the head of the chain and end up
639 // accidentally freeing it, invalidating the pointer owned by external
642 // If crtBuf_ == head() then IOBuf::gather() will perform all necessary
643 // checking. We only have to perform an explicit check here when calling
644 // gather() on a non-head element.
645 if (this->crtBuf_ != this->head() && this->totalLength() < n) {
646 throw std::overflow_error("cannot gather() past the end of the chain");
648 this->crtBuf_->gather(this->offset_ + n);
650 void gatherAtMost(size_t n) {
651 size_t size = std::min(n, this->totalLength());
652 return this->crtBuf_->gather(this->offset_ + size);
655 using detail::Writable<RWCursor<access>>::pushAtMost;
656 size_t pushAtMost(const uint8_t* buf, size_t len) {
659 // Fast path: the current buffer is big enough.
660 size_t available = this->length();
661 if (LIKELY(available >= len)) {
662 if (access == CursorAccess::UNSHARE) {
665 memcpy(writableData(), buf, len);
666 this->offset_ += len;
670 if (access == CursorAccess::UNSHARE) {
673 memcpy(writableData(), buf, available);
675 if (UNLIKELY(!this->tryAdvanceBuffer())) {
683 void insert(std::unique_ptr<folly::IOBuf> buf) {
684 folly::IOBuf* nextBuf;
685 if (this->offset_ == 0) {
687 nextBuf = this->crtBuf_;
688 this->crtBuf_->prependChain(std::move(buf));
690 std::unique_ptr<folly::IOBuf> remaining;
691 if (this->crtBuf_->length() - this->offset_ > 0) {
692 // Need to split current IOBuf in two.
693 remaining = this->crtBuf_->cloneOne();
694 remaining->trimStart(this->offset_);
695 nextBuf = remaining.get();
696 buf->prependChain(std::move(remaining));
699 nextBuf = this->crtBuf_->next();
701 this->crtBuf_->trimEnd(this->length());
702 this->crtBuf_->appendChain(std::move(buf));
704 // Jump past the new links
706 this->crtBuf_ = nextBuf;
709 uint8_t* writableData() {
710 return this->crtBuf_->writableData() + this->offset_;
714 void maybeUnshare() {
715 if (UNLIKELY(maybeShared_)) {
716 this->crtBuf_->unshareOne();
717 maybeShared_ = false;
728 typedef RWCursor<CursorAccess::PRIVATE> RWPrivateCursor;
729 typedef RWCursor<CursorAccess::UNSHARE> RWUnshareCursor;
732 * Append to the end of a buffer chain, growing the chain (by allocating new
733 * buffers) in increments of at least growth bytes every time. Won't grow
734 * (and push() and ensure() will throw) if growth == 0.
736 * TODO(tudorb): add a flavor of Appender that reallocates one IOBuf instead
739 class Appender : public detail::Writable<Appender> {
741 Appender(IOBuf* buf, uint64_t growth)
743 crtBuf_(buf->prev()),
747 uint8_t* writableData() {
748 return crtBuf_->writableTail();
751 size_t length() const {
752 return crtBuf_->tailroom();
756 * Mark n bytes (must be <= length()) as appended, as per the
757 * IOBuf::append() method.
759 void append(size_t n) {
764 * Ensure at least n contiguous bytes available to write.
765 * Postcondition: length() >= n.
767 void ensure(uint64_t n) {
768 if (LIKELY(length() >= n)) {
772 // Waste the rest of the current buffer and allocate a new one.
773 // Don't make it too small, either.
775 throw std::out_of_range("can't grow buffer chain");
778 n = std::max(n, growth_);
779 buffer_->prependChain(IOBuf::create(n));
780 crtBuf_ = buffer_->prev();
783 using detail::Writable<Appender>::pushAtMost;
784 size_t pushAtMost(const uint8_t* buf, size_t len) {
787 // Fast path: it all fits in one buffer.
788 size_t available = length();
789 if (LIKELY(available >= len)) {
790 memcpy(writableData(), buf, len);
795 memcpy(writableData(), buf, available);
798 if (UNLIKELY(!tryGrowChain())) {
807 * Append to the end of this buffer, using a printf() style
810 * Note that folly/Format.h provides nicer and more type-safe mechanisms
811 * for formatting strings, which should generally be preferred over
812 * printf-style formatting. Appender objects can be used directly as an
813 * output argument for Formatter objects. For example:
815 * Appender app(&iobuf);
816 * format("{} {}", "hello", "world")(app);
818 * However, printf-style strings are still needed when dealing with existing
819 * third-party code in some cases.
821 * This will always add a nul-terminating character after the end
822 * of the output. However, the buffer data length will only be updated to
823 * include the data itself. The nul terminator will be the first byte in the
826 * This method may throw exceptions on error.
828 void printf(FOLLY_PRINTF_FORMAT const char* fmt, ...)
829 FOLLY_PRINTF_FORMAT_ATTR(2, 3);
831 void vprintf(const char* fmt, va_list ap);
834 * Calling an Appender object with a StringPiece will append the string
835 * piece. This allows Appender objects to be used directly with
838 void operator()(StringPiece sp) {
843 bool tryGrowChain() {
844 assert(crtBuf_->next() == buffer_);
849 buffer_->prependChain(IOBuf::create(growth_));
850 crtBuf_ = buffer_->prev();
859 class QueueAppender : public detail::Writable<QueueAppender> {
862 * Create an Appender that writes to a IOBufQueue. When we allocate
863 * space in the queue, we grow no more than growth bytes at once
864 * (unless you call ensure() with a bigger value yourself).
866 QueueAppender(IOBufQueue* queue, uint64_t growth) {
867 reset(queue, growth);
870 void reset(IOBufQueue* queue, uint64_t growth) {
875 uint8_t* writableData() {
876 return static_cast<uint8_t*>(queue_->writableTail());
879 size_t length() const { return queue_->tailroom(); }
881 void append(size_t n) { queue_->postallocate(n); }
883 // Ensure at least n contiguous; can go above growth_, throws if
885 void ensure(uint64_t n) { queue_->preallocate(n, growth_); }
888 typename std::enable_if<std::is_arithmetic<T>::value>::type
891 auto p = queue_->preallocate(sizeof(T), growth_);
892 storeUnaligned(p.first, value);
893 queue_->postallocate(sizeof(T));
896 using detail::Writable<QueueAppender>::pushAtMost;
897 size_t pushAtMost(const uint8_t* buf, size_t len) {
898 size_t remaining = len;
899 while (remaining != 0) {
900 auto p = queue_->preallocate(std::min(remaining, growth_),
903 memcpy(p.first, buf, p.second);
904 queue_->postallocate(p.second);
906 remaining -= p.second;
912 void insert(std::unique_ptr<folly::IOBuf> buf) {
914 queue_->append(std::move(buf), true);
919 folly::IOBufQueue* queue_;