diff options
author | Jacques Lucke <jacques@blender.org> | 2020-06-10 15:47:16 +0300 |
---|---|---|
committer | Jacques Lucke <jacques@blender.org> | 2020-06-10 15:47:22 +0300 |
commit | a71f073dfb0277255ac63ab880fff1cf5cb3c699 (patch) | |
tree | 1c24a0f63fb6a9f0c61c4218ed4c1d9921b067b1 /source/blender | |
parent | 75ce20a00067e05eca575deb74fbf2b5c118c309 (diff) |
BLI: add Map.pop_try method
I found this pattern in depsgraph code more than once.
Diffstat (limited to 'source/blender')
-rw-r--r-- | source/blender/blenlib/BLI_map.hh | 34 |
1 files changed, 34 insertions, 0 deletions
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 { @@ -388,6 +389,23 @@ class Map { } /** + * 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<Value> 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<typename ForwardKey> Optional<Value> 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<typename ForwardKey> Optional<Value> 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> value = *slot.value(); + slot.remove(); + m_removed_slots++; + return value; + } + if (slot.is_empty()) { + return {}; + } + } + MAP_SLOT_PROBING_END(); + } + template<typename ForwardKey, typename CreateValueF, typename ModifyValueF> auto add_or_modify__impl(ForwardKey &&key, const CreateValueF &create_value, |