From 7bbf9dc04144247aa8fd862b5fafc3e691a80264 Mon Sep 17 00:00:00 2001 From: greg Date: Fri, 7 Aug 2020 12:58:43 -0400 Subject: [PATCH] issue #60: add non-const if_contains() which can update the mapped_value. --- parallel_hashmap/phmap.h | 15 +++++++++++++++ tests/parallel_hash_map_test.cc | 15 ++++++++++----- 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/parallel_hashmap/phmap.h b/parallel_hashmap/phmap.h index f1b7996..cd98170 100644 --- a/parallel_hashmap/phmap.h +++ b/parallel_hashmap/phmap.h @@ -3431,12 +3431,27 @@ public: #endif typename Lockable::SharedLock m; auto it = const_cast(this)->find(key, this->hash(key), m); + if (it == this->end()) + return false; + std::forward(f)((const mapped_type&)Policy::value(&*it)); + return true; + } + + template + bool if_contains(const key_arg& key, F&& f) { +#if __cplusplus >= 201703L + static_assert(std::is_invocable::value); +#endif + typename Lockable::UniqueLock m; + auto it = this->find(key, this->hash(key), m); if (it == this->end()) return false; std::forward(f)(Policy::value(&*it)); return true; } + + template MappedReference

operator[](key_arg&& key) { return Policy::value(&*try_emplace(std::forward(key)).first); diff --git a/tests/parallel_hash_map_test.cc b/tests/parallel_hash_map_test.cc index fcac843..662a949 100644 --- a/tests/parallel_hash_map_test.cc +++ b/tests/parallel_hash_map_test.cc @@ -13,13 +13,18 @@ TEST(THIS_TEST_NAME, ThreadSafeContains) { // We can't test mutable keys, or non-copyable keys with ThisMap. // Test that the nodes have the proper API. ThisMap m = { {1, 7}, {2, 9} }; - auto val = 0; - - auto func = [&val](int& v) { val = v; }; - EXPECT_TRUE(m.if_contains(2, func)); + const ThisMap& const_m(m); + + auto val = 0; + auto get_value = [&val](const int& v) { val = v; }; + EXPECT_TRUE(const_m.if_contains(2, get_value)); EXPECT_EQ(val, 9); - EXPECT_FALSE(m.if_contains(3, func)); + EXPECT_FALSE(m.if_contains(3, get_value)); + + auto set_value = [&val](int& v) { v = 11; }; + EXPECT_TRUE(m.if_contains(2, set_value)); + EXPECT_EQ(m[2], 11); } } // namespace