2 * Copyright (C) 1996-2009 Michael R. Elkins <me@mutt.org>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
30 #define SOMEPRIME 149711
32 static unsigned int hash_string (const unsigned char *s, unsigned int n)
38 h = (h * SOMEPRIME) % n;
43 static unsigned int hash_case_string (const unsigned char *s, unsigned int n)
48 h += (h << 7) + tolower (*s++);
49 h = (h * SOMEPRIME) % n;
54 HASH *hash_create (int nelem, int lower)
56 HASH *table = safe_malloc (sizeof (HASH));
60 table->table = safe_calloc (nelem, sizeof (struct hash_elem *));
63 table->hash_string = hash_case_string;
64 table->cmp_string = mutt_strcasecmp;
68 table->hash_string = hash_string;
69 table->cmp_string = mutt_strcmp;
74 /* table hash table to update
76 * data data to associate with `key'
77 * allow_dup if nonzero, duplicate keys are allowed in the table
79 int hash_insert (HASH * table, const char *key, void *data, int allow_dup)
81 struct hash_elem *ptr;
84 ptr = (struct hash_elem *) safe_malloc (sizeof (struct hash_elem));
85 h = table->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)
101 r = table->cmp_string (tmp->key, key);
113 table->table[h] = ptr;
119 void *hash_find_hash (const HASH * table, int hash, const char *key)
121 struct hash_elem *ptr = table->table[hash];
122 for (; ptr; ptr = ptr->next)
124 if (table->cmp_string (key, ptr->key) == 0)
130 void hash_delete_hash (HASH * table, int hash, const char *key, const void *data,
131 void (*destroy) (void *))
133 struct hash_elem *ptr = table->table[hash];
134 struct hash_elem **last = &table->table[hash];
138 if ((data == ptr->data || !data)
139 && table->cmp_string (ptr->key, key) == 0)
156 /* ptr pointer to the hash table to be freed
157 * destroy() function to call to free the ->data member (optional)
159 void hash_destroy (HASH **ptr, void (*destroy) (void *))
163 struct hash_elem *elem, *tmp;
165 for (i = 0 ; i < pptr->nelem; i++)
167 for (elem = pptr->table[i]; elem; )
177 FREE (ptr); /* __FREE_CHECKED__ */