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 void *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 size_t limit = primes [self->prime_index]; if (self->size >= limit * LOAD_FACTOR / 100) { // Create new hash table uint new_prime_index = self->prime_index + GROWTH_FACTOR; if (s_zhash_rehash (self, new_prime_index)) return -1; self->chain_limit += CHAIN_GROWS; } 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; }