From: Holger Schemel Date: Thu, 22 Feb 2024 21:51:45 +0000 (+0100) Subject: added function to check if hash table value exists for a given key X-Git-Tag: 4.4.0.0-test-1~317 X-Git-Url: https://git.artsoft.org/?a=commitdiff_plain;h=afba55b62615e9b162159c0f7b0df602f27f69a7;hp=e1342541fd884143a3d43a5cc7a44de99aa7c715;p=rocksndiamonds.git added function to check if hash table value exists for a given key This function is required if integer values are used directly as hash values, because a value of "0" would be indistinguishable from a non-existent entry, which is returned as "NULL". --- diff --git a/src/libgame/hash.c b/src/libgame/hash.c index 101ec121..89c7134f 100644 --- a/src/libgame/hash.c +++ b/src/libgame/hash.c @@ -268,6 +268,29 @@ hashtable_change(struct hashtable *h, void *k, void *v) return 0; } +/*****************************************************************************/ +int /* checks if key exists */ +hashtable_exists(struct hashtable *h, void *k) +{ + struct entry *e; + unsigned int hashvalue, index; + + hashvalue = hash(h, k); + index = indexFor(h->tablelength, hashvalue); + e = h->table[index]; + + while (e != NULL) + { + /* Check hash value to short circuit heavier comparison */ + if ((hashvalue == e->h) && (h->eqfn(k, e->k))) + return 1; + + e = e->next; + } + + return 0; +} + /*****************************************************************************/ void * /* returns value associated with key */ hashtable_search(struct hashtable *h, void *k) diff --git a/src/libgame/hash.h b/src/libgame/hash.h index 8d0eff23..8fe6f7fa 100644 --- a/src/libgame/hash.h +++ b/src/libgame/hash.h @@ -196,6 +196,24 @@ static int fnname (struct hashtable *h, keytype *k, valuetype *v) \ return hashtable_change(h, k, v); \ } +/***************************************************************************** + * hashtable_exists + + * @name hashtable_exists + * @param h the hashtable to search + * @param k the key to search for + * @return non-zero if key exists, else zero + */ + +int +hashtable_exists(struct hashtable *h, void *k); + +#define DEFINE_HASHTABLE_EXISTS(fnname, keytype, valuetype) \ +static int fnname (struct hashtable *h, keytype *k) \ +{ \ + return hashtable_exists(h, k); \ +} + /***************************************************************************** * hashtable_search