2 * Copyright (c) 2013 Larisa Grigore<larisagrigore@gmail.com>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 #include "sysvipc_hash.h"
34 _hash_init(int nr_elems)
37 struct hashtable *hashtable;
42 for (hashsize = 2; hashsize < nr_elems; hashsize <<= 1)
45 hashtable = malloc(sizeof(struct hashtable));
50 hashtable->entries = malloc(hashsize * sizeof(struct entries_list));
51 if (!hashtable->entries) {
57 hashtable->nr_elems = hashsize;
59 for (i = 0; i < hashsize; i++)
60 LIST_INIT(&hashtable->entries[i]);
67 _hash_destroy(struct hashtable *hashtable)
69 struct entries_list *tmp;
70 u_long hashmask = hashtable->nr_elems -1;
72 for (tmp = &hashtable->entries[0]; tmp <= &hashtable->entries[hashmask]; tmp++) {
76 free(hashtable->entries);
83 _hash_insert(struct hashtable *hashtable, u_long key, void *value)
86 u_long hashmask = hashtable->nr_elems -1;
87 struct entries_list *list =
88 &hashtable->entries[key & hashmask];
89 struct hashentry *new_entry = malloc(sizeof(struct hashentry));
90 new_entry->value = value;
92 LIST_INSERT_HEAD(list, new_entry, entry_link);
96 _hash_lookup(struct hashtable *hashtable, u_long key)
99 u_long hashmask = hashtable->nr_elems -1;
100 struct entries_list *list =
101 &hashtable->entries[key & hashmask];
102 struct hashentry *tmp;
104 LIST_FOREACH(tmp, list, entry_link) {
105 if (tmp->key == key) {
114 _hash_remove(struct hashtable *hashtable, u_long key)
118 u_long hashmask = hashtable->nr_elems -1;
119 struct entries_list *list =
120 &hashtable->entries[key & hashmask];
121 struct hashentry *tmp;
123 LIST_FOREACH(tmp, list, entry_link) {
131 LIST_REMOVE(tmp, entry_link);
138 get_hash_size(int nr_elems)
142 for (hashsize = 2; hashsize < nr_elems; hashsize <<= 1)