[Bf-blender-cvs] [c8816dbd310] functions: StringRef.drop_prefix

Jacques Lucke noreply at git.blender.org
Mon Jul 8 17:57:09 CEST 2019


Commit: c8816dbd310549767d4db6719368977747a69351
Author: Jacques Lucke
Date:   Mon Jul 8 14:14:45 2019 +0200
Branches: functions
https://developer.blender.org/rBc8816dbd310549767d4db6719368977747a69351

StringRef.drop_prefix

===================================================================

M	source/blender/blenlib/BLI_string_ref.hpp
M	tests/gtests/blenlib/BLI_string_ref_test.cc

===================================================================

diff --git a/source/blender/blenlib/BLI_string_ref.hpp b/source/blender/blenlib/BLI_string_ref.hpp
index e722d9cfe98..bd688ac673b 100644
--- a/source/blender/blenlib/BLI_string_ref.hpp
+++ b/source/blender/blenlib/BLI_string_ref.hpp
@@ -76,8 +76,14 @@ class StringRefBase {
     return m_data + m_size;
   }
 
+  /**
+   * Returns true when the string begins with the given prefix. Otherwise false.
+   */
   bool startswith(StringRef prefix) const;
 
+  /**
+   * Returns true when the string ends with the given suffix. Otherwise false.
+   */
   bool endswith(StringRef suffix) const;
 
   /**
@@ -133,6 +139,25 @@ class StringRef : public StringRefBase {
   StringRef(const std::string &str) : StringRefBase(str.data(), str.size())
   {
   }
+
+  /**
+   * Return a new StringRef that does not contain the first n chars.
+   */
+  StringRef drop_prefix(uint n) const
+  {
+    BLI_assert(n <= m_size);
+    return StringRef(m_data + n, m_size - n);
+  }
+
+  /**
+   * Return a new StringRef that with the given prefix being skipped.
+   * Asserts when the string does not begin with the prefix.
+   */
+  StringRef drop_prefix(StringRef prefix) const
+  {
+    BLI_assert(this->startswith(prefix));
+    return this->drop_prefix(prefix.size());
+  }
 };
 
 /* More inline functions
diff --git a/tests/gtests/blenlib/BLI_string_ref_test.cc b/tests/gtests/blenlib/BLI_string_ref_test.cc
index cb81c7676d6..44a7f895eaa 100644
--- a/tests/gtests/blenlib/BLI_string_ref_test.cc
+++ b/tests/gtests/blenlib/BLI_string_ref_test.cc
@@ -199,3 +199,22 @@ TEST(string_ref, EndsWith)
   EXPECT_FALSE(ref.endswith(" test"));
   EXPECT_FALSE(ref.endswith("a"));
 }
+
+TEST(string_ref, DropPrefixN)
+{
+  StringRef ref("test");
+  StringRef ref2 = ref.drop_prefix(2);
+  StringRef ref3 = ref2.drop_prefix(2);
+  EXPECT_EQ(ref2.size(), 2);
+  EXPECT_EQ(ref3.size(), 0);
+  EXPECT_EQ(ref2, "st");
+  EXPECT_EQ(ref3, "");
+}
+
+TEST(string_ref, DropPrefix)
+{
+  StringRef ref("test");
+  StringRef ref2 = ref.drop_prefix("tes");
+  EXPECT_EQ(ref2.size(), 1);
+  EXPECT_EQ(ref2, "t");
+}



More information about the Bf-blender-cvs mailing list