1/*	$NetBSD: hash.c,v 1.19 2009/01/24 10:59:09 dsl 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#ifndef MAKE_NATIVE
73static char rcsid[] = "$NetBSD: hash.c,v 1.19 2009/01/24 10:59:09 dsl Exp $";
74#else
75#include <sys/cdefs.h>
76#ifndef lint
77#if 0
78static char sccsid[] = "@(#)hash.c	8.1 (Berkeley) 6/6/93";
79#else
80__RCSID("$NetBSD: hash.c,v 1.19 2009/01/24 10:59:09 dsl Exp $");
81#endif
82#endif /* not lint */
83#endif
84
85/* hash.c --
86 *
87 * 	This module contains routines to manipulate a hash table.
88 * 	See hash.h for a definition of the structure of the hash
89 * 	table.  Hash tables grow automatically as the amount of
90 * 	information increases.
91 */
92#include "sprite.h"
93#include "make.h"
94#include "hash.h"
95
96/*
97 * Forward references to local procedures that are used before they're
98 * defined:
99 */
100
101static void RebuildTable(Hash_Table *);
102
103/*
104 * The following defines the ratio of # entries to # buckets
105 * at which we rebuild the table to make it larger.
106 */
107
108#define rebuildLimit 3
109
110/*
111 *---------------------------------------------------------
112 *
113 * Hash_InitTable --
114 *
115 *	This routine just sets up the hash table.
116 *
117 * Input:
118 *	t		Structure to to hold table.
119 *	numBuckets	How many buckets to create for starters. This
120 *			number is rounded up to a power of two.   If
121 *			<= 0, a reasonable default is chosen. The
122 *			table will grow in size later as needed.
123 *
124 * Results:
125 *	None.
126 *
127 * Side Effects:
128 *	Memory is allocated for the initial bucket area.
129 *
130 *---------------------------------------------------------
131 */
132
133void
134Hash_InitTable(Hash_Table *t, int numBuckets)
135{
136	int i;
137	struct Hash_Entry **hp;
138
139	/*
140	 * Round up the size to a power of two.
141	 */
142	if (numBuckets <= 0)
143		i = 16;
144	else {
145		for (i = 2; i < numBuckets; i <<= 1)
146			 continue;
147	}
148	t->numEntries = 0;
149	t->size = i;
150	t->mask = i - 1;
151	t->bucketPtr = hp = bmake_malloc(sizeof(*hp) * i);
152	while (--i >= 0)
153		*hp++ = NULL;
154}
155
156/*
157 *---------------------------------------------------------
158 *
159 * Hash_DeleteTable --
160 *
161 *	This routine removes everything from a hash table
162 *	and frees up the memory space it occupied (except for
163 *	the space in the Hash_Table structure).
164 *
165 * Results:
166 *	None.
167 *
168 * Side Effects:
169 *	Lots of memory is freed up.
170 *
171 *---------------------------------------------------------
172 */
173
174void
175Hash_DeleteTable(Hash_Table *t)
176{
177	struct Hash_Entry **hp, *h, *nexth = NULL;
178	int i;
179
180	for (hp = t->bucketPtr, i = t->size; --i >= 0;) {
181		for (h = *hp++; h != NULL; h = nexth) {
182			nexth = h->next;
183			free(h);
184		}
185	}
186	free(t->bucketPtr);
187
188	/*
189	 * Set up the hash table to cause memory faults on any future access
190	 * attempts until re-initialization.
191	 */
192	t->bucketPtr = NULL;
193}
194
195/*
196 *---------------------------------------------------------
197 *
198 * Hash_FindEntry --
199 *
200 * 	Searches a hash table for an entry corresponding to key.
201 *
202 * Input:
203 *	t		Hash table to search.
204 *	key		A hash key.
205 *
206 * Results:
207 *	The return value is a pointer to the entry for key,
208 *	if key was present in the table.  If key was not
209 *	present, NULL is returned.
210 *
211 * Side Effects:
212 *	None.
213 *
214 *---------------------------------------------------------
215 */
216
217Hash_Entry *
218Hash_FindEntry(Hash_Table *t, const char *key)
219{
220	Hash_Entry *e;
221	unsigned h;
222	const char *p;
223
224	for (h = 0, p = key; *p;)
225		h = (h << 5) - h + *p++;
226	p = key;
227	for (e = t->bucketPtr[h & t->mask]; e != NULL; e = e->next)
228		if (e->namehash == h && strcmp(e->name, p) == 0)
229			return (e);
230	return NULL;
231}
232
233/*
234 *---------------------------------------------------------
235 *
236 * Hash_CreateEntry --
237 *
238 *	Searches a hash table for an entry corresponding to
239 *	key.  If no entry is found, then one is created.
240 *
241 * Input:
242 *	t		Hash table to search.
243 *	key		A hash key.
244 *	newPtr		Filled in with TRUE if new entry created,
245 *			FALSE otherwise.
246 *
247 * Results:
248 *	The return value is a pointer to the entry.  If *newPtr
249 *	isn't NULL, then *newPtr is filled in with TRUE if a
250 *	new entry was created, and FALSE if an entry already existed
251 *	with the given key.
252 *
253 * Side Effects:
254 *	Memory may be allocated, and the hash buckets may be modified.
255 *---------------------------------------------------------
256 */
257
258Hash_Entry *
259Hash_CreateEntry(Hash_Table *t, const char *key, Boolean *newPtr)
260{
261	Hash_Entry *e;
262	unsigned h;
263	const char *p;
264	int keylen;
265	struct Hash_Entry **hp;
266
267	/*
268	 * Hash the key.  As a side effect, save the length (strlen) of the
269	 * key in case we need to create the entry.
270	 */
271	for (h = 0, p = key; *p;)
272		h = (h << 5) - h + *p++;
273	keylen = p - key;
274	p = key;
275	for (e = t->bucketPtr[h & t->mask]; e != NULL; e = e->next) {
276		if (e->namehash == h && strcmp(e->name, p) == 0) {
277			if (newPtr != NULL)
278				*newPtr = FALSE;
279			return (e);
280		}
281	}
282
283	/*
284	 * The desired entry isn't there.  Before allocating a new entry,
285	 * expand the table if necessary (and this changes the resulting
286	 * bucket chain).
287	 */
288	if (t->numEntries >= rebuildLimit * t->size)
289		RebuildTable(t);
290	e = bmake_malloc(sizeof(*e) + keylen);
291	hp = &t->bucketPtr[h & t->mask];
292	e->next = *hp;
293	*hp = e;
294	Hash_SetValue(e, NULL);
295	e->namehash = h;
296	(void)strcpy(e->name, p);
297	t->numEntries++;
298
299	if (newPtr != NULL)
300		*newPtr = TRUE;
301	return (e);
302}
303
304/*
305 *---------------------------------------------------------
306 *
307 * Hash_DeleteEntry --
308 *
309 * 	Delete the given hash table entry and free memory associated with
310 *	it.
311 *
312 * Results:
313 *	None.
314 *
315 * Side Effects:
316 *	Hash chain that entry lives in is modified and memory is freed.
317 *
318 *---------------------------------------------------------
319 */
320
321void
322Hash_DeleteEntry(Hash_Table *t, Hash_Entry *e)
323{
324	Hash_Entry **hp, *p;
325
326	if (e == NULL)
327		return;
328	for (hp = &t->bucketPtr[e->namehash & t->mask];
329	     (p = *hp) != NULL; hp = &p->next) {
330		if (p == e) {
331			*hp = p->next;
332			free(p);
333			t->numEntries--;
334			return;
335		}
336	}
337	(void)write(2, "bad call to Hash_DeleteEntry\n", 29);
338	abort();
339}
340
341/*
342 *---------------------------------------------------------
343 *
344 * Hash_EnumFirst --
345 *	This procedure sets things up for a complete search
346 *	of all entries recorded in the hash table.
347 *
348 * Input:
349 *	t		Table to be searched.
350 *	searchPtr	Area in which to keep state about search.
351 *
352 * Results:
353 *	The return value is the address of the first entry in
354 *	the hash table, or NULL if the table is empty.
355 *
356 * Side Effects:
357 *	The information in searchPtr is initialized so that successive
358 *	calls to Hash_Next will return successive HashEntry's
359 *	from the table.
360 *
361 *---------------------------------------------------------
362 */
363
364Hash_Entry *
365Hash_EnumFirst(Hash_Table *t, Hash_Search *searchPtr)
366{
367	searchPtr->tablePtr = t;
368	searchPtr->nextIndex = 0;
369	searchPtr->hashEntryPtr = NULL;
370	return Hash_EnumNext(searchPtr);
371}
372
373/*
374 *---------------------------------------------------------
375 *
376 * Hash_EnumNext --
377 *    This procedure returns successive entries in the hash table.
378 *
379 * Input:
380 *	searchPtr	Area used to keep state about search.
381 *
382 * Results:
383 *    The return value is a pointer to the next HashEntry
384 *    in the table, or NULL when the end of the table is
385 *    reached.
386 *
387 * Side Effects:
388 *    The information in searchPtr is modified to advance to the
389 *    next entry.
390 *
391 *---------------------------------------------------------
392 */
393
394Hash_Entry *
395Hash_EnumNext(Hash_Search *searchPtr)
396{
397	Hash_Entry *e;
398	Hash_Table *t = searchPtr->tablePtr;
399
400	/*
401	 * The hashEntryPtr field points to the most recently returned
402	 * entry, or is nil if we are starting up.  If not nil, we have
403	 * to start at the next one in the chain.
404	 */
405	e = searchPtr->hashEntryPtr;
406	if (e != NULL)
407		e = e->next;
408	/*
409	 * If the chain ran out, or if we are starting up, we need to
410	 * find the next nonempty chain.
411	 */
412	while (e == NULL) {
413		if (searchPtr->nextIndex >= t->size)
414			return NULL;
415		e = t->bucketPtr[searchPtr->nextIndex++];
416	}
417	searchPtr->hashEntryPtr = e;
418	return (e);
419}
420
421/*
422 *---------------------------------------------------------
423 *
424 * RebuildTable --
425 *	This local routine makes a new hash table that
426 *	is larger than the old one.
427 *
428 * Results:
429 * 	None.
430 *
431 * Side Effects:
432 *	The entire hash table is moved, so any bucket numbers
433 *	from the old table are invalid.
434 *
435 *---------------------------------------------------------
436 */
437
438static void
439RebuildTable(Hash_Table *t)
440{
441	Hash_Entry *e, *next = NULL, **hp, **xp;
442	int i, mask;
443        Hash_Entry **oldhp;
444	int oldsize;
445
446	oldhp = t->bucketPtr;
447	oldsize = i = t->size;
448	i <<= 1;
449	t->size = i;
450	t->mask = mask = i - 1;
451	t->bucketPtr = hp = bmake_malloc(sizeof(*hp) * i);
452	while (--i >= 0)
453		*hp++ = NULL;
454	for (hp = oldhp, i = oldsize; --i >= 0;) {
455		for (e = *hp++; e != NULL; e = next) {
456			next = e->next;
457			xp = &t->bucketPtr[e->namehash & mask];
458			e->next = *xp;
459			*xp = e;
460		}
461	}
462	free(oldhp);
463}
464