~kdsch/c-modules

f4c80dd9dfbfa63aba8ed9630c461806559f3c7c — Karl Schultheisz 4 months ago ee3e476
dynamic-array: allow custom memory allocator
3 files changed, 10 insertions(+), 10 deletions(-)

M dynamic-array.c
M dynamic-array.h
M main.c
M dynamic-array.c => dynamic-array.c +4 -5
@@ 1,7 1,6 @@
#include <assert.h>
#include "dynamic-array.h"
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>

void


@@ 20,7 19,7 @@ array_full(const struct array *const a)
}

static enum status
array_grow(struct array *const a)
array_grow(struct array *const a, void *(*const realloc)(void *p, size_t size))
{
	assert(a != NULL);



@@ 40,10 39,10 @@ array_grow(struct array *const a)
}

enum status
array_append(struct array *const a, const uint32_t x)
array_append(struct array *const a, const uint32_t x, void *(*const realloc)(void *p, size_t size))
{
	if (array_full(a)) {
		const enum status status = array_grow(a);
		const enum status status = array_grow(a, realloc);
		if (status != STATUS_OK) {
			return status;
		}


@@ 58,7 57,7 @@ array_append(struct array *const a, const uint32_t x)
}

void
array_free(struct array *const a)
array_free(struct array *const a, void (*const free)(void *ptr))
{
	assert(a != NULL);


M dynamic-array.h => dynamic-array.h +2 -2
@@ 15,6 15,6 @@ struct array {
};

void array_init(struct array *const a);
enum status array_append(struct array *const a, const uint32_t x);
void array_free(struct array *const a);
enum status array_append(struct array *const a, const uint32_t x, void *(*const realloc)(void *p, size_t size));
void array_free(struct array *const a, void (*const free)(void *ptr));
#endif

M main.c => main.c +4 -3
@@ 1,16 1,17 @@
#include "dynamic-array.c"
#include "pool-allocator.c"
#include <stdlib.h>

static void
harness_array(void)
{
	struct array a;
	array_init(&a);
	assert(array_append(&a, 42) == STATUS_OK);
	assert(array_append(&a, 42, realloc) == STATUS_OK);
	assert(a.length == 1);
	assert(array_append(&a, 42) == STATUS_OK);
	assert(array_append(&a, 42, realloc) == STATUS_OK);
	assert(a.length == 2);
	array_free(&a);
	array_free(&a, free);
	assert(a.length == 0);
}