-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStr.cpp
170 lines (135 loc) · 3 KB
/
Str.cpp
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
#include "Str.h"
#include <string.h>
#include "Math/Base.h"
#include "Memory/Extras.h"
#include "Parsing.h"
const Str Str::NullStr((void*)0, 0);
char Str::Null = '\0';
Str::Str(const char* cstr)
{
data = (char*)cstr;
len = (u64)strlen(
cstr); // This struct is not meant to be used for huge strings
has_null_term = true;
}
bool Str::split(u64 at, Str* left, Str* right) const
{
if ((len < at) || (at >= len)) {
return false;
}
if (left != 0) {
left->data = data;
left->len = at + 1;
}
if (right != 0) {
right->data = data + at + 1;
right->len = len - (at + 1);
}
return true;
}
u64 Str::last_of(char c) const
{
if (len == 0) return len;
u64 i = len;
while (i != 0) {
--i;
if (data[i] == c) {
return i;
}
}
return len;
}
u64 Str::first_of(char c, u64 start) const
{
for (u64 i = start; i < len; ++i) {
if (data[i] == c) {
return i;
}
}
return len;
}
u64 Str::last_of(const Str& s, u64 start) const
{
if (s.len == 0) return len;
start = min(len, start);
u64 sindex = s.len;
u64 i = start;
while (i != 0) {
i--;
sindex--;
if (data[i] != s[sindex]) {
sindex = s.len;
}
if (sindex == 0) {
return i;
}
}
return len;
}
u64 Str::first_of(const Str& s, u64 start) const
{
if (s.len == 0) return len;
u64 sindex = 0;
u64 i;
for (i = start; i < len; ++i) {
if (data[i] == s[sindex]) {
sindex++;
} else {
sindex = 0;
}
if (sindex == s.len) {
return i - s.len + 1;
}
}
return len;
}
bool Str::starts_with(const Str& needle) const
{
u64 i = 0;
while ((i < needle.len) && (i < len) && (data[i] == needle[i])) {
i++;
}
return (i == needle.len);
}
bool Str::ends_with(const Str& needle) const
{
#if MOK_STR_RANGE_CHECK
if ((len == 0) || (needle.len == 0)) return false;
#endif
u64 mi = len - 1;
u64 ni = needle.len - 1;
while ((mi != 0) && (ni != 0)) {
if (data[mi] != needle[ni]) {
return false;
}
mi--;
ni--;
}
if (mi < 0) {
return false;
}
return true;
}
bool operator==(const Str& left, const Str& right)
{
if (left.len != right.len) return false;
for (int i = 0; i < left.len; ++i) {
if (left[i] != right[i]) {
return false;
}
}
return true;
}
Str& Str::to_upper()
{
for (u64 i = 0; i < len; ++i) {
data[i] = uppercase_of(data[i]);
}
return *this;
}
Str Str::clone(Allocator& alloc) const
{
umm dup_data = (umm)alloc.reserve(len);
memcpy(dup_data, data, len);
return Str((char*)dup_data, len);
}