~kdsch/c-modules

c8450fadd5075e10c91c1a9601a8fb7faadcfba9 — Karl Schultheisz 4 months ago f4c80dd master
pool-allocator: use indexes in API, not pointers
3 files changed, 21 insertions(+), 20 deletions(-)

M main.c
M pool-allocator.c
M pool-allocator.h
M main.c => main.c +3 -3
@@ 20,17 20,17 @@ harness_pool_allocator(void)
{
	struct object_allocator allocator;
	object_allocator_init(&allocator);
	struct object *objects[32];
	uint8_t indexes[32];

	for (uint8_t i = 0; i < 32; i++) {
		objects[i] = object_new(&allocator);
		indexes[i] = object_new(&allocator);
	}

	assert(object_new(&allocator) == NULL);
	assert(allocator.used == UINT32_MAX);

	for (uint8_t i = 0; i < 32; i++) {
		object_free(&allocator, objects[i]);
		object_free(&allocator, indexes[i]);
	}

	assert(allocator.used == 0);

M pool-allocator.c => pool-allocator.c +16 -15
@@ 1,5 1,6 @@
#include "pool-allocator.h"
#include <assert.h>
#include <stdbool.h>
#include <stddef.h>
#include <string.h>



@@ 28,7 29,7 @@ count_trailing_zeroes(uint32_t x)
	return n;
}

struct object *
uint8_t
object_new(struct object_allocator *allocator)
{
	assert(allocator);


@@ 43,25 44,25 @@ object_new(struct object_allocator *allocator)

	const uint8_t index = position - 1;
	allocator->used |= 1u << index;
	return &allocator->objects[index];
	return index;
}

void
object_free(struct object_allocator *allocator, struct object *object)
static bool
object_is_used(const struct object_allocator *const allocator, const uint8_t index)
{
	assert(allocator);
	assert(index < 32);
	return allocator->used | (1u << index);
}

	// Don't call me when nothing is allocated.
void
object_free(struct object_allocator *allocator, const uint8_t index)
{
	assert(allocator);
	assert(0 < allocator->used);
	assert(index < 32);
	assert(object_is_used(allocator, index));

	for (uint8_t i = 0; i < 32; i++) {
		if (object == &allocator->objects[i]) {
			allocator->used &= ~(1u << i);
			memset(object, 0, sizeof(*object));
			return;
		}
	}

	// Don't call me with addresses that aren't mine.
	assert(0);
	allocator->used &= ~(1u << index);
	memset(&allocator->objects[index], 0, sizeof(allocator->objects[0]));
}

M pool-allocator.h => pool-allocator.h +2 -2
@@ 8,6 8,6 @@ struct object_allocator {
};

void object_allocator_init(struct object_allocator *allocator);
struct object *object_new(struct object_allocator *allocator);
void object_free(struct object_allocator *allocator, struct object *object);
uint8_t object_new(struct object_allocator *allocator);
void object_free(struct object_allocator *allocator, const uint8_t index);
#endif