2 * Copyright notice from original mutt:
3 * Copyright (C) 1996-2000 Michael R. Elkins <me@mutt.org>
5 * This file is part of mutt-ng, see http://www.muttng.org/.
6 * It's licensed under the GNU General Public License,
7 * please see the file GPL in the top level source directory.
22 #define SOMEPRIME 149711
24 int hash_string (const unsigned char *s, int n)
34 h = (h * SOMEPRIME) % n;
35 h = (h >= 0) ? h : h + n;
41 HASH *hash_create (int nelem)
43 HASH *table = mem_malloc (sizeof (HASH));
49 table->table = mem_calloc (nelem, sizeof (struct hash_elem *));
53 HASH *hash_resize (HASH * ptr, int nelem)
56 struct hash_elem *elem, *tmp;
59 table = hash_create (nelem);
61 for (i = 0; i < ptr->nelem; i++) {
62 for (elem = ptr->table[i]; elem;) {
65 hash_insert (table, tmp->key, tmp->data, 1);
69 mem_free (&ptr->table);
75 /* table hash table to update
77 * data data to associate with `key'
78 * allow_dup if nonzero, duplicate keys are allowed in the table
80 int hash_insert (HASH * table, const char *key, void *data, int allow_dup)
82 struct hash_elem *ptr;
85 ptr = (struct hash_elem *) mem_malloc (sizeof (struct hash_elem));
86 h = hash_string ((unsigned char *) key, table->nelem);
91 ptr->next = table->table[h];
92 table->table[h] = ptr;
96 struct hash_elem *tmp, *last;
99 for (tmp = table->table[h], last = NULL; tmp; last = tmp, tmp = tmp->next) {
100 r = str_cmp (tmp->key, key);
111 table->table[h] = ptr;
118 void *hash_find_hash (const HASH * table, int hash, const char *key)
120 struct hash_elem *ptr = table->table[hash];
122 for (; ptr; ptr = ptr->next) {
123 if (str_cmp (key, ptr->key) == 0)
129 void hash_delete_hash (HASH * table, int hash, const char *key, const void *data,
130 void (*destroy) (void *))
132 struct hash_elem *ptr = table->table[hash];
133 struct hash_elem **last = &table->table[hash];
136 if ((data == ptr->data || !data) && str_cmp (ptr->key, key) == 0) {
150 /* ptr pointer to the hash table to be freed
151 * destroy() function to call to free the ->data member (optional)
153 void hash_destroy (HASH ** ptr, void (*destroy) (void *))
157 struct hash_elem *elem, *tmp;
159 for (i = 0; i < pptr->nelem; i++) {
160 for (elem = pptr->table[i]; elem;) {
168 mem_free (&pptr->table);
172 void hash_map (HASH* table, void (*mapfunc) (const char* key, void* data,
174 unsigned long more) {
176 struct hash_elem* elem = NULL;
178 if (!table || !mapfunc)
181 for (i = 0; i < table->nelem; i++)
182 for (elem = table->table[i]; elem; elem = elem->next)
183 mapfunc (elem->key, elem->data, more);