From 93879b1920722ac21d352efcb73f7a7f93070c7d Mon Sep 17 00:00:00 2001 From: Alyssa Rosenzweig Date: Thu, 7 Mar 2024 16:27:50 -0400 Subject: [PATCH] util/hash_table: add DERIVE macro MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit we typically use a hash table with a fixed struct key, but this requires tedious boilerplate. add a macro that generates all the boilerplate for you so you can just create a table and go. naming inspired by Rust #![derive]. Signed-off-by: Alyssa Rosenzweig Reviewed-by: Marek Olšák Reviewed-by: Boris Brezillon Part-of: --- src/util/hash_table.h | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/util/hash_table.h b/src/util/hash_table.h index 9bb9eb4de8c..2e6a50be3a7 100644 --- a/src/util/hash_table.h +++ b/src/util/hash_table.h @@ -162,6 +162,26 @@ hash_table_call_foreach(struct hash_table *ht, callback(entry->key, entry->data, closure); } +/** + * This helper macro generates the boilerplate required to use a hash table with + * a fixed-size struct as the key. + */ +#define DERIVE_HASH_TABLE(T) \ + static uint32_t T##_hash(const void *key) \ + { \ + return _mesa_hash_data(key, sizeof(struct T)); \ + } \ + \ + static bool T##_equal(const void *a, const void *b) \ + { \ + return memcmp(a, b, sizeof(struct T)) == 0; \ + } \ + \ + static struct hash_table *T##_table_create(void *memctx) \ + { \ + return _mesa_hash_table_create(memctx, T##_hash, T##_equal); \ + } + /** * Hash table wrapper which supports 64-bit keys. */