/*
hash.c -- hash table management
- Copyright (C) 2012 Guus Sliepen <guus@tinc-vpn.org>
+ Copyright (C) 2012-2013 Guus Sliepen <guus@tinc-vpn.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
static uint32_t hash_function(const void *p, size_t len) {
const uint8_t *q = p;
uint32_t hash = 0;
- while(len > 0) {
+ while(true) {
for(int i = len > 4 ? 4 : len; --i;)
- hash += q[i] << (8 * i);
+ hash += q[len - i] << (8 * i);
hash *= 0x9e370001UL; // Golden ratio prime.
+ if(len <= 4)
+ break;
len -= 4;
}
return hash;
/* (De)allocation */
hash_t *hash_alloc(size_t n, size_t size) {
- hash_t *hash = xmalloc_and_zero(sizeof *hash);
+ hash_t *hash = xzalloc(sizeof *hash);
hash->n = n;
hash->size = size;
- hash->keys = xmalloc(hash->n * hash->size);
- hash->values = xmalloc_and_zero(hash->n * sizeof *hash->values);
+ hash->keys = xzalloc(hash->n * hash->size);
+ hash->values = xzalloc(hash->n * sizeof *hash->values);
return 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)
+ 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);
+ }
}