add operator +, ==, and != to Cursor classes
authorAdam Simpkins <simpkins@fb.com>
Thu, 20 Feb 2014 23:28:50 +0000 (15:28 -0800)
committerDave Watson <davejwatson@fb.com>
Fri, 28 Feb 2014 22:02:43 +0000 (14:02 -0800)
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
folly/io/test/IOBufCursorTest.cpp

index 764f52a1f4d4b0ed419aa52cb3f15e84ef20459f..f893d5a437937911e25329eb8ee28beef00b5c09 100644 (file)
@@ -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 <class T>
   typename std::enable_if<std::is_arithmetic<T>::value, T>::type
index e0bf5a5adff69c2bf016aa9824918ff3b4d19dcf..d0f369c3794f4f5f4af32349ddf6205bc4ca28ae 100644 (file)
@@ -98,15 +98,23 @@ TEST(IOBuf, copy_assign_convert) {
   EXPECT_EQ(3, cursor4.read<uint8_t>());
 }
 
-TEST(IOBuf, overloading) {
-  unique_ptr<IOBuf> 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<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) {