2 hash.c -- hash table management
3 Copyright (C) 2012 Guus Sliepen <guus@tinc-vpn.org>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25 /* Generic hash function */
27 static uint32_t hash_function(const void *p, size_t len) {
31 for(int i = len > 4 ? 4 : len; --i;)
32 hash += q[i] << (8 * i);
33 hash *= 0x9e370001UL; // Golden ratio prime.
39 /* Map 32 bits int onto 0..n-1, without throwing away too many bits if n is 2^8 or 2^16 */
41 static uint32_t modulo(uint32_t hash, size_t n) {
43 return (hash >> 24) ^ ((hash >> 16) & 0xff) ^ ((hash >> 8) & 0xff) ^ (hash & 0xff);
45 return (hash >> 16) ^ (hash & 0xffff);
52 hash_t *hash_alloc(size_t n, size_t size) {
53 hash_t *hash = xmalloc_and_zero(sizeof *hash);
56 hash->keys = xmalloc(hash->n * hash->size);
57 hash->values = xmalloc_and_zero(hash->n * sizeof *hash->values);
61 void hash_free(hash_t *hash) {
67 /* Searching and inserting */
69 void hash_insert(hash_t *hash, const void *key, const void *value) {
70 uint32_t i = modulo(hash_function(key, hash->size), hash->n);
71 memcpy(hash->keys + i * hash->size, key, hash->size);
72 hash->values[i] = value;
75 void *hash_search(const hash_t *hash, const void *key) {
76 uint32_t i = modulo(hash_function(key, hash->size), hash->n);
77 if(hash->values[i] && !memcmp(key, hash->keys + i * hash->size, hash->size)) {
78 return (void *)hash->values[i];
83 void *hash_search_or_insert(hash_t *hash, const void *key, const void *value) {
84 uint32_t i = modulo(hash_function(key, hash->size), hash->n);
85 if(hash->values[i] && !memcmp(key, hash->keys + i * hash->size, hash->size))
86 return (void *)hash->values[i];
87 memcpy(hash->keys + i * hash->size, key, hash->size);
88 hash->values[i] = value;
92 /* Utility functions */
94 void hash_clear(hash_t *hash) {
95 memset(hash->values, 0, hash->n * sizeof *hash->values);
98 void hash_resize(hash_t *hash, size_t n) {
99 hash->keys = xrealloc(hash->keys, n * hash->size);
100 hash->values = xrealloc(hash->values, n * sizeof *hash->values);
102 memset(hash->values + hash->n, 0, (n - hash->n) * sizeof *hash->values);