Commit 29ba8408 authored by Adam Simpkins's avatar Adam Simpkins Committed by Dave Watson

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
parent 788c6823
...@@ -84,6 +84,24 @@ class CursorBase { ...@@ -84,6 +84,24 @@ class CursorBase {
p->skip(offset); p->skip(offset);
return *p; 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 <class T> template <class T>
typename std::enable_if<std::is_arithmetic<T>::value, T>::type typename std::enable_if<std::is_arithmetic<T>::value, T>::type
......
...@@ -98,15 +98,23 @@ TEST(IOBuf, copy_assign_convert) { ...@@ -98,15 +98,23 @@ TEST(IOBuf, copy_assign_convert) {
EXPECT_EQ(3, cursor4.read<uint8_t>()); EXPECT_EQ(3, cursor4.read<uint8_t>());
} }
TEST(IOBuf, overloading) { TEST(IOBuf, arithmetic) {
unique_ptr<IOBuf> iobuf1(IOBuf::create(20)); IOBuf iobuf1(IOBuf::CREATE, 20);
iobuf1->append(20); iobuf1.append(20);
RWPrivateCursor wcursor(iobuf1.get()); RWPrivateCursor wcursor(&iobuf1);
wcursor += 1; wcursor += 1;
wcursor.write((uint8_t)1); wcursor.write((uint8_t)1);
Cursor cursor(iobuf1.get()); Cursor cursor(&iobuf1);
cursor += 1; cursor += 1;
EXPECT_EQ(1, cursor.read<uint8_t>()); EXPECT_EQ(1, cursor.read<uint8_t>());
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) { TEST(IOBuf, endian) {
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment