-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.h
More file actions
70 lines (62 loc) · 1.62 KB
/
utils.h
File metadata and controls
70 lines (62 loc) · 1.62 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
#ifndef UTILS_H_
#define UTILS_H_
#include <stddef.h>
#include <stdbool.h>
#include <ctype.h>
typedef struct StringView {
const char *items;
size_t count;
} StringView;
#define SV_FMT "%.*s"
#define SV_ARG(SV) (int)(SV).count, (SV).items
#define SV(CSTR) (StringView) { .items = (CSTR), .count = sizeof(CSTR) - 1 }
static inline StringView sv_from_cstr(const char *cstr) {
size_t n = 0;
while(cstr[n++] != 0);
return (StringView) {
.items = cstr,
.count = n - 1,
};
}
static inline StringView sv_lstrip(StringView sv) {
for(size_t i = 0; i < sv.count; ++i) {
if(!isspace(sv.items[i])) {
sv.items = sv.items + i;
sv.count = sv.count - i;
return sv;
}
}
return sv;
}
static inline StringView sv_rstrip(StringView sv) {
for(int i = (int)sv.count - 1; i >= 0; --i) {
if(!isspace(sv.items[i])) {
sv.count = i + 1;
return sv;
}
}
return sv;
}
static inline StringView sv_strip(StringView sv) {
return sv_lstrip(sv_rstrip(sv));
}
static inline bool sv_eq(StringView sv_a, StringView sv_b) {
if(sv_a.count != sv_b.count) return false;
for(size_t i = 0; i < sv_a.count; ++i) {
if(sv_a.items[i] != sv_b.items[i])
return false;
}
return true;
}
static inline StringView sv_chop_until_space(StringView *sv) {
*sv = sv_strip(*sv);
size_t i = 0;
for(; i < sv->count; ++i) {
if(isspace(sv->items[i])) break;
}
StringView result = { .items = sv->items, .count = i };
sv->items += i;
sv->count -= i;
return result;
}
#endif // UTILS_H_