-
Notifications
You must be signed in to change notification settings - Fork 11
/
util.c
76 lines (65 loc) · 1.42 KB
/
util.c
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
/*
* helpers
*****************************************************************************/
#include "util.h"
int is_digit_char(char x) {
return ('0' <= x && x <= '9');
}
int is_hex_char(char x) {
return (('0' <= x && x <= '9') ||
('a' <= x && x <= 'f') ||
('A' <= x && x <= 'F'));
}
int is_ws_char(char x) {
return (x == ' ' || x == '\t' || x == '\r' || x == '\n');
}
size_t strtosizet(const char *s) {
size_t ret = 0;
for (; *s != '\0'; s++) {
if (!is_digit_char(*s)) return SIZE_MAX;
ret *= 10;
ret += (size_t) (*s - '0');
}
return ret;
}
void warn(const char *fmt, ...) {
va_list ap;
fprintf(stderr, "jt: ");
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
fprintf(stderr, "\n");
}
void die(const char *fmt, ...) {
va_list ap;
fprintf(stderr, "jt: ");
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
fprintf(stderr, "\n");
exit(1);
}
void die_err(const char *fmt, ...) {
va_list ap;
fprintf(stderr, "jt: ");
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
if (errno != 0)
fprintf(stderr, ": %s", strerror(errno));
fprintf(stderr, "\n");
exit(1);
}
void die_mem() {
die("can't allocate memory");
}
void *jmalloc(size_t size) {
void *ret;
if (! (ret = malloc(size))) die_mem();
return ret;
}
void *jrealloc(void *ptr, size_t size) {
void *ret;
if (! (ret = realloc(ptr, size))) die_mem();
return ret;
}