aboutsummaryrefslogtreecommitdiff
path: root/src/allocator.h
blob: dd9bb16cdf37dfbb568ef1c5dd9957d203fc7009 (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
#pragma once

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

struct allocator {
	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)))