Merge pull request #940 from qlyoung/hashtable-expansion-lf

lib: use load factor as hash expansion trigger
This commit is contained in:
David Lamparter 2017-08-09 20:43:40 +02:00 committed by GitHub
commit 2c3699c0eb
2 changed files with 4 additions and 6 deletions

View File

@ -141,18 +141,15 @@ void *hash_get(struct hash *hash, void *data, void *(*alloc_func)(void *))
unsigned int key; unsigned int key;
unsigned int index; unsigned int index;
void *newdata; void *newdata;
unsigned int len;
struct hash_backet *backet; struct hash_backet *backet;
key = (*hash->hash_key)(data); key = (*hash->hash_key)(data);
index = key & (hash->size - 1); index = key & (hash->size - 1);
len = 0;
for (backet = hash->index[index]; backet != NULL; for (backet = hash->index[index]; backet != NULL;
backet = backet->next) { backet = backet->next) {
if (backet->key == key && (*hash->hash_cmp)(backet->data, data)) if (backet->key == key && (*hash->hash_cmp)(backet->data, data))
return backet->data; return backet->data;
++len;
} }
if (alloc_func) { if (alloc_func) {
@ -160,7 +157,7 @@ void *hash_get(struct hash *hash, void *data, void *(*alloc_func)(void *))
if (newdata == NULL) if (newdata == NULL)
return NULL; return NULL;
if (len > HASH_THRESHOLD) { if (HASH_THRESHOLD(hash->count + 1, hash->size)) {
hash_expand(hash); hash_expand(hash);
index = key & (hash->size - 1); index = key & (hash->size - 1);
} }

View File

@ -28,8 +28,9 @@ DECLARE_MTYPE(HASH)
DECLARE_MTYPE(HASH_BACKET) DECLARE_MTYPE(HASH_BACKET)
/* Default hash table size. */ /* Default hash table size. */
#define HASH_INITIAL_SIZE 256 /* initial number of backets. */ #define HASH_INITIAL_SIZE 256
#define HASH_THRESHOLD 10 /* expand when backet. */ /* Expansion threshold */
#define HASH_THRESHOLD(used, size) ((used) > (size))
#define HASHWALK_CONTINUE 0 #define HASHWALK_CONTINUE 0
#define HASHWALK_ABORT -1 #define HASHWALK_ABORT -1