1 //
2 // nazghul - an old-school RPG engine
3 // Copyright (C) 2002, 2003 Gordon McNutt
4 //
5 // This program is free software; you can redistribute it and/or modify it
6 // under the terms of the GNU General Public License as published by the Free
7 // Software Foundation; either version 2 of the License, or (at your option)
8 // any later version.
9 //
10 // This program is distributed in the hope that it will be useful, but WITHOUT
11 // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 // FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
13 // more details.
14 //
15 // You should have received a copy of the GNU General Public License along with
16 // this program; if not, write to the Free Foundation, Inc., 59 Temple Place,
17 // Suite 330, Boston, MA 02111-1307 USA
18 //
19 // Gordon McNutt
20 // gmcnutt@users.sourceforge.net
21 //
22 #include "hash.h"
23 #include "olist.h"
24 #include "common.h"
25 
hash_create(int n)26 struct hash *hash_create(int n)
27 {
28 	struct hash *hash;
29 	int i;
30 
31 	CREATE(hash, struct hash, 0);
32 	hash->n = n;
33 	hash->buckets = (struct olist *) malloc(n * sizeof(struct olist));
34 	if (!hash->buckets) {
35 		hash_destroy(hash);
36 		return 0;
37 	}
38 	for (i = 0; i < n; i++) {
39 		list_init(&hash->buckets[i].list);
40 	}
41 	return hash;
42 }
43 
hash_destroy(struct hash * hash)44 void hash_destroy(struct hash *hash)
45 {
46 	if (hash->buckets)
47 		free(hash->buckets);
48 	free(hash);
49 }
50 
hash_add(struct hash * hash,struct olist * val)51 void hash_add(struct hash *hash, struct olist *val)
52 {
53 	struct olist *b = &hash->buckets[val->key % hash->n];
54 	olist_add(b, val);
55 }
56 
hash_lookup(struct hash * hash,int key)57 struct olist *hash_lookup(struct hash *hash, int key)
58 {
59 	struct olist *b = &hash->buckets[key % hash->n];
60 	return olist_lookup(b, key, 1);
61 }
62