From 29ba8408181362420acb20bcad2a82f22e033d19 Mon Sep 17 00:00:00 2001 From: Adam Simpkins Date: Thu, 20 Feb 2014 15:28:50 -0800 Subject: [PATCH] add operator +, ==, and != to Cursor classes Summary: Add operator+, which returns a new Cursor pointing the specified number of bytes ahead. Cursor already implemented a += operator. Also add == and != operators for checking to see if two cursors are pointing to the same location. Note that some derived cursor classes do contain additional state, and we don't consider that state when comparing for equality. For instance, two Appenders pointing to the same location will compare as equal, even if they are configured with different growth parameters. It seems like this is the behavior most users will expect, but let me know if you have concerns about this. Test Plan: Updated the unit tests to exercise the new operators. Reviewed By: davejwatson@fb.com FB internal diff: D1183537 --- folly/io/Cursor.h | 18 ++++++++++++++++++ folly/io/test/IOBufCursorTest.cpp | 18 +++++++++++++----- 2 files changed, 31 insertions(+), 5 deletions(-) diff --git a/folly/io/Cursor.h b/folly/io/Cursor.h index 764f52a1..f893d5a4 100644 --- a/folly/io/Cursor.h +++ b/folly/io/Cursor.h @@ -84,6 +84,24 @@ class CursorBase { p->skip(offset); return *p; } + Derived operator+(size_t offset) const { + Derived other(*this); + other.skip(offset); + return other; + } + + /** + * Compare cursors for equality/inequality. + * + * Two cursors are equal if they are pointing to the same location in the + * same IOBuf chain. + */ + bool operator==(const Derived& other) const { + return (offset_ == other.offset_) && (crtBuf_ == other.crtBuf_); + } + bool operator!=(const Derived& other) const { + return !operator==(other); + } template typename std::enable_if::value, T>::type diff --git a/folly/io/test/IOBufCursorTest.cpp b/folly/io/test/IOBufCursorTest.cpp index e0bf5a5a..d0f369c3 100644 --- a/folly/io/test/IOBufCursorTest.cpp +++ b/folly/io/test/IOBufCursorTest.cpp @@ -98,15 +98,23 @@ TEST(IOBuf, copy_assign_convert) { EXPECT_EQ(3, cursor4.read()); } -TEST(IOBuf, overloading) { - unique_ptr iobuf1(IOBuf::create(20)); - iobuf1->append(20); - RWPrivateCursor wcursor(iobuf1.get()); +TEST(IOBuf, arithmetic) { + IOBuf iobuf1(IOBuf::CREATE, 20); + iobuf1.append(20); + RWPrivateCursor wcursor(&iobuf1); wcursor += 1; wcursor.write((uint8_t)1); - Cursor cursor(iobuf1.get()); + Cursor cursor(&iobuf1); cursor += 1; EXPECT_EQ(1, cursor.read()); + + Cursor start(&iobuf1); + Cursor cursor2 = start + 9; + EXPECT_EQ(7, cursor2 - cursor); + EXPECT_NE(cursor, cursor2); + cursor += 8; + cursor2 = cursor2 + 1; + EXPECT_EQ(cursor, cursor2); } TEST(IOBuf, endian) { -- 2.34.1