Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdlib.h>
- #include <assert.h>
- #include "hash_table.h"
- #include "types.h"
- void hash_table_init(hash_table *ht) {
- ht->entries = (hash_table_entry*) calloc(INITIAL_HASH_TABLE_ENTRIES, sizeof(hash_table_entry));
- ht->num_entries = INITIAL_HASH_TABLE_ENTRIES;
- ht->used_entries = 0;
- }
- void hash_table_free(hash_table *ht) {
- free(ht->entries);
- free(ht);
- }
- void hash_table_put(hash_table *ht, char *key, void *value) {
- if(ht->used_entries == ht->num_entries) {
- hash_table_resize(ht);
- }
- s32 index = hash_table_find_index(ht, key);
- if(ht->entries[index].value) {
- index = hash_table_probe(ht, index);
- }
- assert(index != -1);
- if(value) {
- ht->used_entries++;
- } else {
- ht->used_entries--;
- }
- ht->entries[index].key = key;
- ht->entries[index].value = value;
- }
- void* hash_table_get(hash_table *ht, char *key) {
- s32 index = hash_table_find_index(ht, key);
- if(index == -1) {
- return 0;
- }
- return ht->entries[index].value;
- }
- void hash_table_resize(hash_table *ht) {
- u32 new_num_entries = ht->used_entries * 2;
- if(new_num_entries == 0) {
- new_num_entries = INITIAL_HASH_TABLE_ENTRIES;
- }
- hash_table_entry *old_entries = ht->entries;
- u32 old_num_entries = ht->num_entries;
- ht->entries = (hash_table_entry*) calloc(new_num_entries, sizeof(hash_table_entry));
- ht->num_entries = new_num_entries;
- ht->used_entries = 0;
- u32 index;
- for(index = 0; index < old_num_entries; index++) {
- hash_table_entry entry = old_entries[index];
- if(entry.value) {
- hash_table_put(ht, old_entries[index].key, old_entries[index].value);
- }
- }
- free(old_entries);
- }
- s32 hash_table_find_index(hash_table *ht, char *key) {
- return (s32) (hash_string(key) % ht->num_entries);
- }
- s32 hash_table_probe(hash_table *ht, s32 index) {
- do {
- index++;
- if(index >= ht->num_entries) {
- return -1;
- }
- } while(ht->entries[index].value);
- return index;
- }
- u64 hash_string(char *str) {
- if(!str) {
- return 0;
- }
- u64 hash = 5381;
- u8 c;
- while(c = *str++) {
- hash = ((hash << 5) + hash) + c;
- }
- return hash;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement