Home | History | Annotate | Line # | Download | only in make
hash.c revision 1.41
      1 /*	$NetBSD: hash.c,v 1.41 2020/10/04 18:16:09 rillig Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1988, 1989, 1990 The Regents of the University of California.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to Berkeley by
      8  * Adam de Boor.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  * 3. Neither the name of the University nor the names of its contributors
     19  *    may be used to endorse or promote products derived from this software
     20  *    without specific prior written permission.
     21  *
     22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     32  * SUCH DAMAGE.
     33  */
     34 
     35 /*
     36  * Copyright (c) 1988, 1989 by Adam de Boor
     37  * Copyright (c) 1989 by Berkeley Softworks
     38  * All rights reserved.
     39  *
     40  * This code is derived from software contributed to Berkeley by
     41  * Adam de Boor.
     42  *
     43  * Redistribution and use in source and binary forms, with or without
     44  * modification, are permitted provided that the following conditions
     45  * are met:
     46  * 1. Redistributions of source code must retain the above copyright
     47  *    notice, this list of conditions and the following disclaimer.
     48  * 2. Redistributions in binary form must reproduce the above copyright
     49  *    notice, this list of conditions and the following disclaimer in the
     50  *    documentation and/or other materials provided with the distribution.
     51  * 3. All advertising materials mentioning features or use of this software
     52  *    must display the following acknowledgement:
     53  *	This product includes software developed by the University of
     54  *	California, Berkeley and its contributors.
     55  * 4. Neither the name of the University nor the names of its contributors
     56  *    may be used to endorse or promote products derived from this software
     57  *    without specific prior written permission.
     58  *
     59  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     60  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     61  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     62  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     63  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     64  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     65  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     66  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     67  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     68  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     69  * SUCH DAMAGE.
     70  */
     71 
     72 /*
     73  * This module contains routines to manipulate a hash table.
     74  * See hash.h for a definition of the structure of the hash
     75  * table.  Hash tables grow automatically as the amount of
     76  * information increases.
     77  */
     78 
     79 #include "make.h"
     80 
     81 /*	"@(#)hash.c	8.1 (Berkeley) 6/6/93"	*/
     82 MAKE_RCSID("$NetBSD: hash.c,v 1.41 2020/10/04 18:16:09 rillig Exp $");
     83 
     84 /*
     85  * The ratio of # entries to # buckets at which we rebuild the table to
     86  * make it larger.
     87  */
     88 #define rebuildLimit 3
     89 
     90 /* This hash function matches Gosling's emacs. */
     91 static unsigned int
     92 hash(const char *key, size_t *out_keylen)
     93 {
     94 	unsigned h = 0;
     95 	const char *p = key;
     96 	while (*p != '\0')
     97 		h = (h << 5) - h + (unsigned char)*p++;
     98 	if (out_keylen != NULL)
     99 		*out_keylen = (size_t)(p - key);
    100 	return h;
    101 }
    102 
    103 static Hash_Entry *
    104 HashTable_Find(Hash_Table *t, unsigned int h, const char *key)
    105 {
    106 	Hash_Entry *e;
    107 	int chainlen = 0;
    108 
    109 #ifdef DEBUG_HASH_LOOKUP
    110 	DEBUG4(HASH, "%s: %p h=%x key=%s\n", __func__, t, h, key);
    111 #endif
    112 
    113 	for (e = t->buckets[h & t->bucketsMask]; e != NULL; e = e->next) {
    114 		chainlen++;
    115 		if (e->namehash == h && strcmp(e->name, key) == 0)
    116 			break;
    117 	}
    118 
    119 	if (chainlen > t->maxchain)
    120 		t->maxchain = chainlen;
    121 
    122 	return e;
    123 }
    124 
    125 /* Sets up the hash table. */
    126 void
    127 Hash_InitTable(Hash_Table *t)
    128 {
    129 	size_t n = 16, i;
    130 	struct Hash_Entry **hp;
    131 
    132 	t->numEntries = 0;
    133 	t->maxchain = 0;
    134 	t->bucketsSize = n;
    135 	t->bucketsMask = n - 1;
    136 	t->buckets = hp = bmake_malloc(sizeof(*hp) * n);
    137 	for (i = 0; i < n; i++)
    138 		hp[i] = NULL;
    139 }
    140 
    141 /* Removes everything from the hash table and frees up the memory space it
    142  * occupied (except for the space in the Hash_Table structure). */
    143 void
    144 Hash_DeleteTable(Hash_Table *t)
    145 {
    146 	struct Hash_Entry **hp, *h, *nexth = NULL;
    147 	int i;
    148 
    149 	for (hp = t->buckets, i = t->bucketsSize; --i >= 0;) {
    150 		for (h = *hp++; h != NULL; h = nexth) {
    151 			nexth = h->next;
    152 			free(h);
    153 		}
    154 	}
    155 	free(t->buckets);
    156 
    157 	/*
    158 	 * Set up the hash table to cause memory faults on any future access
    159 	 * attempts until re-initialization.
    160 	 */
    161 	t->buckets = NULL;
    162 }
    163 
    164 /* Searches the hash table for an entry corresponding to the key.
    165  *
    166  * Input:
    167  *	t		Hash table to search.
    168  *	key		A hash key.
    169  *
    170  * Results:
    171  *	Returns a pointer to the entry for key, or NULL if the table contains
    172  *	no entry for the key.
    173  */
    174 Hash_Entry *
    175 Hash_FindEntry(Hash_Table *t, const char *key)
    176 {
    177 	unsigned int h = hash(key, NULL);
    178 	return HashTable_Find(t, h, key);
    179 }
    180 
    181 void *
    182 Hash_FindValue(Hash_Table *t, const char *key)
    183 {
    184 	Hash_Entry *he = Hash_FindEntry(t, key);
    185 	return he != NULL ? he->value : NULL;
    186 }
    187 
    188 /* Makes a new hash table that is larger than the old one. The entire hash
    189  * table is moved, so any bucket numbers from the old table become invalid. */
    190 static void
    191 RebuildTable(Hash_Table *t)
    192 {
    193 	Hash_Entry *e, *next = NULL, **hp, **xp;
    194 	int i, mask;
    195 	Hash_Entry **oldhp;
    196 	int oldsize;
    197 
    198 	oldhp = t->buckets;
    199 	oldsize = i = t->bucketsSize;
    200 	i <<= 1;
    201 	t->bucketsSize = i;
    202 	t->bucketsMask = mask = i - 1;
    203 	t->buckets = hp = bmake_malloc(sizeof(*hp) * i);
    204 	while (--i >= 0)
    205 		*hp++ = NULL;
    206 	for (hp = oldhp, i = oldsize; --i >= 0;) {
    207 		for (e = *hp++; e != NULL; e = next) {
    208 			next = e->next;
    209 			xp = &t->buckets[e->namehash & mask];
    210 			e->next = *xp;
    211 			*xp = e;
    212 		}
    213 	}
    214 	free(oldhp);
    215 	DEBUG5(HASH, "%s: %p size=%d entries=%d maxchain=%d\n",
    216 	       __func__, t, t->bucketsSize, t->numEntries, t->maxchain);
    217 	t->maxchain = 0;
    218 }
    219 
    220 /* Searches the hash table for an entry corresponding to the key.
    221  * If no entry is found, then one is created.
    222  *
    223  * Input:
    224  *	t		Hash table to search.
    225  *	key		A hash key.
    226  *	newPtr		Filled with TRUE if new entry created,
    227  *			FALSE otherwise.
    228  */
    229 Hash_Entry *
    230 Hash_CreateEntry(Hash_Table *t, const char *key, Boolean *newPtr)
    231 {
    232 	Hash_Entry *e;
    233 	unsigned h;
    234 	size_t keylen;
    235 	struct Hash_Entry **hp;
    236 
    237 	h = hash(key, &keylen);
    238 	e = HashTable_Find(t, h, key);
    239 	if (e) {
    240 		if (newPtr != NULL)
    241 			*newPtr = FALSE;
    242 		return e;
    243 	}
    244 
    245 	/*
    246 	 * The desired entry isn't there.  Before allocating a new entry,
    247 	 * expand the table if necessary (and this changes the resulting
    248 	 * bucket chain).
    249 	 */
    250 	if (t->numEntries >= rebuildLimit * t->bucketsSize)
    251 		RebuildTable(t);
    252 
    253 	e = bmake_malloc(sizeof(*e) + keylen);
    254 	hp = &t->buckets[h & t->bucketsMask];
    255 	e->next = *hp;
    256 	*hp = e;
    257 	Hash_SetValue(e, NULL);
    258 	e->namehash = h;
    259 	memcpy(e->name, key, keylen + 1);
    260 	t->numEntries++;
    261 
    262 	if (newPtr != NULL)
    263 		*newPtr = TRUE;
    264 	return e;
    265 }
    266 
    267 /* Delete the given hash table entry and free memory associated with it. */
    268 void
    269 Hash_DeleteEntry(Hash_Table *t, Hash_Entry *e)
    270 {
    271 	Hash_Entry **hp, *p;
    272 
    273 	for (hp = &t->buckets[e->namehash & t->bucketsMask];
    274 	     (p = *hp) != NULL; hp = &p->next) {
    275 		if (p == e) {
    276 			*hp = p->next;
    277 			free(p);
    278 			t->numEntries--;
    279 			return;
    280 		}
    281 	}
    282 	abort();
    283 }
    284 
    285 /* Sets things up for enumerating all entries in the hash table.
    286  *
    287  * Input:
    288  *	t		Table to be searched.
    289  *	searchPtr	Area in which to keep state about search.
    290  *
    291  * Results:
    292  *	The return value is the address of the first entry in
    293  *	the hash table, or NULL if the table is empty.
    294  */
    295 Hash_Entry *
    296 Hash_EnumFirst(Hash_Table *t, Hash_Search *searchPtr)
    297 {
    298 	searchPtr->table = t;
    299 	searchPtr->nextBucket = 0;
    300 	searchPtr->entry = NULL;
    301 	return Hash_EnumNext(searchPtr);
    302 }
    303 
    304 /* Returns the next entry in the hash table, or NULL if the end of the table
    305  * is reached.
    306  *
    307  * Input:
    308  *	searchPtr	Area used to keep state about search.
    309  */
    310 Hash_Entry *
    311 Hash_EnumNext(Hash_Search *searchPtr)
    312 {
    313 	Hash_Entry *e;
    314 	Hash_Table *t = searchPtr->table;
    315 
    316 	/*
    317 	 * The entry field points to the most recently returned
    318 	 * entry, or is NULL if we are starting up.  If not NULL, we have
    319 	 * to start at the next one in the chain.
    320 	 */
    321 	e = searchPtr->entry;
    322 	if (e != NULL)
    323 		e = e->next;
    324 	/*
    325 	 * If the chain ran out, or if we are starting up, we need to
    326 	 * find the next nonempty chain.
    327 	 */
    328 	while (e == NULL) {
    329 		if (searchPtr->nextBucket >= t->bucketsSize)
    330 			return NULL;
    331 		e = t->buckets[searchPtr->nextBucket++];
    332 	}
    333 	searchPtr->entry = e;
    334 	return e;
    335 }
    336 
    337 void
    338 Hash_ForEach(Hash_Table *t, void (*action)(void *, void *), void *data)
    339 {
    340 	Hash_Search search;
    341 	Hash_Entry *e;
    342 
    343 	for (e = Hash_EnumFirst(t, &search);
    344 	     e != NULL;
    345 	     e = Hash_EnumNext(&search))
    346 		action(Hash_GetValue(e), data);
    347 }
    348 
    349 void
    350 Hash_DebugStats(Hash_Table *t, const char *name)
    351 {
    352 	DEBUG4(HASH, "Hash_Table %s: size=%d numEntries=%d maxchain=%d\n",
    353 	       name, t->bucketsSize, t->numEntries, t->maxchain);
    354 }
    355