2 #include "chise-name.h"
4 struct CHISE_HASH_TABLE_ENTRY
10 struct CHISE_HASH_TABLE
13 CHISE_HASH_TABLE_ENTRY *data;
17 chise_make_hash_table (size_t size)
19 CHISE_HASH_TABLE* hash
20 = (CHISE_HASH_TABLE*)malloc (sizeof (CHISE_HASH_TABLE));
26 = (CHISE_HASH_TABLE_ENTRY*) malloc (sizeof (CHISE_HASH_TABLE_ENTRY)
28 if (hash->data == NULL)
35 memset (hash->data, 0, sizeof (CHISE_HASH_TABLE_ENTRY) * size);
40 chise_destroy_hash_table (CHISE_HASH_TABLE* hash)
49 /* derived from hashpjw, Dragon Book P436. */
51 chise_hash_c_string (const unsigned char *ptr)
58 hash = (hash << 4) + *ptr++;
59 g = hash & 0xf0000000;
61 hash = (hash ^ (g >> 24)) ^ g;
63 return hash & 07777777777;
68 chise_make_name_table ()
70 return chise_make_hash_table (32);
74 chise_destroy_name_table (CHISE_NAME_TABLE* table)
76 chise_destroy_hash_table (table);
80 chise_name_table_put (CHISE_NAME_TABLE* table,
81 const unsigned char *key, void *value)
84 CHISE_NAME_TABLE_ENTRY* entry;
89 index = chise_hash_c_string (key) % table->size;
90 for (i = index; i < table->size; i++)
92 entry = &table->data[i];
93 if (entry->key == NULL)
95 size_t len = strlen (key);
97 entry->key = (unsigned char*)malloc (len + 1);
98 if (entry->key == NULL)
100 strcpy (entry->key, key);
101 entry->value = value;
104 else if (strcmp (entry->key, key) == 0)
106 entry->value = value;
110 if (chise_name_table_grow (table) == 0)
111 return chise_name_table_put (table, key, value);
116 chise_name_table_get (CHISE_NAME_TABLE* table,
117 const unsigned char *key)
120 CHISE_NAME_TABLE_ENTRY entry;
125 index = chise_hash_c_string (key) % table->size;
126 for (i = index; i < table->size; i++)
128 entry = table->data[i];
129 if (entry.key == NULL)
131 else if (strcmp (entry.key, key) == 0)
138 chise_name_table_grow (CHISE_NAME_TABLE* table)
140 CHISE_NAME_TABLE *new_table
141 = chise_make_hash_table (table->size * 2);
144 if (new_table == NULL)
147 for (i = 0; i < table->size; i++)
149 CHISE_NAME_TABLE_ENTRY entry = table->data[i];
150 if ( (entry.key != NULL) && (entry.value != NULL) )
153 = chise_name_table_put (new_table, entry.key, entry.value);
156 chise_destroy_hash_table (new_table);
161 table->size = new_table->size;
162 table->data = new_table->data;