From 474b2889339e24e602a7498c30ed07e2c47e6982 Mon Sep 17 00:00:00 2001 From: Jacques Lucke Date: Wed, 10 Jun 2020 19:02:28 +0200 Subject: BLI: add Map.pop_default method There is a nice use case for this in depsgraph code. Also I added some previously missing calls to std::move. --- source/blender/blenlib/BLI_map.hh | 43 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 41 insertions(+), 2 deletions(-) (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 13f1a967d65..9737367ebca 100644 --- a/source/blender/blenlib/BLI_map.hh +++ b/source/blender/blenlib/BLI_map.hh @@ -405,6 +405,28 @@ class Map { return this->pop_try__impl(key, m_hash(key)); } + /** + * Get the value that corresponds to the given key and remove it from the map. If the key is not + * in the map, return the given default value instead. + */ + Value pop_default(const Key &key, const Value &default_value) + { + return this->pop_default_as(key, default_value); + } + Value pop_default(const Key &key, Value &&default_value) + { + return this->pop_default_as(key, std::move(default_value)); + } + + /** + * Same as `pop_default`, but accepts other key types that are supported by the hash function. + */ + template + Value pop_default_as(const ForwardKey &key, ForwardValue &&default_value) + { + return this->pop_default__impl(key, std::forward(default_value), m_hash(key)); + } + /** * This method can be used to implement more complex custom behavior without having to do * multiple lookups @@ -1039,7 +1061,7 @@ class Map { MAP_SLOT_PROBING_BEGIN (hash, slot) { if (slot.contains(key, m_is_equal, hash)) { - Value value = *slot.value(); + Value value = std::move(*slot.value()); slot.remove(); return value; } @@ -1051,7 +1073,7 @@ class Map { { MAP_SLOT_PROBING_BEGIN (hash, slot) { if (slot.contains(key, m_is_equal, hash)) { - Optional value = *slot.value(); + Optional value = std::move(*slot.value()); slot.remove(); m_removed_slots++; return value; @@ -1063,6 +1085,23 @@ class Map { MAP_SLOT_PROBING_END(); } + template + Value pop_default__impl(const ForwardKey &key, ForwardValue &&default_value, uint32_t hash) + { + MAP_SLOT_PROBING_BEGIN (hash, slot) { + if (slot.contains(key, m_is_equal, hash)) { + Value value = std::move(*slot.value()); + slot.remove(); + m_removed_slots++; + return value; + } + if (slot.is_empty()) { + return std::forward(default_value); + } + } + MAP_SLOT_PROBING_END(); + } + template auto add_or_modify__impl(ForwardKey &&key, const CreateValueF &create_value, -- cgit v1.2.3