aboutsummaryrefslogtreecommitdiff
path: root/allocator.c
blob: 6d13a17a3b22a2bbb32832f18b2b6a37b0b05d89 (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
#include "allocator.h"

#include <stdlib.h>

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

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

struct its1_allocator its1_default_allocator = {
	.allocate   = &default_allocate,
	.deallocate = &default_deallocate
};

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

void *
its1_malloc(struct its1_allocator *allocator, size_t n)
{
	if ( allocator == NULL ) {
		allocator = &its1_default_allocator;
	}

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

void
its1_free(struct its1_allocator *allocator, void *ptr)
{
	if ( allocator == NULL ) {
		allocator = &its1_default_allocator;
	}

	allocator->deallocate(allocator, ptr);
}

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

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

	return dest;
}

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

	ptr = its1_malloc(allocator, n);
	if ( ptr != NULL ) {
		memset(ptr, 0, n);
	}

	return ptr;
}

int
main()
{
}