-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.c
113 lines (97 loc) · 2.49 KB
/
utils.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
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
#include <stdio.h>
#include "utils.h"
// returns true if c is present in str
// str must be null-terminated
bool derp_char_in_str(char c, char* str) {
int i = 0;
while (str[i] != '\0') {
if (str[i] == c) return true;
i++;
}
return false;
}
// copy from inbuf to outbuf, advancing i all the while, until a character in term is encountered
char* derp_read_until(char* inbuf, int* i, char* term) {
char outbuf[16];
int j = 0;
while (!derp_char_in_str(inbuf[*i], term)) {
outbuf[j] = inbuf[*i];
j++;
(*i)++;
}
// prepare the heaped string
outbuf[j] = '\0';
char *str = malloc(j);
check_mem(str);
strcpy(str, outbuf);
return str;
error:
if (str != NULL) free(str);
return NULL;
}
// copy from inbuf to outbuf, advancing i all the while, until a character NOT in term is encountered
char* derp_read_from_whitelist(char* inbuf, int* i, char* whitelist) {
char outbuf[16];
int j = 0;
while (derp_char_in_str(inbuf[*i], whitelist)) {
outbuf[j] = inbuf[*i];
j++;
(*i)++;
}
// prepare the heaped string
outbuf[j] = '\0';
char *str = malloc(j);
check_mem(str);
strcpy(str, outbuf);
return str;
error:
if (str != NULL) free(str);
return NULL;
}
// copy from inbuf to outbuf, advancing i all the while, until a character in term is encountered
char* derp_read_until_from_str(char* inbuf, int* i, char* term, char* allowed) {
char outbuf[16];
int j = 0;
while (derp_char_in_str(inbuf[*i], allowed)) {
if (derp_char_in_str(inbuf[*i], term)) break;
outbuf[j] = inbuf[*i];
j++;
(*i)++;
}
// prepare the heaped string
outbuf[j] = '\0';
char *str = malloc(j);
check_mem(str);
strcpy(str, outbuf);
return str;
error:
if (str != NULL) free(str);
return NULL;
}
// copy from inbuf to outbuf, advancing i all the while, until a character in term is encountered
// if a character not in term or allowed is encountered, abort
char* derp_read_until_from_str_panicky(char* inbuf, int* i, char* term, char* allowed) {
char outbuf[16];
int j = 0;
while (derp_char_in_str(inbuf[*i], allowed)) {
if (derp_char_in_str(inbuf[*i], term)) break;
outbuf[j] = inbuf[*i];
j++;
(*i)++;
}
// if a character not in term or allowed is encountered, abort
if (!derp_char_in_str(inbuf[*i], allowed) && !derp_char_in_str(inbuf[*i], term)) {
debug("aborted on weird char: '%c'", inbuf[*i]);
goto error;
}
// prepare the heaped string
outbuf[j] = '\0';
char *str = NULL;
str = malloc(j);
check_mem(str);
strcpy(str, outbuf);
return str;
error:
if (str != NULL) free(str);
return NULL;
}