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
145
146
|
#include "util.h"
#include "aoc.h"
#include <ctype.h>
#include <stdint.h>
#include <stdio.h>
void
die(const char *fmtstr, ...)
{
va_list ap;
va_start(ap, fmtstr);
fprintf(stderr, "\n");
vfprintf(stderr, fmtstr, ap);
fprintf(stderr, "\n");
va_end(ap);
abort();
}
bool
readtok(char *buf, size_t buflen, char sep, const char **pos, const char *end)
{
const char *c;
size_t len;
if (*pos >= end)
return false;
len = 0;
for (c = *pos; c != end && *c != sep; c++) {
if (len == buflen) die("util: readline: no space");
buf[len++] = *c;
}
if (len == buflen)
die("util: readline: no space");
buf[len++] = '\0';
*pos = c + 1;
return true;
}
int64_t
parsei64(const char *str)
{
int64_t val;
char *end;
val = strtoll(str, &end, 0);
if (end && *end && !isspace(*end))
die("util: parsei64: invalid %s", str);
return val;
}
char *
aprintf(const char *fmtstr, ...)
{
va_list ap, cpy;
ssize_t nb;
char *str;
va_copy(cpy, ap);
va_start(cpy, fmtstr);
nb = vsnprintf(NULL, 0, fmtstr, cpy);
if (nb < 0) die("util: aprintf: invalid fmtstr: %s", fmtstr);
va_end(cpy);
str = malloc((size_t) nb + 1);
if (!str) die("util: aprintf: malloc %lu", nb + 1);
va_start(ap, fmtstr);
nb = vsnprintf(str, (size_t) nb + 1, fmtstr, ap);
va_end(ap);
return str;
}
char *
strdup(const char *str)
{
char *alloc;
alloc = malloc(strlen(str) + 1);
strcpy(alloc, str);
return alloc;
}
char *
apprintf(char *str, const char *fmtstr, ...)
{
va_list ap, cpy;
ssize_t nb;
size_t len;
len = str ? strlen(str) : 0;
va_copy(cpy, ap);
va_start(cpy, fmtstr);
nb = vsnprintf(NULL, 0, fmtstr, cpy);
if (nb < 0) die("util: aprintf: invalid fmtstr: %s", fmtstr);
va_end(cpy);
str = realloc(str, len + (size_t) nb + 1);
if (!str) die("util: aprintf: realloc %lu", nb + 1);
va_start(ap, fmtstr);
nb = vsnprintf(str + len, (size_t) nb + 1, fmtstr, ap);
va_end(ap);
return str;
}
void *
memdup(const void *data, size_t size)
{
void *new;
new = malloc(size);
if (!new) die("util: memdup: malloc %lu", size);
memcpy(new, data, size);
return new;
}
void
readall(FILE *file, void **data, size_t *size)
{
ssize_t pos;
fseek(file, 0, SEEK_END);
pos = ftell(file);
if (pos < 0) die("util: readall: ftell");
*size = (size_t) pos;
fseek(file, 0, SEEK_SET);
*data = malloc(*size);
if (!*data) die("util: readall: malloc %lu", *size);
if (fread(*data, 1, *size, file) != *size)
die("util: readall: incomplete");
}
|