c-hashmap icon indicating copy to clipboard operation
c-hashmap copied to clipboard

Move struct hashmap and struct bucket to header

Open pseregiet opened this issue 1 year ago • 2 comments

Because of this move we can now have a hashmap object on the stack or allocate it ourselfs. We have a separate function to initialize and deinitialize (free buckets) the already allocated hashmap object.

Also the iterate function was moved to header and inlined. Now a static callback can be fully inlined with the function (tested only on GCC with -O2 -g)

Also add a macro 'hashmap_foreach' which allows us to write the 'callback' inline, sort of like a C++ lambda. Here's an example usage:

hashmap_foreach(map, arg_key, arg_len, arg_val,
    {
        // our code goes here in braces. above 'arg' variables are set
        // for each element in the hashmap
        printf("key: %s, keylen: %u, value: " PRIxPTR "\n",
            arg_key, arg_len, arg_val);
    });

The syntax is a bit strange, we pass our code closed in braces as last argument but I don't see a better way to do it with just the preprocessor macros.

pseregiet avatar Jun 09 '23 17:06 pseregiet

PS. I think at this point you might as well move all the function to the header and make it a one file library. It's small enough where it's fully reasonable and could allow for inlining those small functions.

pseregiet avatar Jun 09 '23 17:06 pseregiet

PS2: I'd recommend replacing uintptr_t type with void *. I understand the idea of using uintptr_t, but in the most common case of storing pointers it requires one to do an extra cast at every function call. We can take advantage of the (usually criticized) weak type checking of C and just have it use (void *) which would avoid casting in the most common use case.

pseregiet avatar Jun 09 '23 17:06 pseregiet