2 * Copyright 2014 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 {
54 template <class Derived, typename BufType>
57 const uint8_t* data() const {
58 return crtBuf_->data() + offset_;
62 * Return the remaining space available in the current IOBuf.
64 * May return 0 if the cursor is at the end of an IOBuf. Use peek() instead
65 * if you want to avoid this. peek() will advance to the next non-empty
66 * IOBuf (up to the end of the chain) if the cursor is currently pointing at
67 * the end of a buffer.
69 size_t length() const {
70 return crtBuf_->length() - offset_;
74 * Return the space available until the end of the entire IOBuf chain.
76 size_t totalLength() const {
77 if (crtBuf_ == buffer_) {
78 return crtBuf_->computeChainDataLength() - offset_;
80 CursorBase end(buffer_->prev());
81 end.offset_ = end.buffer_->length();
85 Derived& operator+=(size_t offset) {
86 Derived* p = static_cast<Derived*>(this);
90 Derived operator+(size_t offset) const {
97 * Compare cursors for equality/inequality.
99 * Two cursors are equal if they are pointing to the same location in the
102 bool operator==(const Derived& other) const {
103 return (offset_ == other.offset_) && (crtBuf_ == other.crtBuf_);
105 bool operator!=(const Derived& other) const {
106 return !operator==(other);
110 typename std::enable_if<std::is_arithmetic<T>::value, T>::type
113 pull(&val, sizeof(T));
119 return Endian::big(read<T>());
124 return Endian::little(read<T>());
128 * Read a fixed-length string.
130 * The std::string-based APIs should probably be avoided unless you
131 * ultimately want the data to live in an std::string. You're better off
132 * using the pull() APIs to copy into a raw buffer otherwise.
134 std::string readFixedString(size_t len) {
139 // Fast path: it all fits in one buffer.
140 size_t available = length();
141 if (LIKELY(available >= len)) {
142 str.append(reinterpret_cast<const char*>(data()), len);
147 str.append(reinterpret_cast<const char*>(data()), available);
148 if (UNLIKELY(!tryAdvanceBuffer())) {
149 throw std::out_of_range("string underflow");
156 * Read a string consisting of bytes until the given terminator character is
157 * seen. Raises an std::length_error if maxLength bytes have been processed
158 * before the terminator is seen.
160 * See comments in readFixedString() about when it's appropriate to use this
163 std::string readTerminatedString(
164 char termChar = '\0',
165 size_t maxLength = std::numeric_limits<size_t>::max()) {
169 const uint8_t* buf = data();
170 size_t buflen = length();
173 while (i < buflen && buf[i] != termChar) {
176 // Do this check after incrementing 'i', as even though we start at the
177 // 0 byte, it still represents a single character
178 if (str.length() + i >= maxLength) {
179 throw std::length_error("string overflow");
183 str.append(reinterpret_cast<const char*>(buf), i);
191 if (UNLIKELY(!tryAdvanceBuffer())) {
192 throw std::out_of_range("string underflow");
197 explicit CursorBase(BufType* buf)
202 // Make all the templated classes friends for copy constructor.
203 template <class D, typename B> friend class CursorBase;
208 * This also allows constructing a CursorBase from other derived types.
209 * For instance, this allows constructing a Cursor from an RWPrivateCursor.
211 template <class OtherDerived, class OtherBuf>
212 explicit CursorBase(const CursorBase<OtherDerived, OtherBuf>& cursor)
213 : crtBuf_(cursor.crtBuf_),
214 offset_(cursor.offset_),
215 buffer_(cursor.buffer_) {}
217 // reset cursor to point to a new buffer.
218 void reset(BufType* buf) {
225 * Return the available data in the current buffer.
226 * If you want to gather more data from the chain into a contiguous region
227 * (for hopefully zero-copy access), use gather() before peek().
229 std::pair<const uint8_t*, size_t> peek() {
230 // Ensure that we're pointing to valid data
231 size_t available = length();
232 while (UNLIKELY(available == 0 && tryAdvanceBuffer())) {
233 available = length();
236 return std::make_pair(data(), available);
239 void pull(void* buf, size_t len) {
240 if (UNLIKELY(pullAtMost(buf, len) != len)) {
241 throw std::out_of_range("underflow");
245 void clone(std::unique_ptr<folly::IOBuf>& buf, size_t len) {
246 if (UNLIKELY(cloneAtMost(buf, len) != len)) {
247 throw std::out_of_range("underflow");
251 void clone(folly::IOBuf& buf, size_t len) {
252 if (UNLIKELY(cloneAtMost(buf, len) != len)) {
253 throw std::out_of_range("underflow");
257 void skip(size_t len) {
258 if (UNLIKELY(skipAtMost(len) != len)) {
259 throw std::out_of_range("underflow");
263 size_t pullAtMost(void* buf, size_t len) {
264 uint8_t* p = reinterpret_cast<uint8_t*>(buf);
267 // Fast path: it all fits in one buffer.
268 size_t available = length();
269 if (LIKELY(available >= len)) {
270 memcpy(p, data(), len);
275 memcpy(p, data(), available);
277 if (UNLIKELY(!tryAdvanceBuffer())) {
285 size_t cloneAtMost(folly::IOBuf& buf, size_t len) {
286 buf = folly::IOBuf();
288 std::unique_ptr<folly::IOBuf> tmp;
290 for (int loopCount = 0; true; ++loopCount) {
291 // Fast path: it all fits in one buffer.
292 size_t available = length();
293 if (LIKELY(available >= len)) {
294 if (loopCount == 0) {
295 crtBuf_->cloneOneInto(buf);
296 buf.trimStart(offset_);
297 buf.trimEnd(buf.length() - len);
299 tmp = crtBuf_->cloneOne();
300 tmp->trimStart(offset_);
301 tmp->trimEnd(tmp->length() - len);
302 buf.prependChain(std::move(tmp));
310 if (loopCount == 0) {
311 crtBuf_->cloneOneInto(buf);
312 buf.trimStart(offset_);
314 tmp = crtBuf_->cloneOne();
315 tmp->trimStart(offset_);
316 buf.prependChain(std::move(tmp));
320 if (UNLIKELY(!tryAdvanceBuffer())) {
327 size_t cloneAtMost(std::unique_ptr<folly::IOBuf>& buf, size_t len) {
329 buf = make_unique<folly::IOBuf>();
332 return cloneAtMost(*buf, len);
335 size_t skipAtMost(size_t len) {
338 // Fast path: it all fits in one buffer.
339 size_t available = length();
340 if (LIKELY(available >= len)) {
342 return skipped + len;
345 skipped += available;
346 if (UNLIKELY(!tryAdvanceBuffer())) {
354 * Return the distance between two cursors.
356 size_t operator-(const CursorBase& other) const {
357 BufType *otherBuf = other.crtBuf_;
360 if (otherBuf != crtBuf_) {
361 len += otherBuf->length() - other.offset_;
363 for (otherBuf = otherBuf->next();
364 otherBuf != crtBuf_ && otherBuf != other.buffer_;
365 otherBuf = otherBuf->next()) {
366 len += otherBuf->length();
369 if (otherBuf == other.buffer_) {
370 throw std::out_of_range("wrap-around");
375 if (offset_ < other.offset_) {
376 throw std::out_of_range("underflow");
379 len += offset_ - other.offset_;
386 * Return the distance from the given IOBuf to the this cursor.
388 size_t operator-(const BufType* buf) const {
391 BufType *curBuf = buf;
392 while (curBuf != crtBuf_) {
393 len += curBuf->length();
394 curBuf = curBuf->next();
395 if (curBuf == buf || curBuf == buffer_) {
396 throw std::out_of_range("wrap-around");
414 bool tryAdvanceBuffer() {
415 BufType* nextBuf = crtBuf_->next();
416 if (UNLIKELY(nextBuf == buffer_)) {
417 offset_ = crtBuf_->length();
423 static_cast<Derived*>(this)->advanceDone();
436 class Cursor : public detail::CursorBase<Cursor, const IOBuf> {
438 explicit Cursor(const IOBuf* buf)
439 : detail::CursorBase<Cursor, const IOBuf>(buf) {}
441 template <class OtherDerived, class OtherBuf>
442 explicit Cursor(const detail::CursorBase<OtherDerived, OtherBuf>& cursor)
443 : detail::CursorBase<Cursor, const IOBuf>(cursor) {}
448 template <class Derived>
452 typename std::enable_if<std::is_arithmetic<T>::value>::type
454 const uint8_t* u8 = reinterpret_cast<const uint8_t*>(&value);
455 Derived* d = static_cast<Derived*>(this);
456 d->push(u8, sizeof(T));
460 void writeBE(T value) {
461 Derived* d = static_cast<Derived*>(this);
462 d->write(Endian::big(value));
466 void writeLE(T value) {
467 Derived* d = static_cast<Derived*>(this);
468 d->write(Endian::little(value));
471 void push(const uint8_t* buf, size_t len) {
472 Derived* d = static_cast<Derived*>(this);
473 if (d->pushAtMost(buf, len) != len) {
474 throw std::out_of_range("overflow");
478 void push(ByteRange buf) {
479 if (this->pushAtMost(buf) != buf.size()) {
480 throw std::out_of_range("overflow");
484 size_t pushAtMost(ByteRange buf) {
485 Derived* d = static_cast<Derived*>(this);
486 return d->pushAtMost(buf.data(), buf.size());
490 * push len bytes of data from input cursor, data could be in an IOBuf chain.
491 * If input cursor contains less than len bytes, or this cursor has less than
492 * len bytes writable space, an out_of_range exception will be thrown.
494 void push(Cursor cursor, size_t len) {
495 if (this->pushAtMost(cursor, len) != len) {
496 throw std::out_of_range("overflow");
500 size_t pushAtMost(Cursor cursor, size_t len) {
503 auto currentBuffer = cursor.peek();
504 const uint8_t* crtData = currentBuffer.first;
505 size_t available = currentBuffer.second;
506 if (available == 0) {
507 // end of buffer chain
510 // all data is in current buffer
511 if (available >= len) {
512 this->push(crtData, len);
514 return written + len;
517 // write the whole current IOBuf
518 this->push(crtData, available);
519 cursor.skip(available);
520 written += available;
526 } // namespace detail
528 enum class CursorAccess {
533 template <CursorAccess access>
535 : public detail::CursorBase<RWCursor<access>, IOBuf>,
536 public detail::Writable<RWCursor<access>> {
537 friend class detail::CursorBase<RWCursor<access>, IOBuf>;
539 explicit RWCursor(IOBuf* buf)
540 : detail::CursorBase<RWCursor<access>, IOBuf>(buf),
541 maybeShared_(true) {}
543 template <class OtherDerived, class OtherBuf>
544 explicit RWCursor(const detail::CursorBase<OtherDerived, OtherBuf>& cursor)
545 : detail::CursorBase<RWCursor<access>, IOBuf>(cursor),
546 maybeShared_(true) {}
548 * Gather at least n bytes contiguously into the current buffer,
549 * by coalescing subsequent buffers from the chain as necessary.
551 void gather(size_t n) {
552 // Forbid attempts to gather beyond the end of this IOBuf chain.
553 // Otherwise we could try to coalesce the head of the chain and end up
554 // accidentally freeing it, invalidating the pointer owned by external
557 // If crtBuf_ == head() then IOBuf::gather() will perform all necessary
558 // checking. We only have to perform an explicit check here when calling
559 // gather() on a non-head element.
560 if (this->crtBuf_ != this->head() && this->totalLength() < n) {
561 throw std::overflow_error("cannot gather() past the end of the chain");
563 this->crtBuf_->gather(this->offset_ + n);
565 void gatherAtMost(size_t n) {
566 size_t size = std::min(n, this->totalLength());
567 return this->crtBuf_->gather(this->offset_ + size);
570 using detail::Writable<RWCursor<access>>::pushAtMost;
571 size_t pushAtMost(const uint8_t* buf, size_t len) {
574 // Fast path: the current buffer is big enough.
575 size_t available = this->length();
576 if (LIKELY(available >= len)) {
577 if (access == CursorAccess::UNSHARE) {
580 memcpy(writableData(), buf, len);
581 this->offset_ += len;
585 if (access == CursorAccess::UNSHARE) {
588 memcpy(writableData(), buf, available);
590 if (UNLIKELY(!this->tryAdvanceBuffer())) {
598 void insert(std::unique_ptr<folly::IOBuf> buf) {
599 folly::IOBuf* nextBuf;
600 if (this->offset_ == 0) {
602 nextBuf = this->crtBuf_;
603 this->crtBuf_->prependChain(std::move(buf));
605 std::unique_ptr<folly::IOBuf> remaining;
606 if (this->crtBuf_->length() - this->offset_ > 0) {
607 // Need to split current IOBuf in two.
608 remaining = this->crtBuf_->cloneOne();
609 remaining->trimStart(this->offset_);
610 nextBuf = remaining.get();
611 buf->prependChain(std::move(remaining));
614 nextBuf = this->crtBuf_->next();
616 this->crtBuf_->trimEnd(this->length());
617 this->crtBuf_->appendChain(std::move(buf));
619 // Jump past the new links
621 this->crtBuf_ = nextBuf;
624 uint8_t* writableData() {
625 return this->crtBuf_->writableData() + this->offset_;
629 void maybeUnshare() {
630 if (UNLIKELY(maybeShared_)) {
631 this->crtBuf_->unshareOne();
632 maybeShared_ = false;
643 typedef RWCursor<CursorAccess::PRIVATE> RWPrivateCursor;
644 typedef RWCursor<CursorAccess::UNSHARE> RWUnshareCursor;
647 * Append to the end of a buffer chain, growing the chain (by allocating new
648 * buffers) in increments of at least growth bytes every time. Won't grow
649 * (and push() and ensure() will throw) if growth == 0.
651 * TODO(tudorb): add a flavor of Appender that reallocates one IOBuf instead
654 class Appender : public detail::Writable<Appender> {
656 Appender(IOBuf* buf, uint64_t growth)
658 crtBuf_(buf->prev()),
662 uint8_t* writableData() {
663 return crtBuf_->writableTail();
666 size_t length() const {
667 return crtBuf_->tailroom();
671 * Mark n bytes (must be <= length()) as appended, as per the
672 * IOBuf::append() method.
674 void append(size_t n) {
679 * Ensure at least n contiguous bytes available to write.
680 * Postcondition: length() >= n.
682 void ensure(uint64_t n) {
683 if (LIKELY(length() >= n)) {
687 // Waste the rest of the current buffer and allocate a new one.
688 // Don't make it too small, either.
690 throw std::out_of_range("can't grow buffer chain");
693 n = std::max(n, growth_);
694 buffer_->prependChain(IOBuf::create(n));
695 crtBuf_ = buffer_->prev();
698 using detail::Writable<Appender>::pushAtMost;
699 size_t pushAtMost(const uint8_t* buf, size_t len) {
702 // Fast path: it all fits in one buffer.
703 size_t available = length();
704 if (LIKELY(available >= len)) {
705 memcpy(writableData(), buf, len);
710 memcpy(writableData(), buf, available);
713 if (UNLIKELY(!tryGrowChain())) {
722 * Append to the end of this buffer, using a printf() style
725 * Note that folly/Format.h provides nicer and more type-safe mechanisms
726 * for formatting strings, which should generally be preferred over
727 * printf-style formatting. Appender objects can be used directly as an
728 * output argument for Formatter objects. For example:
730 * Appender app(&iobuf);
731 * format("{} {}", "hello", "world")(app);
733 * However, printf-style strings are still needed when dealing with existing
734 * third-party code in some cases.
736 * This will always add a nul-terminating character after the end
737 * of the output. However, the buffer data length will only be updated to
738 * include the data itself. The nul terminator will be the first byte in the
741 * This method may throw exceptions on error.
743 void printf(FOLLY_PRINTF_FORMAT const char* fmt, ...)
744 FOLLY_PRINTF_FORMAT_ATTR(2, 3);
746 void vprintf(const char* fmt, va_list ap);
749 * Calling an Appender object with a StringPiece will append the string
750 * piece. This allows Appender objects to be used directly with
753 void operator()(StringPiece sp) {
758 bool tryGrowChain() {
759 assert(crtBuf_->next() == buffer_);
764 buffer_->prependChain(IOBuf::create(growth_));
765 crtBuf_ = buffer_->prev();
774 class QueueAppender : public detail::Writable<QueueAppender> {
777 * Create an Appender that writes to a IOBufQueue. When we allocate
778 * space in the queue, we grow no more than growth bytes at once
779 * (unless you call ensure() with a bigger value yourself).
781 QueueAppender(IOBufQueue* queue, uint64_t growth) {
782 reset(queue, growth);
785 void reset(IOBufQueue* queue, uint64_t growth) {
790 uint8_t* writableData() {
791 return static_cast<uint8_t*>(queue_->writableTail());
794 size_t length() const { return queue_->tailroom(); }
796 void append(size_t n) { queue_->postallocate(n); }
798 // Ensure at least n contiguous; can go above growth_, throws if
800 void ensure(uint64_t n) { queue_->preallocate(n, growth_); }
803 typename std::enable_if<std::is_arithmetic<T>::value>::type
806 auto p = queue_->preallocate(sizeof(T), growth_);
807 storeUnaligned(p.first, value);
808 queue_->postallocate(sizeof(T));
811 using detail::Writable<QueueAppender>::pushAtMost;
812 size_t pushAtMost(const uint8_t* buf, size_t len) {
813 size_t remaining = len;
814 while (remaining != 0) {
815 auto p = queue_->preallocate(std::min(remaining, growth_),
818 memcpy(p.first, buf, p.second);
819 queue_->postallocate(p.second);
821 remaining -= p.second;
827 void insert(std::unique_ptr<folly::IOBuf> buf) {
829 queue_->append(std::move(buf), true);
834 folly::IOBufQueue* queue_;
840 #endif // FOLLY_CURSOR_H