// hashmap.c #include "hashmap.h" #include #include // DJB2哈希算法 static unsigned long hash(const char* str) { unsigned long hash = 5381; int c; while ((c = *str++)) hash = ((hash << 5) + hash) + c; /* hash * 33 + c */ return hash % HMAP_SIZE; } void hmap_init(HashMap* map) { memset(map->buckets, 0, sizeof(map->buckets)); } void hmap_put(HashMap* map, const char* key, void* value) { unsigned long idx = hash(key); HashMapEntry* entry = malloc(sizeof(HashMapEntry)); entry->key = strdup(key); entry->value = value; entry->next = map->buckets[idx]; map->buckets[idx] = entry; } void* hmap_get(HashMap* map, const char* key) { unsigned long idx = hash(key); HashMapEntry* entry = map->buckets[idx]; while (entry) { if (strcmp(entry->key, key) == 0) return entry->value; entry = entry->next; } return NULL; } int hmap_contains(HashMap* map, const char* key) { return hmap_get(map, key) != NULL; } void hmap_destroy(HashMap* map) { for (int i = 0; i < HMAP_SIZE; i++) { HashMapEntry* entry = map->buckets[i]; while (entry) { HashMapEntry* next = entry->next; free(entry->key); free(entry); entry = next; } } }