[Bf-blender-cvs] [00b4b903618] functions: new try_lookup method for StringMap

Jacques Lucke noreply at git.blender.org
Thu Nov 21 15:19:43 CET 2019


Commit: 00b4b9036182df34cdcb0bb492d9e1d4d2e3048c
Author: Jacques Lucke
Date:   Wed Nov 20 18:11:12 2019 +0100
Branches: functions
https://developer.blender.org/rB00b4b9036182df34cdcb0bb492d9e1d4d2e3048c

new try_lookup method for StringMap

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

M	source/blender/blenlib/BLI_optional.h
M	source/blender/blenlib/BLI_string_map.h
M	tests/gtests/blenlib/BLI_string_map_test.cc

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

diff --git a/source/blender/blenlib/BLI_optional.h b/source/blender/blenlib/BLI_optional.h
index 47ea9d2803f..6ffff38cc0d 100644
--- a/source/blender/blenlib/BLI_optional.h
+++ b/source/blender/blenlib/BLI_optional.h
@@ -35,7 +35,7 @@ template<typename T> class Optional {
   bool m_set;
 
  public:
-  static Optional FromPointer(T *ptr)
+  static Optional FromPointer(const T *ptr)
   {
     if (ptr == nullptr) {
       return Optional();
@@ -54,7 +54,7 @@ template<typename T> class Optional {
     this->reset();
   }
 
-  Optional(T &value) : Optional()
+  Optional(const T &value) : Optional()
   {
     this->set(value);
   }
diff --git a/source/blender/blenlib/BLI_string_map.h b/source/blender/blenlib/BLI_string_map.h
index 15762207c12..8d146771123 100644
--- a/source/blender/blenlib/BLI_string_map.h
+++ b/source/blender/blenlib/BLI_string_map.h
@@ -30,6 +30,7 @@
 #include "BLI_map.h"
 #include "BLI_string_ref.h"
 #include "BLI_vector.h"
+#include "BLI_optional.h"
 
 namespace BLI {
 
@@ -263,6 +264,11 @@ template<typename T, typename Allocator = GuardedAllocator> class StringMap {
     return const_cast<T *>(const_cast<const StringMap *>(this)->lookup_ptr(key));
   }
 
+  Optional<T> try_lookup(StringRef key) const
+  {
+    return Optional<T>::FromPointer(this->lookup_ptr(key));
+  }
+
   /**
    * Get a copy of the value corresponding to the key. If the key does not exist, return the
    * default value.
diff --git a/tests/gtests/blenlib/BLI_string_map_test.cc b/tests/gtests/blenlib/BLI_string_map_test.cc
index cc02a54e0c8..59620dd2799 100644
--- a/tests/gtests/blenlib/BLI_string_map_test.cc
+++ b/tests/gtests/blenlib/BLI_string_map_test.cc
@@ -128,6 +128,15 @@ TEST(string_map, LookupDefault)
   EXPECT_EQ(map.lookup_default("test", 42), 5);
 }
 
+TEST(string_map, TryLookup)
+{
+  StringMap<int> map;
+  map.add_new("test", 4);
+  EXPECT_TRUE(map.try_lookup("test").has_value());
+  EXPECT_FALSE(map.try_lookup("value").has_value());
+  EXPECT_EQ(map.try_lookup("test").value(), 4);
+}
+
 TEST(string_map, FindKeyForValue)
 {
   StringMap<int> map;



More information about the Bf-blender-cvs mailing list