Proposal: allow setting memory functions through callbacks (in addition to macros) #49
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Passing a function pointer to the library gives greater flexibility than through the
#define
s for FAST_OBJ_REALLOC/_FREE, as it's a choice that can be made (and changed) at runtime.This PR adds a new (optional)
fast_obj_set_memory_functions
API for that, to set three new global variables in the FAST_OBJ_IMPLEMENTATION:By default, these will fallback to calling FAST_OBJ_REALLOC and FAST_OBJ_FREE, so this is not a breaking change (I have still bumped the version to 1.4).
The two
typedef
s --fastObjRealloc
andfastObjFree
-- take avoid* context
which allows for passing user data to the memory functions. Also, realloc takes both the new size and old size, to avoid the need of externally keeping track of allocation sizes.I'd meant to do the same for the dealloc function (see https://nullprogram.com/blog/2023/12/17/), but ended up deciding against it as the majority of users will continue to use libc's
free
, thus leading to unnecessarystrlen
computations.For context: the motivation behind this is that it will make it easier/cleaner to integrate fast_obj with arena allocators (where
fastObjFree
is usually a no-op). If this isn't deemed useful in the general case, feel free not to accept the PR 🙂