4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
22 * Copyright 2008 Sun Microsystems, Inc. All rights reserved.
23 * Use is subject to license terms.
28 #include <sys/nsctl/nsc_hash.h>
30 #define HASH_PRIME 2039
32 static int calc_hash(const char *);
39 hash
= (hash_node_t
**)calloc(HASH_PRIME
, sizeof (hash_node_t
*));
44 nsc_insert_node(hash_node_t
**hash
, void *data
, const char *key
)
49 node
= (hash_node_t
*)malloc(sizeof (hash_node_t
));
53 node
->key
= strdup(key
);
57 * possible enhancement would be to search
58 * in this index for a duplicate
60 index
= calc_hash(key
);
61 node
->next
= hash
[ index
];
71 * Searches the hash to find a node.
75 * pointer to node if found.
78 nsc_lookup(hash_node_t
**hash
, const char *key
)
83 index
= calc_hash(key
);
86 if (strcmp(node
->key
, key
) == 0)
94 nsc_remove_node(hash_node_t
**hash
, char *key
)
97 hash_node_t
*node
, *prev
;
100 index
= calc_hash(key
);
101 if (!hash
[ index
]) {
105 if (strcmp(hash
[ index
]->key
, key
) == 0) {
106 node
= hash
[ index
];
108 hash
[ index
] = hash
[ index
]->next
;
113 prev
= hash
[ index
];
115 while (node
&& (strcmp(node
->key
, key
) != 0)) {
120 /* did we find it? */
122 prev
->next
= node
->next
;
132 nsc_remove_all(hash_node_t
**hash
, void (*callback
)(void *))
135 hash_node_t
*p
, *next
;
137 for (i
= 0; i
< HASH_PRIME
; i
++) {
152 /* ---------------------------------------------------------------------- */
155 * Basic rotating hash, as per Knuth.
158 calc_hash(const char *key
)
160 unsigned int hash
, i
;
161 int len
= strlen(key
);
162 for (hash
= len
, i
= 0; i
< len
; i
++) {
163 hash
= (hash
<< 5) ^ (hash
>> 27) ^ key
[ i
];
165 return (hash
% HASH_PRIME
);