From a71f073dfb0277255ac63ab880fff1cf5cb3c699 Mon Sep 17 00:00:00 2001 From: Jacques Lucke Date: Wed, 10 Jun 2020 14:47:16 +0200 Subject: BLI: add Map.pop_try method I found this pattern in depsgraph code more than once. --- source/blender/blenlib/BLI_map.hh | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) (limited to 'source/blender/blenlib/BLI_map.hh') diff --git a/source/blender/blenlib/BLI_map.hh b/source/blender/blenlib/BLI_map.hh index 5819430fe97..82415dd5726 100644 --- a/source/blender/blenlib/BLI_map.hh +++ b/source/blender/blenlib/BLI_map.hh @@ -73,6 +73,7 @@ #include "BLI_hash.hh" #include "BLI_hash_tables.hh" #include "BLI_map_slots.hh" +#include "BLI_optional.hh" #include "BLI_probing_strategies.hh" namespace blender { @@ -387,6 +388,23 @@ class Map { return this->pop__impl(key, m_hash(key)); } + /** + * Get the value that is stored for the given key and remove it from the map. If the key is not + * in the map, a value-less optional is returned. + */ + Optional pop_try(const Key &key) + { + return this->pop_try_as(key); + } + + /** + * Same as `pop_try`, but accepts other key types that are supported by the hash function. + */ + template Optional pop_try_as(const ForwardKey &key) + { + return this->pop_try__impl(key, m_hash(key)); + } + /** * This method can be used to implement more complex custom behavior without having to do * multiple lookups @@ -1029,6 +1047,22 @@ class Map { MAP_SLOT_PROBING_END(); } + template Optional pop_try__impl(const ForwardKey &key, uint32_t hash) + { + MAP_SLOT_PROBING_BEGIN (hash, slot) { + if (slot.contains(key, m_is_equal, hash)) { + Optional value = *slot.value(); + slot.remove(); + m_removed_slots++; + return value; + } + if (slot.is_empty()) { + return {}; + } + } + MAP_SLOT_PROBING_END(); + } + template auto add_or_modify__impl(ForwardKey &&key, const CreateValueF &create_value, -- cgit v1.2.3