static item_t * s_item_lookup (zhash_t *self, const char *key) { // Look in bucket list for item by key self->cached_index = s_item_hash (key, self->limit); item_t *item = self->items [self->cached_index]; while (item) { if (streq (item->key, key)) break; item = item->next; } return item; }
int zhash_insert (zhash_t *self, char *key, void *value) { assert (self); assert (key); // If we're exceeding the load factor of the hash table, // resize it according to the growth factor if (self->size >= self->limit * LOAD_FACTOR / 100) { item_t *cur_item, *next_item; item_t **new_items; size_t new_limit; qbyte index, new_index; // Create new hash table new_limit = self->limit * GROWTH_FACTOR / 100; new_items = (item_t **) zmalloc (sizeof (item_t *) * new_limit); if (!new_items) return ENOMEM; // Move all items to the new hash table, rehashing to // take into account new hash table limit for (index = 0; index != self->limit; index++) { cur_item = self->items [index]; while (cur_item) { next_item = cur_item->next; new_index = s_item_hash (cur_item->key, new_limit); cur_item->index = new_index; cur_item->next = new_items [new_index]; new_items [new_index] = cur_item; cur_item = next_item; } } // Destroy old hash table free (self->items); self->items = new_items; self->limit = new_limit; } return s_item_insert (self, key, value)? 0: -1; }
int zhash_insert (zhash_t *self, const char *key, void *value) { assert (self); assert (key); // If we're exceeding the load factor of the hash table, // resize it according to the growth factor if (self->size >= self->limit * LOAD_FACTOR / 100) { // Create new hash table size_t new_limit = self->limit * GROWTH_FACTOR / 100; item_t **new_items = (item_t **) zmalloc (sizeof (item_t *) * new_limit); if (!new_items) return -1; // Move all items to the new hash table, rehashing to // take into account new hash table limit uint index; for (index = 0; index != self->limit; index++) { item_t *cur_item = self->items [index]; while (cur_item) { item_t *next_item = cur_item->next; uint new_index = s_item_hash (cur_item->key, new_limit); cur_item->index = new_index; cur_item->next = new_items [new_index]; new_items [new_index] = cur_item; cur_item = next_item; } } // Destroy old hash table free (self->items); self->items = new_items; self->limit = new_limit; } // If necessary, take duplicate of item (string) value if (self->autofree) value = strdup ((char *) value); return s_item_insert (self, key, value)? 0: -1; }