Created
July 18, 2022 01:57
-
-
Save audinue/64c78a8a25e54a04a0582879992814bc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
#include <string.h> | |
#define CAPACITY 4096 | |
typedef struct Entry { | |
char* key; | |
void* value; | |
struct Entry* next; | |
} Entry; | |
Entry* entries[CAPACITY]; | |
unsigned _hash(char* key) { | |
unsigned hash; | |
for (hash = 0; *key != 0; key++) | |
hash = *key + 31 * hash; | |
return hash % CAPACITY; | |
} | |
void* get(char* key) { | |
Entry* entry; | |
for (entry = entries[_hash(key)]; entry; entry = entry->next) | |
if (!strcmp(key, entry->key)) | |
return entry->value; | |
return 0; | |
} | |
void put(char* key, void* value) { | |
Entry* entry; | |
unsigned hash = _hash(key); | |
for (entry = entries[hash]; entry; entry = entry->next) | |
if (!strcmp(key, entry->key)) | |
{ | |
entry->value = value; | |
return; | |
} | |
entry = (Entry*) malloc(sizeof(Entry)); | |
entry->key = key; | |
entry->value = value; | |
entry->next = entries[hash]; | |
entries[hash] = entry; | |
} | |
#include <stdio.h> | |
void main() | |
{ | |
int i; | |
printf("put\n"); | |
for (i = 0; i < 2000; ++i) | |
{ | |
char* key = malloc(32); | |
sprintf(key, "%d", i); | |
put(key, (void*) (i * 10)); | |
} | |
printf("get\n"); | |
printf("%d\n", (int) get("1234")); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This hash map is good enough for one off apps.
But terrible enough for reusability: