summaryrefslogtreecommitdiff
path: root/util/alloc.c
blob: 662c452f99a1365783ccad8887fa9efa0d392e5d (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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
#include <stdlib.h>
#include <stdio.h>
#include <inttypes.h>
#include <stdarg.h>
#include <ctype.h>
#include <string.h>
#include <assert.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#include "util.h"

/* Some systems don't have strndup. */
/* malloc wrappers */
void *zalloc(size_t sz)
{
	void *mem;

	mem = calloc(1, sz);
	if (!mem && sz)
		die("Out of memory");
	return mem;
}

void *xalloc(size_t sz)
{
	void *mem;

	mem = malloc(sz);
	if (!mem && sz)
		die("Out of memory");
	return mem;
}

void *zrealloc(void *mem, size_t oldsz, size_t sz)
{
	char *p;

	p = xrealloc(mem, sz);
	if (sz > oldsz)
		memset(&p[oldsz], 0, sz - oldsz);
	return p;
}

void *xrealloc(void *mem, size_t sz)
{
	mem = realloc(mem, sz);
	if (!mem && sz)
		die("Out of memory");
	return mem;
}

/* lists */
void lappend(void *l, size_t *len, void *n)
{
	void ***pl;

	pl = l;
	*pl = xrealloc(*pl, (*len + 1) * sizeof(void *));
	(*pl)[*len] = n;
	(*len)++;
}

void *lpop(void *l, size_t *len)
{
	void ***pl;
	void *v;

	pl = l;
	(*len)--;
	v = (*pl)[*len];
	*pl = xrealloc(*pl, *len * sizeof(void *));
	return v;
}

void linsert(void *p, size_t *len, size_t idx, void *v)
{
	void ***pl, **l;

	pl = p;
	*pl = xrealloc(*pl, (*len + 1) * sizeof(void *));
	l = *pl;

	memmove(&l[idx + 1], &l[idx], (*len - idx) * sizeof(void *));
	l[idx] = v;
	(*len)++;
}

void ldel(void *p, size_t *len, size_t idx)
{
	void ***pl, **l;

	assert(p != NULL);
	assert(idx < *len);
	pl = p;
	l = *pl;
	memmove(&l[idx], &l[idx + 1], (*len - idx - 1) * sizeof(void *));
	(*len)--;
	*pl = xrealloc(l, *len * sizeof(void *));
}

void lcat(void *dst, size_t *ndst, void *src, size_t nsrc)
{
	size_t i;
	void ***d, **s;

	d = dst;
	s = src;
	for (i = 0; i < nsrc; i++)
		lappend(d, ndst, s[i]);
}

void lfree(void *l, size_t *len)
{
	void ***pl;

	assert(l != NULL);
	pl = l;
	free(*pl);
	*pl = NULL;
	*len = 0;
}

void *memdup(void *mem, size_t len)
{
	void *ret;

        if (!mem)
            return NULL;
	ret = xalloc(len);
	return memcpy(ret, mem, len);
}