editor: #undef O after use
[0verkill.git] / hash.c
blob133437a7855552f3f5791e327d9b632342d32ff4
1 /* HASHING TABLE */
3 #include <stdlib.h>
4 #include <string.h>
5 #include <stdio.h>
7 #include "hash.h"
8 #include "data.h"
9 #include "error.h"
11 struct table_type table[TABLE_SIZE];
14 /* hash function */
16 #define hash(id) (id&(TABLE_SIZE-1))
19 /* adds item to hash table */
20 void add_to_table(struct object_list *pointer)
22 int c;
23 unsigned int a;
24 a=hash(pointer->member.id);
25 c=table[a].count;
26 table[a].pointer=mem_realloc(table[a].pointer,(c+1)*sizeof(struct object *));
27 if (!table[a].pointer){ERROR("Not enough memory.\n");EXIT(1);}
29 table[a].pointer[c]=pointer;
30 table[a].count++;
34 /* removes object from table */
35 /* returns pointer to the object */
36 /* if there's not such an object returns null */
37 struct object_list * remove_from_table(unsigned int id)
39 unsigned int a;
40 int b;
41 struct object_list *p;
43 a=hash(id);
44 if (!table[a].count)return 0;
45 for (b=0;b<table[a].count;b++)
46 if (table[a].pointer[b]->member.id==id)
48 p=table[a].pointer[b];
49 memmove(table[a].pointer+b,table[a].pointer+b+1,(table[a].count-b-1)*sizeof(struct object_list *));
50 table[a].count--;
51 table[a].pointer=mem_realloc(table[a].pointer,table[a].count*sizeof(struct object_list*));
52 return p;
54 return 0;
58 /* tests if object number id is in table */
59 /* if true returns pointer, otherwise returns null */
60 struct object_list* find_in_table(unsigned int id)
62 unsigned int a;
63 int b;
65 a=hash(id);
66 if (!table[a].count)return 0;
67 for (b=0;b<table[a].count;b++)
68 if (table[a].pointer[b]->member.id==id) return table[a].pointer[b];
69 return 0;
73 /* initializes hash table */
74 void hash_table_init(void)
76 int a;
78 for (a=0;a<TABLE_SIZE;a++)
80 table[a].count=0;
81 table[a].pointer=DUMMY;
86 /* removes hash table from memory */
87 void free_hash_table(void)
89 int a,b;
91 for (a=0;a<TABLE_SIZE;a++)
93 for (b=0;b<table[a].count;b++)
94 mem_free(table[a].pointer[b]);
95 mem_free(table[a].pointer);