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
|
#define _XOPEN_SOURCE 600
#include "util.h"
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <wchar.h>
#include <wctype.h>
static const char *allowed = "abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.:,;-_(){}[]";
int
strnwidth(const char *s, int n)
{
mbstate_t shift_state;
wchar_t wc;
size_t wc_len;
size_t width = 0;
memset(&shift_state, '\0', sizeof shift_state);
for (size_t i = 0; i < n; i += wc_len) {
wc_len = mbrtowc(&wc, s + i, MB_CUR_MAX, &shift_state);
if (!wc_len) {
break;
} else if (wc_len >= (size_t)-2) {
width += MIN(n - 1, strlen(s + i));
break;
} else {
width += iswcntrl(wc) ? 2 : MAX(0, wcwidth(wc));
}
}
done:
return width;
}
void
assert(int cond, const char *file, int line, const char *condstr)
{
if (cond) return;
fprintf(stderr, "Assertion failed %s:%i (%s)", file, line, condstr);
exit(1);
}
char *
sanitized(const char *instr)
{
const char *p;
char *clean;
int i;
clean = strdup(instr);
ASSERT(clean != NULL);
for (i = 0, p = instr; *p; p++) {
if (strchr(allowed, *p))
clean[i++] = *p;
}
ASSERT(i != 0);
clean[i] = '\0';
return clean;
}
char *
aprintf(const char *fmtstr, ...)
{
va_list ap, cpy;
size_t size;
char *str;
va_copy(cpy, ap);
va_start(ap, fmtstr);
size = vsnprintf(NULL, 0, fmtstr, ap);
va_end(ap);
str = malloc(size + 1);
ASSERT(str != NULL);
va_start(cpy, fmtstr);
vsnprintf(str, size + 1, fmtstr, cpy);
va_end(cpy);
return str;
}
|