Add Range::erase
authorAlan Frindell <afrind@fb.com>
Tue, 19 Jan 2016 22:21:15 +0000 (14:21 -0800)
committerfacebook-github-bot-4 <folly-bot@fb.com>
Tue, 19 Jan 2016 23:20:26 +0000 (15:20 -0800)
Summary: Needed to use StringPiece with boost::algorithm::trim()

Reviewed By: yfeldblum

Differential Revision: D2833657

fb-gh-sync-id: 3430b1a2540279b2f69f04c871df3bca748f2cb1

folly/Range.h
folly/test/RangeTest.cpp

index 2e994732f80f6b9c9aabf5b53cc07cfa515f35fe..6bece6da47007172036085a765837a5b5881ca92 100644 (file)
@@ -594,6 +594,22 @@ public:
     return !empty() && back() == c;
   }
 
+  /**
+   * Remove the items in [b, e), as long as this subrange is at the beginning
+   * or end of the Range.
+   *
+   * Required for boost::algorithm::trim()
+   */
+  void erase(Iter b, Iter e) {
+    if (b == b_) {
+      b_ = e;
+    } else if (e == e_) {
+      e_ = b;
+    } else {
+      throw std::out_of_range("index out of range");
+    }
+  }
+
   /**
    * Remove the given prefix and return true if the range starts with the given
    * prefix; return false otherwise.
index f9ffda970cda2588e5dd411fca9f50f45ed60980..b1cdace815ac4e114042f1348f8667b14752259b 100644 (file)
@@ -29,6 +29,7 @@
 #include <type_traits>
 #include <vector>
 #include <boost/range/concepts.hpp>
+#include <boost/algorithm/string/trim.hpp>
 #include <gtest/gtest.h>
 
 using namespace folly;
@@ -420,6 +421,43 @@ TEST(StringPiece, SuffixEmpty) {
   EXPECT_EQ("", a);
 }
 
+TEST(StringPiece, erase) {
+  StringPiece a("hello");
+  auto b = a.begin();
+  auto e = b + 1;
+  a.erase(b, e);
+  EXPECT_EQ("ello", a);
+
+  e = a.end();
+  b = e - 1;
+  a.erase(b, e);
+  EXPECT_EQ("ell", a);
+
+  b = a.end() - 1;
+  e = a.end() - 1;
+  EXPECT_THROW(a.erase(b, e), std::out_of_range);
+
+  b = a.begin();
+  e = a.end();
+  a.erase(b, e);
+  EXPECT_EQ("", a);
+
+  a = "hello";
+  b = a.begin();
+  e = b + 2;
+  a.erase(b, e);
+  EXPECT_EQ("llo", a);
+
+  b = a.end() - 2;
+  e = a.end();
+  a.erase(b, e);
+  EXPECT_EQ("l", a);
+
+  a = "      hello  ";
+  boost::algorithm::trim(a);
+  EXPECT_EQ(a, "hello");
+}
+
 TEST(StringPiece, split_step_char_delimiter) {
   //              0         1         2
   //              012345678901234567890123456