2 * Copyright 2015 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #ifndef FOLLY_CURSOR_H
18 #define FOLLY_CURSOR_H
24 #include <type_traits>
27 #include <folly/Bits.h>
28 #include <folly/io/IOBuf.h>
29 #include <folly/io/IOBufQueue.h>
30 #include <folly/Likely.h>
31 #include <folly/Memory.h>
32 #include <folly/Portability.h>
33 #include <folly/Range.h>
36 * Cursor class for fast iteration over IOBuf chains.
38 * Cursor - Read-only access
40 * RWPrivateCursor - Read-write access, assumes private access to IOBuf chain
41 * RWUnshareCursor - Read-write access, calls unshare on write (COW)
42 * Appender - Write access, assumes private access to IOBuf chian
44 * Note that RW cursors write in the preallocated part of buffers (that is,
45 * between the buffer's data() and tail()), while Appenders append to the end
46 * of the buffer (between the buffer's tail() and bufferEnd()). Appenders
47 * automatically adjust the buffer pointers, so you may only use one
48 * Appender with a buffer chain; for this reason, Appenders assume private
49 * access to the buffer (you need to call unshare() yourself if necessary).
51 namespace folly { namespace io {
55 template <class Derived, class BufType>
57 // Make all the templated classes friends for copy constructor.
58 template <class D, typename B> friend class CursorBase;
60 explicit CursorBase(BufType* buf) : crtBuf_(buf), buffer_(buf) { }
65 * This also allows constructing a CursorBase from other derived types.
66 * For instance, this allows constructing a Cursor from an RWPrivateCursor.
68 template <class OtherDerived, class OtherBuf>
69 explicit CursorBase(const CursorBase<OtherDerived, OtherBuf>& cursor)
70 : crtBuf_(cursor.crtBuf_),
71 offset_(cursor.offset_),
72 buffer_(cursor.buffer_) { }
75 * Reset cursor to point to a new buffer.
77 void reset(BufType* buf) {
83 const uint8_t* data() const {
84 return crtBuf_->data() + offset_;
88 * Return the remaining space available in the current IOBuf.
90 * May return 0 if the cursor is at the end of an IOBuf. Use peek() instead
91 * if you want to avoid this. peek() will advance to the next non-empty
92 * IOBuf (up to the end of the chain) if the cursor is currently pointing at
93 * the end of a buffer.
95 size_t length() const {
96 return crtBuf_->length() - offset_;
100 * Return the space available until the end of the entire IOBuf chain.
102 size_t totalLength() const {
103 if (crtBuf_ == buffer_) {
104 return crtBuf_->computeChainDataLength() - offset_;
106 CursorBase end(buffer_->prev());
107 end.offset_ = end.buffer_->length();
112 * Return true if the cursor is at the end of the entire IOBuf chain.
114 bool isAtEnd() const {
115 // Check for the simple cases first.
116 if (offset_ != crtBuf_->length()) {
119 if (crtBuf_ == buffer_->prev()) {
122 // We are at the end of a buffer, but it isn't the last buffer.
123 // We might still be at the end if the remaining buffers in the chain are
125 const IOBuf* buf = crtBuf_->next();;
126 while (buf != buffer_) {
127 if (buf->length() > 0) {
135 Derived& operator+=(size_t offset) {
136 Derived* p = static_cast<Derived*>(this);
140 Derived operator+(size_t offset) const {
141 Derived other(*this);
147 * Compare cursors for equality/inequality.
149 * Two cursors are equal if they are pointing to the same location in the
152 bool operator==(const Derived& other) const {
153 return (offset_ == other.offset_) && (crtBuf_ == other.crtBuf_);
155 bool operator!=(const Derived& other) const {
156 return !operator==(other);
160 typename std::enable_if<std::is_arithmetic<T>::value, T>::type read() {
162 if (LIKELY(length() >= sizeof(T))) {
163 val = loadUnaligned<T>(data());
164 offset_ += sizeof(T);
166 pullSlow(&val, sizeof(T));
173 return Endian::big(read<T>());
178 return Endian::little(read<T>());
182 * Read a fixed-length string.
184 * The std::string-based APIs should probably be avoided unless you
185 * ultimately want the data to live in an std::string. You're better off
186 * using the pull() APIs to copy into a raw buffer otherwise.
188 std::string readFixedString(size_t len) {
191 if (LIKELY(length() >= len)) {
192 str.append(reinterpret_cast<const char*>(data()), len);
195 readFixedStringSlow(&str, len);
201 * Read a string consisting of bytes until the given terminator character is
202 * seen. Raises an std::length_error if maxLength bytes have been processed
203 * before the terminator is seen.
205 * See comments in readFixedString() about when it's appropriate to use this
208 std::string readTerminatedString(
209 char termChar = '\0',
210 size_t maxLength = std::numeric_limits<size_t>::max()) {
214 const uint8_t* buf = data();
215 size_t buflen = length();
218 while (i < buflen && buf[i] != termChar) {
221 // Do this check after incrementing 'i', as even though we start at the
222 // 0 byte, it still represents a single character
223 if (str.length() + i >= maxLength) {
224 throw std::length_error("string overflow");
228 str.append(reinterpret_cast<const char*>(buf), i);
236 if (UNLIKELY(!tryAdvanceBuffer())) {
237 throw std::out_of_range("string underflow");
242 size_t skipAtMost(size_t len) {
243 if (LIKELY(length() >= len)) {
247 return skipAtMostSlow(len);
250 void skip(size_t len) {
251 if (LIKELY(length() >= len)) {
258 size_t pullAtMost(void* buf, size_t len) {
259 // Fast path: it all fits in one buffer.
260 if (LIKELY(length() >= len)) {
261 memcpy(buf, data(), len);
265 return pullAtMostSlow(buf, len);
268 void pull(void* buf, size_t len) {
269 if (LIKELY(length() >= len)) {
270 memcpy(buf, data(), len);
278 * Return the available data in the current buffer.
279 * If you want to gather more data from the chain into a contiguous region
280 * (for hopefully zero-copy access), use gather() before peek().
282 std::pair<const uint8_t*, size_t> peek() {
283 // Ensure that we're pointing to valid data
284 size_t available = length();
285 while (UNLIKELY(available == 0 && tryAdvanceBuffer())) {
286 available = length();
288 return std::make_pair(data(), available);
291 void clone(std::unique_ptr<folly::IOBuf>& buf, size_t len) {
292 if (UNLIKELY(cloneAtMost(buf, len) != len)) {
293 throw std::out_of_range("underflow");
297 void clone(folly::IOBuf& buf, size_t len) {
298 if (UNLIKELY(cloneAtMost(buf, len) != len)) {
299 throw std::out_of_range("underflow");
303 size_t cloneAtMost(folly::IOBuf& buf, size_t len) {
304 buf = folly::IOBuf();
306 std::unique_ptr<folly::IOBuf> tmp;
308 for (int loopCount = 0; true; ++loopCount) {
309 // Fast path: it all fits in one buffer.
310 size_t available = length();
311 if (LIKELY(available >= len)) {
312 if (loopCount == 0) {
313 crtBuf_->cloneOneInto(buf);
314 buf.trimStart(offset_);
315 buf.trimEnd(buf.length() - len);
317 tmp = crtBuf_->cloneOne();
318 tmp->trimStart(offset_);
319 tmp->trimEnd(tmp->length() - len);
320 buf.prependChain(std::move(tmp));
327 if (loopCount == 0) {
328 crtBuf_->cloneOneInto(buf);
329 buf.trimStart(offset_);
331 tmp = crtBuf_->cloneOne();
332 tmp->trimStart(offset_);
333 buf.prependChain(std::move(tmp));
337 if (UNLIKELY(!tryAdvanceBuffer())) {
344 size_t cloneAtMost(std::unique_ptr<folly::IOBuf>& buf, size_t len) {
346 buf = make_unique<folly::IOBuf>();
348 return cloneAtMost(*buf, len);
352 * Return the distance between two cursors.
354 size_t operator-(const CursorBase& other) const {
355 BufType *otherBuf = other.crtBuf_;
358 if (otherBuf != crtBuf_) {
359 len += otherBuf->length() - other.offset_;
361 for (otherBuf = otherBuf->next();
362 otherBuf != crtBuf_ && otherBuf != other.buffer_;
363 otherBuf = otherBuf->next()) {
364 len += otherBuf->length();
367 if (otherBuf == other.buffer_) {
368 throw std::out_of_range("wrap-around");
373 if (offset_ < other.offset_) {
374 throw std::out_of_range("underflow");
377 len += offset_ - other.offset_;
384 * Return the distance from the given IOBuf to the this cursor.
386 size_t operator-(const BufType* buf) const {
389 BufType *curBuf = buf;
390 while (curBuf != crtBuf_) {
391 len += curBuf->length();
392 curBuf = curBuf->next();
393 if (curBuf == buf || curBuf == buffer_) {
394 throw std::out_of_range("wrap-around");
409 bool tryAdvanceBuffer() {
410 BufType* nextBuf = crtBuf_->next();
411 if (UNLIKELY(nextBuf == buffer_)) {
412 offset_ = crtBuf_->length();
418 static_cast<Derived*>(this)->advanceDone();
426 void readFixedStringSlow(std::string* str, size_t len) {
427 for (size_t available; (available = length()) < len; ) {
428 str->append(reinterpret_cast<const char*>(data()), available);
429 if (UNLIKELY(!tryAdvanceBuffer())) {
430 throw std::out_of_range("string underflow");
434 str->append(reinterpret_cast<const char*>(data()), len);
438 size_t pullAtMostSlow(void* buf, size_t len) {
439 uint8_t* p = reinterpret_cast<uint8_t*>(buf);
441 for (size_t available; (available = length()) < len; ) {
442 memcpy(p, data(), available);
444 if (UNLIKELY(!tryAdvanceBuffer())) {
450 memcpy(p, data(), len);
455 void pullSlow(void* buf, size_t len) {
456 if (UNLIKELY(pullAtMostSlow(buf, len) != len)) {
457 throw std::out_of_range("underflow");
461 size_t skipAtMostSlow(size_t len) {
463 for (size_t available; (available = length()) < len; ) {
464 skipped += available;
465 if (UNLIKELY(!tryAdvanceBuffer())) {
471 return skipped + len;
474 void skipSlow(size_t len) {
475 if (UNLIKELY(skipAtMostSlow(len) != len)) {
476 throw std::out_of_range("underflow");
486 } // namespace detail
488 class Cursor : public detail::CursorBase<Cursor, const IOBuf> {
490 explicit Cursor(const IOBuf* buf)
491 : detail::CursorBase<Cursor, const IOBuf>(buf) {}
493 template <class OtherDerived, class OtherBuf>
494 explicit Cursor(const detail::CursorBase<OtherDerived, OtherBuf>& cursor)
495 : detail::CursorBase<Cursor, const IOBuf>(cursor) {}
500 template <class Derived>
504 typename std::enable_if<std::is_arithmetic<T>::value>::type
506 const uint8_t* u8 = reinterpret_cast<const uint8_t*>(&value);
507 Derived* d = static_cast<Derived*>(this);
508 d->push(u8, sizeof(T));
512 void writeBE(T value) {
513 Derived* d = static_cast<Derived*>(this);
514 d->write(Endian::big(value));
518 void writeLE(T value) {
519 Derived* d = static_cast<Derived*>(this);
520 d->write(Endian::little(value));
523 void push(const uint8_t* buf, size_t len) {
524 Derived* d = static_cast<Derived*>(this);
525 if (d->pushAtMost(buf, len) != len) {
526 throw std::out_of_range("overflow");
530 void push(ByteRange buf) {
531 if (this->pushAtMost(buf) != buf.size()) {
532 throw std::out_of_range("overflow");
536 size_t pushAtMost(ByteRange buf) {
537 Derived* d = static_cast<Derived*>(this);
538 return d->pushAtMost(buf.data(), buf.size());
542 * push len bytes of data from input cursor, data could be in an IOBuf chain.
543 * If input cursor contains less than len bytes, or this cursor has less than
544 * len bytes writable space, an out_of_range exception will be thrown.
546 void push(Cursor cursor, size_t len) {
547 if (this->pushAtMost(cursor, len) != len) {
548 throw std::out_of_range("overflow");
552 size_t pushAtMost(Cursor cursor, size_t len) {
555 auto currentBuffer = cursor.peek();
556 const uint8_t* crtData = currentBuffer.first;
557 size_t available = currentBuffer.second;
558 if (available == 0) {
559 // end of buffer chain
562 // all data is in current buffer
563 if (available >= len) {
564 this->push(crtData, len);
566 return written + len;
569 // write the whole current IOBuf
570 this->push(crtData, available);
571 cursor.skip(available);
572 written += available;
578 } // namespace detail
580 enum class CursorAccess {
585 template <CursorAccess access>
587 : public detail::CursorBase<RWCursor<access>, IOBuf>,
588 public detail::Writable<RWCursor<access>> {
589 friend class detail::CursorBase<RWCursor<access>, IOBuf>;
591 explicit RWCursor(IOBuf* buf)
592 : detail::CursorBase<RWCursor<access>, IOBuf>(buf),
593 maybeShared_(true) {}
595 template <class OtherDerived, class OtherBuf>
596 explicit RWCursor(const detail::CursorBase<OtherDerived, OtherBuf>& cursor)
597 : detail::CursorBase<RWCursor<access>, IOBuf>(cursor),
598 maybeShared_(true) {}
600 * Gather at least n bytes contiguously into the current buffer,
601 * by coalescing subsequent buffers from the chain as necessary.
603 void gather(size_t n) {
604 // Forbid attempts to gather beyond the end of this IOBuf chain.
605 // Otherwise we could try to coalesce the head of the chain and end up
606 // accidentally freeing it, invalidating the pointer owned by external
609 // If crtBuf_ == head() then IOBuf::gather() will perform all necessary
610 // checking. We only have to perform an explicit check here when calling
611 // gather() on a non-head element.
612 if (this->crtBuf_ != this->head() && this->totalLength() < n) {
613 throw std::overflow_error("cannot gather() past the end of the chain");
615 this->crtBuf_->gather(this->offset_ + n);
617 void gatherAtMost(size_t n) {
618 size_t size = std::min(n, this->totalLength());
619 return this->crtBuf_->gather(this->offset_ + size);
622 using detail::Writable<RWCursor<access>>::pushAtMost;
623 size_t pushAtMost(const uint8_t* buf, size_t len) {
626 // Fast path: the current buffer is big enough.
627 size_t available = this->length();
628 if (LIKELY(available >= len)) {
629 if (access == CursorAccess::UNSHARE) {
632 memcpy(writableData(), buf, len);
633 this->offset_ += len;
637 if (access == CursorAccess::UNSHARE) {
640 memcpy(writableData(), buf, available);
642 if (UNLIKELY(!this->tryAdvanceBuffer())) {
650 void insert(std::unique_ptr<folly::IOBuf> buf) {
651 folly::IOBuf* nextBuf;
652 if (this->offset_ == 0) {
654 nextBuf = this->crtBuf_;
655 this->crtBuf_->prependChain(std::move(buf));
657 std::unique_ptr<folly::IOBuf> remaining;
658 if (this->crtBuf_->length() - this->offset_ > 0) {
659 // Need to split current IOBuf in two.
660 remaining = this->crtBuf_->cloneOne();
661 remaining->trimStart(this->offset_);
662 nextBuf = remaining.get();
663 buf->prependChain(std::move(remaining));
666 nextBuf = this->crtBuf_->next();
668 this->crtBuf_->trimEnd(this->length());
669 this->crtBuf_->appendChain(std::move(buf));
671 // Jump past the new links
673 this->crtBuf_ = nextBuf;
676 uint8_t* writableData() {
677 return this->crtBuf_->writableData() + this->offset_;
681 void maybeUnshare() {
682 if (UNLIKELY(maybeShared_)) {
683 this->crtBuf_->unshareOne();
684 maybeShared_ = false;
695 typedef RWCursor<CursorAccess::PRIVATE> RWPrivateCursor;
696 typedef RWCursor<CursorAccess::UNSHARE> RWUnshareCursor;
699 * Append to the end of a buffer chain, growing the chain (by allocating new
700 * buffers) in increments of at least growth bytes every time. Won't grow
701 * (and push() and ensure() will throw) if growth == 0.
703 * TODO(tudorb): add a flavor of Appender that reallocates one IOBuf instead
706 class Appender : public detail::Writable<Appender> {
708 Appender(IOBuf* buf, uint64_t growth)
710 crtBuf_(buf->prev()),
714 uint8_t* writableData() {
715 return crtBuf_->writableTail();
718 size_t length() const {
719 return crtBuf_->tailroom();
723 * Mark n bytes (must be <= length()) as appended, as per the
724 * IOBuf::append() method.
726 void append(size_t n) {
731 * Ensure at least n contiguous bytes available to write.
732 * Postcondition: length() >= n.
734 void ensure(uint64_t n) {
735 if (LIKELY(length() >= n)) {
739 // Waste the rest of the current buffer and allocate a new one.
740 // Don't make it too small, either.
742 throw std::out_of_range("can't grow buffer chain");
745 n = std::max(n, growth_);
746 buffer_->prependChain(IOBuf::create(n));
747 crtBuf_ = buffer_->prev();
750 using detail::Writable<Appender>::pushAtMost;
751 size_t pushAtMost(const uint8_t* buf, size_t len) {
754 // Fast path: it all fits in one buffer.
755 size_t available = length();
756 if (LIKELY(available >= len)) {
757 memcpy(writableData(), buf, len);
762 memcpy(writableData(), buf, available);
765 if (UNLIKELY(!tryGrowChain())) {
774 * Append to the end of this buffer, using a printf() style
777 * Note that folly/Format.h provides nicer and more type-safe mechanisms
778 * for formatting strings, which should generally be preferred over
779 * printf-style formatting. Appender objects can be used directly as an
780 * output argument for Formatter objects. For example:
782 * Appender app(&iobuf);
783 * format("{} {}", "hello", "world")(app);
785 * However, printf-style strings are still needed when dealing with existing
786 * third-party code in some cases.
788 * This will always add a nul-terminating character after the end
789 * of the output. However, the buffer data length will only be updated to
790 * include the data itself. The nul terminator will be the first byte in the
793 * This method may throw exceptions on error.
795 void printf(FOLLY_PRINTF_FORMAT const char* fmt, ...)
796 FOLLY_PRINTF_FORMAT_ATTR(2, 3);
798 void vprintf(const char* fmt, va_list ap);
801 * Calling an Appender object with a StringPiece will append the string
802 * piece. This allows Appender objects to be used directly with
805 void operator()(StringPiece sp) {
810 bool tryGrowChain() {
811 assert(crtBuf_->next() == buffer_);
816 buffer_->prependChain(IOBuf::create(growth_));
817 crtBuf_ = buffer_->prev();
826 class QueueAppender : public detail::Writable<QueueAppender> {
829 * Create an Appender that writes to a IOBufQueue. When we allocate
830 * space in the queue, we grow no more than growth bytes at once
831 * (unless you call ensure() with a bigger value yourself).
833 QueueAppender(IOBufQueue* queue, uint64_t growth) {
834 reset(queue, growth);
837 void reset(IOBufQueue* queue, uint64_t growth) {
842 uint8_t* writableData() {
843 return static_cast<uint8_t*>(queue_->writableTail());
846 size_t length() const { return queue_->tailroom(); }
848 void append(size_t n) { queue_->postallocate(n); }
850 // Ensure at least n contiguous; can go above growth_, throws if
852 void ensure(uint64_t n) { queue_->preallocate(n, growth_); }
855 typename std::enable_if<std::is_arithmetic<T>::value>::type
858 auto p = queue_->preallocate(sizeof(T), growth_);
859 storeUnaligned(p.first, value);
860 queue_->postallocate(sizeof(T));
863 using detail::Writable<QueueAppender>::pushAtMost;
864 size_t pushAtMost(const uint8_t* buf, size_t len) {
865 size_t remaining = len;
866 while (remaining != 0) {
867 auto p = queue_->preallocate(std::min(remaining, growth_),
870 memcpy(p.first, buf, p.second);
871 queue_->postallocate(p.second);
873 remaining -= p.second;
879 void insert(std::unique_ptr<folly::IOBuf> buf) {
881 queue_->append(std::move(buf), true);
886 folly::IOBufQueue* queue_;
892 #endif // FOLLY_CURSOR_H