aboutsummaryrefslogtreecommitdiff
path: root/src/allocator.c
blob: d6aeea9598fb29986e5c21a8d27d826d77eaff56 (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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include "allocator.h"

#include <stdlib.h> /* malloc */

/* Interface Code */
static void *
default_allocate(struct allocator *allocator, size_t n)
{
	(void) allocator;
	return malloc(n);
}

static void
default_deallocate(struct allocator *allocator, void *ptr)
{
	(void) allocator;
	free(ptr);
}

struct allocator allocator_default_allocator = {
	.allocate   = &default_allocate,
	.deallocate = &default_deallocate
};

/* Libary Code */
#include <string.h>

void *
allocator_malloc(struct allocator *allocator, size_t n)
{
	if ( !allocator ) {
		allocator = &allocator_default_allocator;
	}

	return allocator->allocate(allocator, n);
}

void
allocator_free(struct allocator *allocator, void *ptr)
{
	if ( !allocator ) {
		allocator = &allocator_default_allocator;
	}

	allocator->deallocate(allocator, ptr);
}

char *
allocator_strdup(struct allocator *allocator, const char *str)
{
	size_t n;
	char  *dest;

	n    = strlen(str) + 1;
	dest = allocator_malloc(allocator, n);
	if ( dest ) {
		memcpy(dest, str, n);
	}

	return dest;
}

void *
allocator_malloc_zero(struct allocator *allocator, size_t n)
{
	void *ptr;

	ptr = allocator_malloc(allocator, n);
	if ( ptr ) {
		memset(ptr, 0, n);
	}

	return ptr;
}

int
main(void)
{
	return 0;
}