xref: /illumos-gate/usr/src/cmd/sgs/crle/common/hash.c (revision 9c72db81a69bf1ea2a220c7cfc40eb0ef089be8c)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright (c) 2000 by Sun Microsystems, Inc.
24  * All rights reserved.
25  */
26 
27 #include	<stdio.h>
28 #include	<stdlib.h>
29 #include	<string.h>
30 #include	<libelf.h>
31 #include	"_crle.h"
32 
33 Hash_tbl *
34 make_hash(int size, Hash_type type, ulong_t ident)
35 {
36 	Hash_tbl *	tbl;
37 
38 	if ((tbl = malloc(sizeof (Hash_tbl))) == 0)
39 		return (0);
40 
41 	if ((tbl->t_entry = calloc((unsigned)(sizeof (Hash_ent *)), size)) == 0)
42 		return (0);
43 
44 	tbl->t_ident = ident;
45 	tbl->t_type = type;
46 	tbl->t_size = size;
47 
48 	return (tbl);
49 }
50 
51 
52 Hash_ent *
53 get_hash(Hash_tbl * tbl, Addr key, Half id, int mode)
54 {
55 	int		bucket;
56 	Hash_ent *	ent;
57 	Word		hashval;
58 
59 	if (tbl->t_type == HASH_STR)
60 		hashval = elf_hash((const char *)key);
61 	else
62 		hashval = key;
63 
64 	bucket = hashval % tbl->t_size;
65 
66 	if (mode & HASH_FND_ENT) {
67 		for (ent = tbl->t_entry[bucket]; ent != NULL;
68 		    ent = ent->e_next) {
69 			if (tbl->t_type == HASH_STR) {
70 				if ((strcmp((const char *)ent->e_key,
71 				    (const char *)key) == 0) && ((id == 0) ||
72 				    (id == ent->e_id)))
73 					return (ent);
74 			} else {
75 				if (ent->e_key == key)
76 					return (ent);
77 			}
78 		}
79 	}
80 	if (!(mode & HASH_ADD_ENT))
81 		return (0);
82 
83 	/*
84 	 * Key not found in this hash table ... insert new entry into bucket.
85 	 */
86 	if ((ent = calloc(sizeof (Hash_ent), 1)) == 0)
87 		return (0);
88 
89 	ent->e_key = key;
90 	ent->e_hash = hashval;
91 
92 	/*
93 	 * Hook into bucket chain
94 	 */
95 	ent->e_next = tbl->t_entry[bucket];
96 	tbl->t_entry[bucket] = ent;
97 
98 	return (ent);
99 }
100