Repository navigation
Expand file tree
/
Copy pathurlor.c
More file actions
116 lines (86 loc) · 2.51 KB
/
Copy pathurlor.c
File metadata and controls
116 lines (86 loc) · 2.51 KB
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
#include "../src/lcthw/bstrlib.h"
#include "../src/lcthw/dbg.h"
#include "../src/lcthw/tstree.h"
// build it like this: gcc ./bin/urlor.c -o ./bin/urlor ./src/lcthw/tstree.o ./src/lcthw/bstrlib.o
TSTree *add_route_data(TSTree *routes, bstring line) {
struct bstrList *data = bsplit(line, ' ');
check(data->qty == 2, "Line '%s' does not have 2 columns", bdata(line));
routes = TSTree_insert(routes, bdata(data->entry[0]), blength(data->entry[0]),
bstrcpy(data->entry[1]));
bstrListDestroy(data);
return routes;
error:
return NULL;
}
TSTree *load_routes(const char *file) {
TSTree *routes = NULL;
bstring line = NULL;
FILE *routes_map = NULL;
routes_map = fopen(file, "r");
check(routes_map != NULL, "Failed to open routes: %s", file);
while ((line = bgets((bNgetc)fgetc, routes_map, '\n')) != NULL) {
check(btrimws(line) == BSTR_OK, "Failed to trim line");
routes = add_route_data(routes, line);
check(routes != NULL, "Failed to add route");
bdestroy(line);
}
fclose(routes_map);
return routes;
error:
if (routes_map) {
fclose(routes_map);
}
if (line) {
bdestroy(line);
}
return NULL;
}
bstring match_url(TSTree *routes, bstring url) {
bstring route = TSTree_search(routes, bdata(url), blength(url));
if (route == NULL) {
printf("No exact match found, trying prefix.\n");
route = TSTree_search_prefix(routes, bdata(url), blength(url));
}
return route;
}
bstring read_line(const char *prompt) {
printf("%s", prompt);
bstring result = bgets((bNgetc)fgetc, stdin, '\n');
check_debug(result != NULL, "stdin closed.");
check(btrimws(result) == BSTR_OK, "Failed to trim.");
return result;
error:
return NULL;
}
void bdestroy_cb(void *value, void *ignored, char x) {
(void)ignored;
bdestroy((bstring)value);
}
void destroy_routes(TSTree *routes) {
TSTree_traverse(routes, bdestroy_cb, NULL);
TSTree_destroy(routes);
}
int main(int argc, char *argv[]) {
bstring url = NULL;
bstring route = NULL;
TSTree *routes = NULL;
check(argc == 2, "USAGE: urlor <urlfile>");
routes = load_routes(argv[1]);
check(routes != NULL, "Your route file has an error.");
while (1) {
url = read_line("URL> ");
check_debug(url != NULL, "goodbye.");
route =
3DC1
match_url(routes, url);
if (route) {
printf("MATCH: %s == %s\n", bdata(url), bdata(route));
} else {
printf("FAIL: %s\n", bdata(url));
}
bdestroy(url);
}
destroy_routes(routes);
return 0;
error:
destroy_routes(routes);
return 1;
}