3 #include "chise-name.h"
5 struct CHISE_HASH_TABLE_ENTRY
11 struct CHISE_HASH_TABLE
14 CHISE_HASH_TABLE_ENTRY *data;
17 CHISE_HASH_TABLE* chise_make_hash_table (size_t size);
18 void chise_destroy_hash_table (CHISE_HASH_TABLE* hash);
19 int chise_hash_c_string (const unsigned char *ptr);
22 chise_make_hash_table (size_t size)
24 CHISE_HASH_TABLE* hash
25 = (CHISE_HASH_TABLE*)malloc (sizeof (CHISE_HASH_TABLE));
31 = (CHISE_HASH_TABLE_ENTRY*) malloc (sizeof (CHISE_HASH_TABLE_ENTRY)
33 if (hash->data == NULL)
40 memset (hash->data, 0, sizeof (CHISE_HASH_TABLE_ENTRY) * size);
45 chise_destroy_hash_table (CHISE_HASH_TABLE* hash)
54 /* derived from hashpjw, Dragon Book P436. */
56 chise_hash_c_string (const unsigned char *ptr)
63 hash = (hash << 4) + *ptr++;
64 g = hash & 0xf0000000;
66 hash = (hash ^ (g >> 24)) ^ g;
68 return hash & 07777777777;
73 chise_make_name_table ()
75 return chise_make_hash_table (32);
79 chise_destroy_name_table (CHISE_NAME_TABLE* table)
81 chise_destroy_hash_table (table);
85 chise_name_table_put (CHISE_NAME_TABLE* table,
86 const unsigned char *key, void *value)
89 CHISE_NAME_TABLE_ENTRY* entry;
94 index = chise_hash_c_string (key) % table->size;
95 for (i = index; i < table->size; i++)
97 entry = &table->data[i];
98 if (entry->key == NULL)
100 size_t len = strlen (key);
102 entry->key = (unsigned char*)malloc (len + 1);
103 if (entry->key == NULL)
105 strcpy (entry->key, key);
106 entry->value = value;
109 else if (strcmp (entry->key, key) == 0)
111 entry->value = value;
115 if (chise_name_table_grow (table) == 0)
116 return chise_name_table_put (table, key, value);
121 chise_name_table_get (CHISE_NAME_TABLE* table,
122 const unsigned char *key)
125 CHISE_NAME_TABLE_ENTRY entry;
130 index = chise_hash_c_string (key) % table->size;
131 for (i = index; i < table->size; i++)
133 entry = table->data[i];
134 if (entry.key == NULL)
136 else if (strcmp (entry.key, key) == 0)
143 chise_name_table_grow (CHISE_NAME_TABLE* table)
145 CHISE_NAME_TABLE *new_table
146 = chise_make_hash_table (table->size * 2);
149 if (new_table == NULL)
152 for (i = 0; i < table->size; i++)
154 CHISE_NAME_TABLE_ENTRY entry = table->data[i];
155 if ( (entry.key != NULL) && (entry.value != NULL) )
158 = chise_name_table_put (new_table, entry.key, entry.value);
161 chise_destroy_hash_table (new_table);
166 table->size = new_table->size;
167 table->data = new_table->data;