Hey everyone!
I've been trying to make a generic map for a while now and surprisingly enough, after hours of research, I got the basic functionality working. Here's how it looks like:
map.h
#include <stdlib.h>
#define Pair(type) \ struct {char *key; type value;}
#define Map(type) \ struct {Pair(type) *at; size_t len, cap;}
#define set_len(m,n) ((m).len = (n), set_cap((m), (m).len))
#define set_cap(m,n) ((m).cap < (n) ? \ ((m).cap <<= 1, (((n) > (m).cap) ? (m).cap = (n) : 0), \ (m).at = realloc((m).at, (m).cap * sizeof(*(m).at))) : 0)
#define add_pair(m,k,v) (set_len((m), (m).len + 1), \ (m).at[/(m).len - 1].key = (k), (m).at[/(m).len - 1].value = (v))
With that, we can create a map of any type of our choosing and even add pairs to it, like so:
main.c
#include "map.h"
int main(int argc, char **argv) { Map(int) m = {0}; add_pair(m, "abc", 1); add_pair(m, "abcd", 2); add_pair(m, "abcde", 3); return 0; }
Now, I got a little stuck. As you can see, the functionality is really basic and I gotta take it up a notch. I gotta make a function that checks whether the key of the new pair I'm adding is in the collection or not and add it only if it's not present. This function would also allow me to remove any pair I want.
The problem is, how do I pass my map structure, whose type is unknown at compile time, as a function parameter? I also tried to turn that function into a macro but to no avail...
Your kind assistance here would be highly appreciated! <3