From d288eeb79abc08d09f535bfd5d64b623d26bd129 Mon Sep 17 00:00:00 2001 From: Jacques Lucke Date: Thu, 13 May 2021 13:39:23 +0200 Subject: BLI: support looking up a key stored in Map or VectorSet Sometimes it is useful to find the key that compares equal to a known key. Typically that happens when the key itself has additional data attached that is not part of its hash. Note that the returned key reference/pointer is const, because the caller must not change the key in a way that changes its hash or how it compares to other keys. --- source/blender/blenlib/BLI_map.hh | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 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 95afbfc2ec6..4d254960f34 100644 --- a/source/blender/blenlib/BLI_map.hh +++ b/source/blender/blenlib/BLI_map.hh @@ -604,6 +604,37 @@ class Map { return this->lookup_or_add_cb_as(std::forward(key), []() { return Value(); }); } + /** + * Returns the key that is stored in the set that compares equal to the given key. This invokes + * undefined behavior when the key is not in the map. + */ + const Key &lookup_key(const Key &key) const + { + return this->lookup_key_as(key); + } + template const Key &lookup_key_as(const ForwardKey &key) const + { + const Slot &slot = this->lookup_slot(key, hash_(key)); + return *slot.key(); + } + + /** + * Returns a pointer to the key that is stored in the map that compares equal to the given key. + * If the key is not in the map, null is returned. + */ + const Key *lookup_key_ptr(const Key &key) const + { + return this->lookup_key_ptr_as(key); + } + template const Key *lookup_key_ptr_as(const ForwardKey &key) const + { + const Slot *slot = this->lookup_slot_ptr(key, hash_(key)); + if (slot == nullptr) { + return nullptr; + } + return slot->key(); + } + /** * Calls the provided callback for every key-value-pair in the map. The callback is expected * to take a `const Key &` as first and a `const Value &` as second parameter. -- cgit v1.2.3