[Bf-blender-cvs] [a40bdbb5fcb] obj-import-experiments: convert stringref to float

Jacques Lucke noreply at git.blender.org
Sun Mar 22 16:17:38 CET 2020


Commit: a40bdbb5fcb20d4235d13d01828d966307416f84
Author: Jacques Lucke
Date:   Sun Mar 22 11:33:49 2020 +0100
Branches: obj-import-experiments
https://developer.blender.org/rBa40bdbb5fcb20d4235d13d01828d966307416f84

convert stringref to float

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

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

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

diff --git a/source/blender/blenlib/BLI_string_ref.h b/source/blender/blenlib/BLI_string_ref.h
index 94e2848c50e..e43b8d59035 100644
--- a/source/blender/blenlib/BLI_string_ref.h
+++ b/source/blender/blenlib/BLI_string_ref.h
@@ -119,6 +119,8 @@ class StringRefBase {
   StringRef lstrip(ArrayRef<char> chars = {' ', '\t', '\n', '\r'}) const;
   StringRef rstrip(ArrayRef<char> chars = {' ', '\t', '\n', '\r'}) const;
   StringRef strip(ArrayRef<char> chars = {' ', '\t', '\n', '\r'}) const;
+
+  float to_float(bool *r_success = nullptr) const;
 };
 
 /**
@@ -354,6 +356,18 @@ inline StringRef StringRefBase::strip(ArrayRef<char> chars) const
   return stripped;
 }
 
+inline float StringRefBase::to_float(bool *r_success) const
+{
+  char *str_with_null = (char *)alloca(m_size + 1);
+  this->copy_to__with_null(str_with_null);
+  char *end;
+  float value = std::strtof(str_with_null, &end);
+  if (r_success) {
+    *r_success = str_with_null != end;
+  }
+  return value;
+}
+
 }  // namespace BLI
 
 #endif /* __BLI_STRING_REF_H__ */
diff --git a/tests/gtests/blenlib/BLI_string_ref_test.cc b/tests/gtests/blenlib/BLI_string_ref_test.cc
index a9687650b06..a41fe569adb 100644
--- a/tests/gtests/blenlib/BLI_string_ref_test.cc
+++ b/tests/gtests/blenlib/BLI_string_ref_test.cc
@@ -305,3 +305,28 @@ TEST(string_ref_null, Strip)
   StringRefNull ref2 = ref1.lstrip();
   EXPECT_EQ(ref2, "test  ");
 }
+
+static void test_valid_float_conversion(StringRef str, float expected)
+{
+  bool success = false;
+  float value = str.to_float(&success);
+  EXPECT_TRUE(success);
+  EXPECT_EQ(value, expected);
+}
+
+static void test_invalid_float_conversion(StringRef str)
+{
+  bool success = true;
+  float value = str.to_float(&success);
+  EXPECT_FALSE(success);
+  EXPECT_EQ(value, 0.0f);
+}
+
+TEST(string_ref, ToFloat)
+{
+  test_valid_float_conversion("25", 25.0f);
+  test_valid_float_conversion("2e3", 2000.0f);
+  test_valid_float_conversion("12.25", 12.25f);
+  test_invalid_float_conversion("abc");
+  test_invalid_float_conversion("");
+}



More information about the Bf-blender-cvs mailing list