X-Git-Url: http://git.meshlink.io/?p=meshlink;a=blobdiff_plain;f=src%2Fhash.c;h=a7964428830abefa4f0254a251f3bd7594357e80;hp=5d90e55c68fdf7d44d0343fc28c4d5709bfef955;hb=963c5055505f2fc117cd5efa06eaa02c9b2bf85d;hpb=76c7550c8ab0e9c0ee14a9c396baa008cfb9bc42 diff --git a/src/hash.c b/src/hash.c index 5d90e55c..a7964428 100644 --- a/src/hash.c +++ b/src/hash.c @@ -27,26 +27,34 @@ static uint32_t hash_function(const void *p, size_t len) { const uint8_t *q = p; uint32_t hash = 0; + while(true) { - for(int i = len > 4 ? 4 : len; --i;) + for(int i = len > 4 ? 4 : len; --i;) { hash += q[len - i] << (8 * i); + } + hash *= 0x9e370001UL; // Golden ratio prime. - if(len <= 4) + + if(len <= 4) { break; + } + len -= 4; } + return hash; } /* Map 32 bits int onto 0..n-1, without throwing away too many bits if n is 2^8 or 2^16 */ static uint32_t modulo(uint32_t hash, size_t n) { - if(n == 0x100) + if(n == 0x100) { return (hash >> 24) ^ ((hash >> 16) & 0xff) ^ ((hash >> 8) & 0xff) ^ (hash & 0xff); - else if(n == 0x10000) + } else if(n == 0x10000) { return (hash >> 16) ^ (hash & 0xffff); - else + } else { return hash % n; + } } /* (De)allocation */ @@ -76,15 +84,21 @@ void hash_insert(hash_t *hash, const void *key, const void *value) { void *hash_search(const hash_t *hash, const void *key) { uint32_t i = modulo(hash_function(key, hash->size), hash->n); - if(hash->values[i] && !memcmp(key, hash->keys + i * hash->size, hash->size)) + + if(hash->values[i] && !memcmp(key, hash->keys + i * hash->size, hash->size)) { return (void *)hash->values[i]; + } + return NULL; } void *hash_search_or_insert(hash_t *hash, const void *key, const void *value) { uint32_t i = modulo(hash_function(key, hash->size), hash->n); - if(hash->values[i] && !memcmp(key, hash->keys + i * hash->size, hash->size)) + + if(hash->values[i] && !memcmp(key, hash->keys + i * hash->size, hash->size)) { return (void *)hash->values[i]; + } + memcpy(hash->keys + i * hash->size, key, hash->size); hash->values[i] = value; return NULL; @@ -99,6 +113,7 @@ void hash_clear(hash_t *hash) { void hash_resize(hash_t *hash, size_t n) { hash->keys = xrealloc(hash->keys, n * hash->size); hash->values = xrealloc(hash->values, n * sizeof(*hash->values)); + if(n > hash->n) { memset(hash->keys + hash->n * hash->size, 0, (n - hash->n) * hash->size); memset(hash->values + hash->n, 0, (n - hash->n) * sizeof(*hash->values));