From 028092a84345815d2d574e4334bbf4d20b58f8f5 Mon Sep 17 00:00:00 2001 From: Ben Clayton Date: Tue, 29 Nov 2022 20:01:42 +0000 Subject: [PATCH] tint/utils: Add Hashmap::Keys(), Hashmap::Values() Change-Id: If51cb3f42e50db842ecd006bcfbbbd060957e650 Reviewed-on: https://dawn-review.googlesource.com/c/dawn/+/112281 Commit-Queue: Ben Clayton Reviewed-by: Antonio Maiorano Kokoro: Ben Clayton --- src/tint/utils/hashmap.h | 24 ++++++++++++++++++++++++ src/tint/utils/hashmap_test.cc | 11 +++++++++++ 2 files changed, 35 insertions(+) diff --git a/src/tint/utils/hashmap.h b/src/tint/utils/hashmap.h index 19a5abebc8..a37eab928b 100644 --- a/src/tint/utils/hashmap.h +++ b/src/tint/utils/hashmap.h @@ -182,6 +182,30 @@ class Hashmap : public HashmapBase { /// @returns a reference to the entry that is equal to the given value. ConstReference Find(const Key& key) const { return ConstReference(*this, key); } + /// @returns the keys of the map as a vector. + /// @note the order of the returned vector is non-deterministic between compilers. + template + Vector Keys() const { + Vector out; + out.Reserve(this->Count()); + for (auto it : *this) { + out.Push(it.key); + } + return out; + } + + /// @returns the values of the map as a vector + /// @note the order of the returned vector is non-deterministic between compilers. + template + Vector Values() const { + Vector out; + out.Reserve(this->Count()); + for (auto it : *this) { + out.Push(it.value); + } + return out; + } + private: Value* Lookup(const Key& key) { if (auto [found, index] = this->IndexOf(key); found) { diff --git a/src/tint/utils/hashmap_test.cc b/src/tint/utils/hashmap_test.cc index 62269673d5..3991eb2b72 100644 --- a/src/tint/utils/hashmap_test.cc +++ b/src/tint/utils/hashmap_test.cc @@ -182,6 +182,17 @@ TEST(Hashmap, MutableIterator) { Entry{3, "three!"}, Entry{4, "four!"})); } +TEST(Hashmap, KeysValues) { + using Map = Hashmap; + Map map; + map.Add(1, "one"); + map.Add(4, "four"); + map.Add(3, "three"); + map.Add(2, "two"); + EXPECT_THAT(map.Keys(), testing::UnorderedElementsAre(1, 2, 3, 4)); + EXPECT_THAT(map.Values(), testing::UnorderedElementsAre("one", "two", "three", "four")); +} + TEST(Hashmap, AddMany) { Hashmap map; for (size_t i = 0; i < kPrimes.size(); i++) {