[Bf-blender-cvs] [92c1d9044ca] functions: new StringRefNull class

Jacques Lucke noreply at git.blender.org
Wed May 15 11:43:08 CEST 2019


Commit: 92c1d9044ca654a7a149162222d946bac95e84db
Author: Jacques Lucke
Date:   Wed May 15 11:00:07 2019 +0200
Branches: functions
https://developer.blender.org/rB92c1d9044ca654a7a149162222d946bac95e84db

new StringRefNull class

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

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 69bfe3d0115..f8f5f9efe4e 100644
--- a/source/blender/blenlib/BLI_string_ref.hpp
+++ b/source/blender/blenlib/BLI_string_ref.hpp
@@ -1,6 +1,7 @@
 #pragma once
 
-/* Reference to a string that might NOT be null-terminated. */
+/* Two types of string references. One that guarantees null termination
+ * and one that does not. */
 
 #include <cstring>
 #include <string>
@@ -9,6 +10,46 @@
 
 namespace BLI {
 
+class StringRefNull {
+ public:
+  using size_type = size_t;
+
+ private:
+  const char *m_data;
+  size_type m_size;
+
+ public:
+  StringRefNull() : m_data(""), m_size(0)
+  {
+  }
+
+  StringRefNull(const char *str) : m_data(str), m_size(strlen(str))
+  {
+    BLI_assert(str != NULL);
+    BLI_assert(m_data[m_size] == '\0');
+  }
+
+  StringRefNull(const std::string &str) : StringRefNull(str.data())
+  {
+  }
+
+  size_type size() const
+  {
+    return m_size;
+  }
+
+  const char *data() const
+  {
+    return m_data;
+  }
+
+  char operator[](size_type index) const
+  {
+    BLI_assert(index <= m_size);
+    return m_data[index];
+  }
+};
+
 class StringRef {
  public:
   using size_type = size_t;
@@ -22,6 +63,10 @@ class StringRef {
   {
   }
 
+  StringRef(StringRefNull other) : m_data(other.data()), m_size(other.size())
+  {
+  }
+
   StringRef(const char *str) : m_data(str), m_size(str ? strlen(str) : 0)
   {
   }
diff --git a/tests/gtests/blenlib/BLI_string_ref_test.cc b/tests/gtests/blenlib/BLI_string_ref_test.cc
index 0f86a7233a8..5cff6adb7a4 100644
--- a/tests/gtests/blenlib/BLI_string_ref_test.cc
+++ b/tests/gtests/blenlib/BLI_string_ref_test.cc
@@ -2,6 +2,22 @@
 #include "BLI_string_ref.hpp"
 
 using BLI::StringRef;
+using BLI::StringRefNull;
+
+TEST(string_ref_null, DefaultConstructor)
+{
+  StringRefNull ref;
+  EXPECT_EQ(ref.size(), 0);
+  EXPECT_EQ(ref[0], '\0');
+}
+
+TEST(string_ref_null, CStringConstructor)
+{
+  const char *str = "Hello";
+  StringRefNull ref(str);
+  EXPECT_EQ(ref.size(), 5);
+  EXPECT_EQ(ref.data(), str);
+}
 
 TEST(string_ref, DefaultConstructor)
 {



More information about the Bf-blender-cvs mailing list