From 6dc60bf49d2c43c701c6f578711d91e51dacb9cf Mon Sep 17 00:00:00 2001 From: Thomas Voss Date: Sat, 24 Dec 2022 02:43:41 +0100 Subject: Add the FOREACH and FOREACH_SAFE macros --- src/gehashmap.h | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) (limited to 'src/gehashmap.h') diff --git a/src/gehashmap.h b/src/gehashmap.h index 311c2c3..1f24943 100644 --- a/src/gehashmap.h +++ b/src/gehashmap.h @@ -11,6 +11,38 @@ #define GEHASHMAP_INITIAL_SIZE 16 #define GEHASHMAP_LOAD_FACTOR 0.75 +/* The GEHASHMAP_FOREACH() macro takes 2 arguments. The first argument “entry” + * is a “struct n##_entry *”. This variable will be set to point to the next + * hashmap entry each iteration. The second argument “map” is a pointer to the + * hashmap to iterate over. + * + * This macro is unsafe to use when modifying the hashmap inplace (i.e. when + * calling n##_remove() in the loop). + */ +#define GEHASHMAP_FOREACH(entry, map) \ + for (size_t _gehashmap_i = 0; \ + _gehashmap_i < (map)->capacity; \ + (_gehashmap_i)++) \ + for ((entry) = (map)->entries[_gehashmap_i]; \ + (entry) != NULL; \ + (entry) = (entry)->next) + +/* The GEHASHMAP_FOREACH_SAFE() macro is identical to the GEHASHMAP_FOREACH() + * macro except it takes an additional “tmp” argument. This argument is of the + * same type as “entry” (a “struct n##_entry *”) and shouldn’t be interacted + * with by the library user. This macro allows you to modify the hashmap + * inplace while iterating. + */ +#define GEHASHMAP_FOREACH_SAFE(entry, tmp, map) \ + for (size_t _gehashmap_i = 0; \ + _gehashmap_i < (map)->capacity; \ + (_gehashmap_i)++) \ + for ((entry) = (map)->entries[_gehashmap_i], \ + (tmp) = (entry) ? (entry)->next : NULL; \ + (entry) != NULL; \ + (entry) = (tmp), \ + (tmp) = (entry) ? (entry)->next : NULL) + #define GEHASHMAP_API(k, v, n) \ struct n##_entry { \ k key; \ -- cgit v1.2.3