Hashtable entry deletion method

This commit is contained in:
Vftdan 2024-08-19 21:19:04 +02:00
parent bca67c9663
commit 184e7d8514
2 changed files with 42 additions and 0 deletions

View File

@ -325,3 +325,36 @@ hash_table_find_impl(const HashTableDynamicData * ht, const HashTableKey key)
return -1;
}
bool
hash_table_delete_at_index_impl(HashTableDynamicData * ht, const HashTableIndex index)
{
if (!ht) {
return false;
}
if (index < 0 || (size_t) index > ht->capacity) {
return false;
}
HashTableKeyEntry *key_entry_ptr = ht->key_array + index;
void *value_ptr = ht->value_array + (ht->value_size * index);
if (!key_entry_ptr->key.bytes) {
// No entry at index
return false;
}
// TODO find base_index and reduce its max_collision_offset when provably justified
hash_table_key_deinit_copied(&key_entry_ptr->key);
ht->length -= 1;
void (*value_deinit)(void*) = ht->value_deinit;
if (value_deinit) {
value_deinit(value_ptr);
}
memset(value_ptr, 0, ht->value_size);
return true;
}

View File

@ -53,10 +53,19 @@ void hash_table_init_impl(HashTableDynamicData * dyndata, size_t value_size, voi
void hash_table_deinit_impl(HashTableDynamicData * dyndata);
HashTableIndex hash_table_insert_impl(HashTableDynamicData * dyndata, const HashTableKey key, const void * value_ptr);
HashTableIndex hash_table_find_impl(const HashTableDynamicData * dyndata, const HashTableKey key);
bool hash_table_delete_at_index_impl(HashTableDynamicData * dyndata, const HashTableIndex index);
__attribute__((unused)) inline static bool
hash_table_delete_by_key_impl(HashTableDynamicData * dyndata, const HashTableKey key)
{
return hash_table_delete_at_index_impl(dyndata, hash_table_find_impl(dyndata, key));
}
#define hash_table_init(ht, value_deinit) hash_table_init_impl(&(ht)->as_HashTableDynamicData, sizeof(*(ht)->value_array), IMPLICIT_CAST(void(void*), void(typeof((ht)->value_array)), value_deinit))
#define hash_table_deinit(ht) hash_table_deinit_impl(&(ht)->as_HashTableDynamicData)
#define hash_table_insert(ht, key, value_ptr) hash_table_insert_impl(&(ht)->as_HashTableDynamicData, key, IMPLICIT_CAST(const void, const typeof(*(ht)->value_array), value_ptr))
#define hash_table_find(ht, key) hash_table_find_impl(&(ht)->as_HashTableDynamicData, key)
#define hash_table_delete_at_index(ht, index) hash_table_delete_at_index_impl(&(ht)->as_HashTableDynamicData, index)
#define hash_table_delete_by_key(ht, key) hash_table_delete_by_key_impl(&(ht)->as_HashTableDynamicData, key)
#endif /* end of include guard: HASH_TABLE_H_ */