1/*	$FreeBSD$	*/
2/*	$NetBSD: hash.c,v 1.1.1.1 1999/11/19 04:30:56 mrg Exp $	*/
3
4/*-
5 * SPDX-License-Identifier: BSD-4-Clause
6 *
7 * Copyright (c) 1988, 1989, 1990 The Regents of the University of California.
8 * Copyright (c) 1988, 1989 by Adam de Boor
9 * Copyright (c) 1989 by Berkeley Softworks
10 * All rights reserved.
11 *
12 * This code is derived from software contributed to Berkeley by
13 * Adam de Boor.
14 *
15 * Redistribution and use in source and binary forms, with or without
16 * modification, are permitted provided that the following conditions
17 * are met:
18 * 1. Redistributions of source code must retain the above copyright
19 *    notice, this list of conditions and the following disclaimer.
20 * 2. Redistributions in binary form must reproduce the above copyright
21 *    notice, this list of conditions and the following disclaimer in the
22 *    documentation and/or other materials provided with the distribution.
23 * 3. All advertising materials mentioning features or use of this software
24 *    must display the following acknowledgement:
25 *	This product includes software developed by the University of
26 *	California, Berkeley and its contributors.
27 * 4. Neither the name of the University nor the names of its contributors
28 *    may be used to endorse or promote products derived from this software
29 *    without specific prior written permission.
30 *
31 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
32 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
33 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
34 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
35 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
36 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
37 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
38 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
39 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
40 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
41 * SUCH DAMAGE.
42 */
43
44#ifdef MAKE_BOOTSTRAP
45static char rcsid[] = "$NetBSD: hash.c,v 1.1.1.1 1999/11/19 04:30:56 mrg Exp $";
46#else
47#include <sys/cdefs.h>
48#ifndef lint
49#if 0
50static char sccsid[] = "@(#)hash.c	8.1 (Berkeley) 6/6/93";
51#else
52__RCSID("$NetBSD: hash.c,v 1.1.1.1 1999/11/19 04:30:56 mrg Exp $");
53#endif
54#endif /* not lint */
55#endif
56
57#include <sys/types.h>
58
59#include <stdlib.h>
60#include <string.h>
61#include <unistd.h>
62
63/* hash.c --
64 *
65 * 	This module contains routines to manipulate a hash table.
66 * 	See hash.h for a definition of the structure of the hash
67 * 	table.  Hash tables grow automatically as the amount of
68 * 	information increases.
69 */
70#include "sprite.h"
71#ifndef ORDER
72#include "make.h"
73#endif /* ORDER */
74#include "hash.h"
75#include "ealloc.h"
76
77/*
78 * Forward references to local procedures that are used before they're
79 * defined:
80 */
81
82static void RebuildTable(Hash_Table *);
83
84/*
85 * The following defines the ratio of # entries to # buckets
86 * at which we rebuild the table to make it larger.
87 */
88
89#define rebuildLimit 8
90
91/*
92 *---------------------------------------------------------
93 *
94 * Hash_InitTable --
95 *
96 *	This routine just sets up the hash table.
97 *
98 * Results:
99 *	None.
100 *
101 * Side Effects:
102 *	Memory is allocated for the initial bucket area.
103 *
104 *---------------------------------------------------------
105 */
106
107void
108Hash_InitTable(
109	register Hash_Table *t,	/* Structure to use to hold table. */
110	int numBuckets)		/* How many buckets to create for starters.
111				 * This number is rounded up to a power of
112				 * two.   If <= 0, a reasonable default is
113				 * chosen. The table will grow in size later
114				 * as needed. */
115{
116	register int i;
117	register struct Hash_Entry **hp;
118
119	/*
120	 * Round up the size to a power of two.
121	 */
122	if (numBuckets <= 0)
123		i = 16;
124	else {
125		for (i = 2; i < numBuckets; i <<= 1)
126			 continue;
127	}
128	t->numEntries = 0;
129	t->size = i;
130	t->mask = i - 1;
131	t->bucketPtr = hp = (struct Hash_Entry **)emalloc(sizeof(*hp) * i);
132	while (--i >= 0)
133		*hp++ = NULL;
134}
135
136/*
137 *---------------------------------------------------------
138 *
139 * Hash_DeleteTable --
140 *
141 *	This routine removes everything from a hash table
142 *	and frees up the memory space it occupied (except for
143 *	the space in the Hash_Table structure).
144 *
145 * Results:
146 *	None.
147 *
148 * Side Effects:
149 *	Lots of memory is freed up.
150 *
151 *---------------------------------------------------------
152 */
153
154void
155Hash_DeleteTable(Hash_Table *t)
156{
157	register struct Hash_Entry **hp, *h, *nexth = NULL;
158	register int i;
159
160	for (hp = t->bucketPtr, i = t->size; --i >= 0;) {
161		for (h = *hp++; h != NULL; h = nexth) {
162			nexth = h->next;
163			free((char *)h);
164		}
165	}
166	free((char *)t->bucketPtr);
167
168	/*
169	 * Set up the hash table to cause memory faults on any future access
170	 * attempts until re-initialization.
171	 */
172	t->bucketPtr = NULL;
173}
174
175/*
176 *---------------------------------------------------------
177 *
178 * Hash_FindEntry --
179 *
180 * 	Searches a hash table for an entry corresponding to key.
181 *
182 * Results:
183 *	The return value is a pointer to the entry for key,
184 *	if key was present in the table.  If key was not
185 *	present, NULL is returned.
186 *
187 * Side Effects:
188 *	None.
189 *
190 *---------------------------------------------------------
191 */
192
193Hash_Entry *
194Hash_FindEntry(
195	Hash_Table *t,		/* Hash table to search. */
196	char *key)		/* A hash key. */
197{
198	register Hash_Entry *e;
199	register unsigned h;
200	register char *p;
201
202	for (h = 0, p = key; *p;)
203		h = (h << 5) - h + *p++;
204	p = key;
205	for (e = t->bucketPtr[h & t->mask]; e != NULL; e = e->next)
206		if (e->namehash == h && strcmp(e->name, p) == 0)
207			return (e);
208	return (NULL);
209}
210
211/*
212 *---------------------------------------------------------
213 *
214 * Hash_CreateEntry --
215 *
216 *	Searches a hash table for an entry corresponding to
217 *	key.  If no entry is found, then one is created.
218 *
219 * Results:
220 *	The return value is a pointer to the entry.  If *newPtr
221 *	isn't NULL, then *newPtr is filled in with TRUE if a
222 *	new entry was created, and FALSE if an entry already existed
223 *	with the given key.
224 *
225 * Side Effects:
226 *	Memory may be allocated, and the hash buckets may be modified.
227 *---------------------------------------------------------
228 */
229
230Hash_Entry *
231Hash_CreateEntry(
232	register Hash_Table *t,	/* Hash table to search. */
233	char *key,		/* A hash key. */
234	Boolean *newPtr)	/* Filled in with TRUE if new entry created,
235				 * FALSE otherwise. */
236{
237	register Hash_Entry *e;
238	register unsigned h;
239	register char *p;
240	int keylen;
241	struct Hash_Entry **hp;
242
243	/*
244	 * Hash the key.  As a side effect, save the length (strlen) of the
245	 * key in case we need to create the entry.
246	 */
247	for (h = 0, p = key; *p;)
248		h = (h << 5) - h + *p++;
249	keylen = p - key;
250	p = key;
251	for (e = t->bucketPtr[h & t->mask]; e != NULL; e = e->next) {
252		if (e->namehash == h && strcmp(e->name, p) == 0) {
253			if (newPtr != NULL)
254				*newPtr = FALSE;
255			return (e);
256		}
257	}
258
259	/*
260	 * The desired entry isn't there.  Before allocating a new entry,
261	 * expand the table if necessary (and this changes the resulting
262	 * bucket chain).
263	 */
264	if (t->numEntries >= rebuildLimit * t->size)
265		RebuildTable(t);
266	e = (Hash_Entry *) emalloc(sizeof(*e) + keylen);
267	hp = &t->bucketPtr[h & t->mask];
268	e->next = *hp;
269	*hp = e;
270	e->clientData = NULL;
271	e->namehash = h;
272	(void) strcpy(e->name, p);
273	t->numEntries++;
274
275	if (newPtr != NULL)
276		*newPtr = TRUE;
277	return (e);
278}
279
280/*
281 *---------------------------------------------------------
282 *
283 * Hash_DeleteEntry --
284 *
285 * 	Delete the given hash table entry and free memory associated with
286 *	it.
287 *
288 * Results:
289 *	None.
290 *
291 * Side Effects:
292 *	Hash chain that entry lives in is modified and memory is freed.
293 *
294 *---------------------------------------------------------
295 */
296
297void
298Hash_DeleteEntry(Hash_Table *t, Hash_Entry *e)
299{
300	register Hash_Entry **hp, *p;
301
302	if (e == NULL)
303		return;
304	for (hp = &t->bucketPtr[e->namehash & t->mask];
305	     (p = *hp) != NULL; hp = &p->next) {
306		if (p == e) {
307			*hp = p->next;
308			free((char *)p);
309			t->numEntries--;
310			return;
311		}
312	}
313	(void)write(2, "bad call to Hash_DeleteEntry\n", 29);
314	abort();
315}
316
317/*
318 *---------------------------------------------------------
319 *
320 * Hash_EnumFirst --
321 *	This procedure sets things up for a complete search
322 *	of all entries recorded in the hash table.
323 *
324 * Results:
325 *	The return value is the address of the first entry in
326 *	the hash table, or NULL if the table is empty.
327 *
328 * Side Effects:
329 *	The information in searchPtr is initialized so that successive
330 *	calls to Hash_Next will return successive HashEntry's
331 *	from the table.
332 *
333 *---------------------------------------------------------
334 */
335
336Hash_Entry *
337Hash_EnumFirst(
338	Hash_Table *t,			/* Table to be searched. */
339	register Hash_Search *searchPtr)/* Area in which to keep state
340					 * about search.*/
341{
342	searchPtr->tablePtr = t;
343	searchPtr->nextIndex = 0;
344	searchPtr->hashEntryPtr = NULL;
345	return Hash_EnumNext(searchPtr);
346}
347
348/*
349 *---------------------------------------------------------
350 *
351 * Hash_EnumNext --
352 *    This procedure returns successive entries in the hash table.
353 *
354 * Results:
355 *    The return value is a pointer to the next HashEntry
356 *    in the table, or NULL when the end of the table is
357 *    reached.
358 *
359 * Side Effects:
360 *    The information in searchPtr is modified to advance to the
361 *    next entry.
362 *
363 *---------------------------------------------------------
364 */
365
366Hash_Entry *
367Hash_EnumNext(
368	register Hash_Search *searchPtr) /* Area used to keep state about
369					    search. */
370{
371	register Hash_Entry *e;
372	Hash_Table *t = searchPtr->tablePtr;
373
374	/*
375	 * The hashEntryPtr field points to the most recently returned
376	 * entry, or is nil if we are starting up.  If not nil, we have
377	 * to start at the next one in the chain.
378	 */
379	e = searchPtr->hashEntryPtr;
380	if (e != NULL)
381		e = e->next;
382	/*
383	 * If the chain ran out, or if we are starting up, we need to
384	 * find the next nonempty chain.
385	 */
386	while (e == NULL) {
387		if (searchPtr->nextIndex >= t->size)
388			return (NULL);
389		e = t->bucketPtr[searchPtr->nextIndex++];
390	}
391	searchPtr->hashEntryPtr = e;
392	return (e);
393}
394
395/*
396 *---------------------------------------------------------
397 *
398 * RebuildTable --
399 *	This local routine makes a new hash table that
400 *	is larger than the old one.
401 *
402 * Results:
403 * 	None.
404 *
405 * Side Effects:
406 *	The entire hash table is moved, so any bucket numbers
407 *	from the old table are invalid.
408 *
409 *---------------------------------------------------------
410 */
411
412static void
413RebuildTable(register Hash_Table *t)
414{
415	register Hash_Entry *e, *next = NULL, **hp, **xp;
416	register int i, mask;
417        register Hash_Entry **oldhp;
418	int oldsize;
419
420	oldhp = t->bucketPtr;
421	oldsize = i = t->size;
422	i <<= 1;
423	t->size = i;
424	t->mask = mask = i - 1;
425	t->bucketPtr = hp = (struct Hash_Entry **) emalloc(sizeof(*hp) * i);
426	while (--i >= 0)
427		*hp++ = NULL;
428	for (hp = oldhp, i = oldsize; --i >= 0;) {
429		for (e = *hp++; e != NULL; e = next) {
430			next = e->next;
431			xp = &t->bucketPtr[e->namehash & mask];
432			e->next = *xp;
433			*xp = e;
434		}
435	}
436	free((char *)oldhp);
437}
438