-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstr.c
115 lines (92 loc) · 2.42 KB
/
str.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
114
115
#include "str.h"
#include "memory.h"
#include <string.h>
#include <stdlib.h>
#define STR_DEFAULT_CAP 64
void destroyString(String *str) {
MFREE(str->buf);
*str = (String){0};
}
bool compareString(const String *a, const String *b) {
bool result = false;
if (a->len == b->len) {
result = (memcmp(a->buf, b->buf, a->len * sizeof(char)) == 0);
}
return result;
}
static void tryExpand(String *str, int newLen) {
if (str->cap < newLen + 1) {
int newCap = MAX(str->cap, 1);
do {
newCap <<= 2;
} while (newCap < (newLen + 1));
char *oldBuf = str->buf;
int oldCap = str->cap;
str->cap = newCap;
str->buf = MMALLOC_ARRAY(char, str->cap);
memcpy(str->buf, oldBuf, oldCap);
MFREE(oldBuf);
}
}
void appendCStr(String *str, const char *toAppend) {
int offset = str->len;
int appendLen = (int)strlen(toAppend);
int newLen = str->len + appendLen;
tryExpand(str, newLen);
str->len = newLen;
memcpy(str->buf + offset, toAppend, appendLen);
str->buf[str->len] = 0;
}
void appendString(String *str, const String *toAppend) {
int offset = str->len;
int appendLen = toAppend->len;
int newLen = str->len + appendLen;
tryExpand(str, newLen);
str->len = newLen;
memcpy(str->buf + offset, toAppend->buf, appendLen);
str->buf[str->len] = 0;
}
void copyStringFromCStr(String *dst, const char *src) {
int srcLen = (int)strlen(src);
tryExpand(dst, srcLen);
memcpy(dst->buf, src, srcLen);
dst->buf[srcLen] = 0;
dst->len = srcLen;
}
void copyString(String *dst, const String *src) {
tryExpand(dst, src->len);
memcpy(dst->buf, src->buf, src->len);
dst->buf[src->len] = 0;
dst->len = src->len;
}
static bool isSeparator(char ch) {
bool result = ch == '/' || ch == '\\';
return result;
}
void appendPathCStr(String *str, const char *path) {
while (*path && isSeparator(*path)) {
++path;
}
if (str->len == 0 || !isSeparator(str->buf[str->len - 1])) {
appendCStr(str, "/");
}
appendCStr(str, path);
}
const char *pathBaseName(const String *str) {
int i = str->len - 1;
while (isSeparator(str->buf[i]) && i >= 0) {
--i;
}
while (!isSeparator(str->buf[i]) && i >= 0) {
--i;
}
return i >= 0 ? &str->buf[i + 1] : "";
}
bool endsWithCString(const String *str, const char *ch) {
int chlen = (int)strlen(ch);
if (str->len < chlen) {
return false;
}
bool result = (strncmp(&str->buf[str->len - chlen], ch, chlen) == 0);
return result;
}