~mcf/cproc

ref: 056c471bb7f85854e2af7a0166785d06820b251a cproc/util.c -rw-r--r-- 2.1 KiB
056c471bMichael Forney qbe: Add default cases to avoid uninitialized warning 4 months ago
                                                                                
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
136
137
138
139
140
141
142
143
144
#include <assert.h>
#include <errno.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdnoreturn.h>
#include <string.h>
#include "util.h"

char *argv0;

static void
vwarn(const char *fmt, va_list ap)
{
	fprintf(stderr, "%s: ", argv0);
	vfprintf(stderr, fmt, ap);
	if (fmt[0] && fmt[strlen(fmt) - 1] == ':') {
		fputc(' ', stderr);
		perror(NULL);
	} else {
		fputc('\n', stderr);
	}
}

void
warn(const char *fmt, ...)
{
	va_list ap;

	va_start(ap, fmt);
	vwarn(fmt, ap);
	va_end(ap);
}

noreturn void
fatal(const char *fmt, ...)
{
	va_list ap;

	va_start(ap, fmt);
	vwarn(fmt, ap);
	va_end(ap);
	exit(1);
}

void *
reallocarray(void *buf, size_t n, size_t m)
{
	if (n > 0 && SIZE_MAX / n < m) {
		errno = ENOMEM;
		return NULL;
	}
	return realloc(buf, n * m);
}

void *
xreallocarray(void *buf, size_t n, size_t m)
{
	buf = reallocarray(buf, n, m);
	if (!buf)
		fatal("reallocarray:");

	return buf;
}

void *
xmalloc(size_t len)
{
	void *buf;

	buf = malloc(len);
	if (!buf)
		fatal("malloc:");

	return buf;
}

char *
progname(char *name, char *fallback)
{
	char *slash;

	if (!name)
		return fallback;
	slash = strrchr(name, '/');
	return slash ? slash + 1 : name;
}

void *
arrayadd(struct array *a, size_t n)
{
	void *v;

	if (a->cap - a->len < n) {
		do a->cap = a->cap ? a->cap * 2 : 256;
		while (a->cap - a->len < n);
		a->val = realloc(a->val, a->cap);
		if (!a->val)
			fatal("realloc");
	}
	v = (char *)a->val + a->len;
	a->len += n;

	return v;
}

void
arrayaddptr(struct array *a, void *v)
{
	*(void **)arrayadd(a, sizeof(v)) = v;
}

void
arrayaddbuf(struct array *a, const void *src, size_t n)
{
	memcpy(arrayadd(a, n), src, n);
}

void *
arraylast(struct array *a, size_t n)
{
	if (a->len == 0)
		return NULL;
	assert(n <= a->len);
	return (char *)a->val + a->len - n;
}

void
listinsert(struct list *list, struct list *new)
{
	new->next = list->next;
	new->prev = list;
	list->next->prev = new;
	list->next = new;
}

void
listremove(struct list *list)
{
	list->next->prev = list->prev;
	list->prev->next = list->next;
	list->next = list->prev = NULL;
}