aboutsummaryrefslogtreecommitdiff
path: root/src/allocator.h
blob: 2c0c5b9b710d2017a6881fea655c4231980f20d0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#pragma once

#include <stddef.h> /* size_t */

struct allocator {
#ifndef NDEBUG
	struct allocator *self;
#endif
	void *(*allocate)(struct allocator *allocator, size_t n);
	void (*deallocate)(struct allocator *allocator, void *ptr);
};

extern struct allocator default_allocator;

/* allocator interface */
void *allocator_malloc(struct allocator *allocator, size_t n);
void  allocator_free(struct allocator *allocator, void *ptr);

/* helper functions */
char *allocator_strdup(struct allocator *allocator, const char *str);
void *allocator_malloc_zero(struct allocator *allocator, size_t n);

#define ALLOCATE(n) \
	allocator_malloc(&allocator_default_allocator, (n))

#define ALLOCATE_ZERO(n) \
	allocator_malloc_zero(&allocator_default_allocator, (n))

#define FREE(ptr) \
	(allocator_free(&allocator_default_allocator, (ptr)), (ptr) = NULL)

#define NEW(ptr) ((ptr) = ALLOCATE(sizeof *(ptr)))
#define NEW0(ptr) ((ptr) = ALLOCATE_ZERO(sizeof *(ptr)))