[Bf-blender-cvs] [4c172f7ca6c] master: BLI: support constructing StringRef from start and end pointer

Jacques Lucke noreply at git.blender.org
Wed Jun 10 18:27:34 CEST 2020


Commit: 4c172f7ca6cff1387220696166a6e0ee9758ac98
Author: Jacques Lucke
Date:   Wed Jun 10 18:26:11 2020 +0200
Branches: master
https://developer.blender.org/rB4c172f7ca6cff1387220696166a6e0ee9758ac98

BLI: support constructing StringRef from start and end pointer

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

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

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

diff --git a/source/blender/blenlib/BLI_string_ref.hh b/source/blender/blenlib/BLI_string_ref.hh
index 8ed923068a8..073137fe175 100644
--- a/source/blender/blenlib/BLI_string_ref.hh
+++ b/source/blender/blenlib/BLI_string_ref.hh
@@ -229,6 +229,16 @@ class StringRef : public StringRefBase {
   {
   }
 
+  /**
+   * Create a StringRef from a start and end pointer. This invokes undefined behavior when the
+   * second point points to a smaller address than the first one.
+   */
+  StringRef(const char *begin, const char *one_after_end)
+      : StringRefBase(begin, (uint)(one_after_end - begin))
+  {
+    BLI_assert(begin <= one_after_end);
+  }
+
   /**
    * Reference a std::string. Remember that when the std::string is destructed, the StringRef
    * will point to uninitialized memory.
diff --git a/tests/gtests/blenlib/BLI_string_ref_test.cc b/tests/gtests/blenlib/BLI_string_ref_test.cc
index 6823a79da06..5bb0c396288 100644
--- a/tests/gtests/blenlib/BLI_string_ref_test.cc
+++ b/tests/gtests/blenlib/BLI_string_ref_test.cc
@@ -36,6 +36,30 @@ TEST(string_ref, DefaultConstructor)
   EXPECT_EQ(ref.size(), 0);
 }
 
+TEST(string_ref, StartEndConstructor)
+{
+  const char *text = "hello world";
+  StringRef ref(text, text + 5);
+  EXPECT_EQ(ref.size(), 5);
+  EXPECT_TRUE(ref == "hello");
+  EXPECT_FALSE(ref == "hello ");
+}
+
+TEST(string_ref, StartEndConstructorNullptr)
+{
+  StringRef ref(nullptr, nullptr);
+  EXPECT_EQ(ref.size(), 0);
+  EXPECT_TRUE(ref == "");
+}
+
+TEST(string_ref, StartEndConstructorSame)
+{
+  const char *text = "hello world";
+  StringRef ref(text, text);
+  EXPECT_EQ(ref.size(), 0);
+  EXPECT_TRUE(ref == "");
+}
+
 TEST(string_ref, CStringConstructor)
 {
   const char *str = "Test";



More information about the Bf-blender-cvs mailing list