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.
18 #include <lib-lib/mem.h>
24 #define SOMEPRIME 149711
26 int hash_string (const unsigned char *s, int n)
36 h = (h * SOMEPRIME) % n;
37 h = (h >= 0) ? h : h + n;
43 HASH *hash_create (int nelem)
45 HASH *table = p_new(HASH, 1);
51 table->table = mem_calloc (nelem, sizeof (struct hash_elem *));
55 HASH *hash_resize(HASH *ptr, int nelem)
58 struct hash_elem *elem, *tmp;
61 table = hash_create (nelem);
63 for (i = 0; i < ptr->nelem; i++) {
64 for (elem = ptr->table[i]; elem;) {
67 hash_insert (table, tmp->key, tmp->data, 1);
71 p_delete(&ptr->table);
77 /* table hash table to update
79 * data data to associate with `key'
80 * allow_dup if nonzero, duplicate keys are allowed in the table
82 int hash_insert (HASH * table, const char *key, void *data, int allow_dup)
84 struct hash_elem *ptr;
87 ptr = p_new(struct hash_elem, 1);
88 h = hash_string ((unsigned char *) key, table->nelem);
93 ptr->next = table->table[h];
94 table->table[h] = ptr;
98 struct hash_elem *tmp, *last;
101 for (tmp = table->table[h], last = NULL; tmp; last = tmp, tmp = tmp->next) {
102 r = str_cmp (tmp->key, key);
113 table->table[h] = ptr;
120 void *hash_find_hash (const HASH * table, int hash, const char *key)
122 struct hash_elem *ptr = table->table[hash];
124 for (; ptr; ptr = ptr->next) {
125 if (str_cmp (key, ptr->key) == 0)
131 void hash_delete_hash (HASH * table, int hash, const char *key, const void *data,
132 void (*destroy) (void *))
134 struct hash_elem *ptr = table->table[hash];
135 struct hash_elem **last = &table->table[hash];
138 if ((data == ptr->data || !data) && str_cmp (ptr->key, key) == 0) {
152 /* ptr pointer to the hash table to be freed
153 * destroy() function to call to free the ->data member (optional)
155 void hash_destroy (HASH ** ptr, void (*destroy) (void *))
159 struct hash_elem *elem, *tmp;
161 for (i = 0; i < pptr->nelem; i++) {
162 for (elem = pptr->table[i]; elem;) {
170 p_delete(&pptr->table);
174 void hash_map (HASH* table, void (*mapfunc) (const char* key, void* data,
176 unsigned long more) {
178 struct hash_elem* elem = NULL;
180 if (!table || !mapfunc)
183 for (i = 0; i < table->nelem; i++)
184 for (elem = table->table[i]; elem; elem = elem->next)
185 mapfunc (elem->key, elem->data, more);