summaryrefslogtreecommitdiff
path: root/usual/cxalloc.c
blob: bc65f8eb33aae86c78f68fec6261e151cdf52d7f (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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
/*
 * libusual - Utility library for C
 *
 * Copyright (c) 2007-2009  Marko Kreen, Skype Technologies OÜ
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <usual/cxalloc.h>
#include <usual/statlist.h>

#include <string.h>

/*
 * Utility routines for cx_* API.
 */

void *cx_alloc(CxMem *cx, size_t len)
{
	if (!len)
		return NULL;
	if (!cx)
		cx = USUAL_ALLOC;
	return cx->ops->c_alloc(cx->ctx, len);
}

void *cx_realloc(CxMem *cx, void *ptr, size_t len)
{
	if (!cx)
		cx = USUAL_ALLOC;
	if (!ptr)
		return cx_alloc(cx, len);
	if (!len) {
		cx_free(cx, ptr);
		return NULL;
	}
	return cx->ops->c_realloc(cx->ctx, ptr, len);
}

void cx_free(CxMem *cx, const void *ptr)
{
	if (!cx)
		cx = USUAL_ALLOC;
	if (ptr)
		cx->ops->c_free(cx->ctx, ptr);
}

void cx_destroy(CxMem *cx)
{
	if (!cx)
		return;
	if (!cx->ops->c_destroy)
		abort();
	cx->ops->c_destroy(cx->ctx);
}

void *cx_alloc0(CxMem *cx, size_t len)
{
	void *p = cx_alloc(cx, len);
	if (p)
		memset(p, 0, len);
	return p;
}

void *cx_memdup(CxMem *cx, const void *src, size_t len)
{
	void *p = cx_alloc(cx, len);
	if (p)
		memcpy(p, src, len);
	return p;
}

void *cx_strdup(CxMem *cx, const char *s)
{
	return cx_memdup(cx, s, strlen(s) + 1);
}

/*
 * Base allocator that uses libc routines.
 */

static void *libc_alloc(void *ctx, size_t len)
{
	return malloc(len);
}

static void *libc_realloc(void *ctx, void *ptr, size_t len)
{
	return realloc(ptr, len);
}

static void libc_free(void *ctx, const void *ptr)
{
	free(ptr);
}

static const struct CxOps libc_alloc_ops = {
	libc_alloc,
	libc_realloc,
	libc_free,
};

const struct CxMem cx_libc_allocator = {
	&libc_alloc_ops,
	NULL,
};