4 ms·
I would drop the API directly and concentrate on the algorithm. If users integrating HAMT need a different allocator situation, they can solve that problem by
by kazinator 3y ago
I would drop the API directly and concentrate on the algorithm.
If users integrating HAMT need a different allocator situation, they can solve that problem by themselves, without a run-time indirection shim.
You can help those users by providing some macros somewhere like #define hamt_malloc(ctx, x) malloc(x) and so forth, so it can be retargeted in one place. Leave an ignored context argument in place for those who would like to have a run-time switch per-instance.
- hgs3 3y agoI've seen this type of API design in C before, but not with a context. I'm curious where HAMT would get the ctx instance to pass to hamt_malloc in this design?
- kazinator 3y agoIf the macro doesn't use the argument, it doesn't have to exist. Currently the code does use macros, e.g. mem_alloc(h->ator, size). Firstly, I'd hide the detail of how the allocator is derived from h into the allocator wrapper routines and just make it mem_alloc(h, size). It's mem_alloc which can do h->ator. Now the nice thing is that h always exists. So even mem_alloc ignores the first parameter, we don't have to pass something fictional as an argument: #define mem_alloc(h, size) malloc(size) then remove the h->ator and related cruft. Someone who needs a context for their allocator can hack that in. By the way, if you're going to have allocator providers, you want: #define mem_alloc(h, size) h->ator->alloc(h->ator, size) ^^^^^^^ and not: #define mem_alloc(h, size) h->ator->alloc(size) like the code has it now. Thou shalt not define a C callback interface without a context pointer. Without a context pointer, you cannot have an allocator module where you can bind different allocator arenas to different objects.
- flohofwoe 3y agoI used macros in my libraries for overriding the allocation functions before, but have switched to runtime callbacks later, same for logging btw (I'd need to look through the issues list for the exact reasons which led to this decision though). In any case, passing callbacks as part of the initialization "feels" right and I didn't hear any complaints since the switch (and it's definitely a lot more convenient for the library user). Also, if the library calls those function so frequently that the pointer indirection would be a performance problem, then there's arguably something very wrong with the library's design.