/* Shrinks MAP's set of buckets to the minimum number needed to store its current number of elements, allocating a new set of buckets and rehashing if that would save space. */ void hmap_shrink (struct hmap *map) { size_t new_mask = capacity_to_mask (map->count); if (new_mask < map->mask) hmap_rehash (map, new_mask); }
void * hmap_put(HMap *map, void *key, void *value) { HMapEntry *entry; uint32_t index; index = hmap_hash(map, key); if (key == NULL) { for (entry = map->buckets[index]; entry != NULL; entry = entry->next) { if (entry->key == NULL) { void *old_value = entry->value; entry->value = value; return old_value; } } } else { for (entry = map->buckets[index]; entry != NULL; entry = entry->next) { if (map->compare(key, entry->key) == 0) { void *old_value = entry->value; entry->value = value; return old_value; } } } map->size++; if (map->size > map->threshold) { hmap_rehash(map); index = hmap_hash(map, key); } entry = xmalloc(sizeof(HMapEntry)); entry->key = key; entry->value = value; entry->next = map->buckets[index]; map->buckets[index] = entry; return NULL; }
/* Ensures that MAP has sufficient space to store at least CAPACITY data elements, allocating a new set of buckets and rehashing if necessary. */ void hmap_reserve (struct hmap *map, size_t capacity) { if (capacity > hmap_capacity (map)) hmap_rehash (map, capacity_to_mask (capacity)); }