Skip to content

Instantly share code, notes, and snippets.

@jedavidson
Last active January 19, 2025 06:50
Show Gist options
  • Save jedavidson/c139a298fedfe5ec102060517827a857 to your computer and use it in GitHub Desktop.
Save jedavidson/c139a298fedfe5ec102060517827a857 to your computer and use it in GitHub Desktop.
Terrible experiments in implementing a monomorphised hash table in C

Include and use as follows:

// one for int -> int
#define HASHTABLE_KEY_TYPE int
#define HASHTABLE_VALUE_TYPE int
#define HASHTABLE_ADT_NAME IntHashTable
#include "hashtable.h"

// one for string -> int
#define HASHTABLE_KEY_TYPE char *
#define HASHTABLE_VALUE_TYPE int
#define HASHTABLE_ADT_NAME StringHashTable
#include "hashtable.h"
#include <stddef.h>
#include <stdint.h>
#if !defined(HASHTABLE_KEY_TYPE)
#error Missing definition for key type
#endif
#if !defined(HASHTABLE_VALUE_TYPE)
#error Missing definition for value type
#endif
#if !defined(HASHTABLE_ADT_NAME)
#define HASHTABLE_ADT_NAME HashTable
#endif
#define HashTable(key, value) HASHTABLE_key ## _ ## value
#define HASHTABLE_CONCAT(tag, method) tag ## _ ## method
#define _HASHTABLE_METHOD(tag, method) HASHTABLE_CONCAT(tag, method)
#define HASHTABLE_METHOD(method) _HASHTABLE_METHOD(HASHTABLE_ADT_NAME, method)
typedef uint32_t Hash;
typedef Hash (*HashFunction)(HASHTABLE_KEY_TYPE key);
typedef struct HASHTABLE_ADT_NAME {
HASHTABLE_VALUE_TYPE *values;
HashFunction h;
size_t size;
size_t capacity;
} HASHTABLE_ADT_NAME;
#undef HASHTABLE_ADT_NAME
#undef HASHTABLE_KEY_TYPE
#undef HASHTABLE_VALUE_TYPE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment