More string stuff

This commit is contained in:
2026-07-26 22:55:29 +02:00
parent 207d141ddf
commit 8534075307
3 changed files with 185 additions and 0 deletions
+72
View File
@@ -0,0 +1,72 @@
#include "string.h"
Str str_empty(void)
{
static const U8 empty_;
static const Str str = {(U8 *)&empty_, 0};
return str;
}
Str str_substr(Str str, U32 start, U32 len)
{
Assert(start < str.len);
Assert(len <= str.len);
Str new_str = str_create(&str.str[start], len);
return new_str;
}
Str str_concat(Allocator *alloc, Str first, Str second)
{
Str str;
str.len = first.len + second.len;
str.str = allocator_push(alloc, str.len, 1);;
MemCopy(str.str, first.str, first.len);
MemCopy(&str.str[first.len], second.str, second.len);
return str;
}
Str str_push(Allocator *alloc, Str str)
{
U8 *mem = (U8 *)allocator_push(alloc, sizeof(Str) + str.len, alignof(Str));
Str *new_str = (Str *)mem;
new_str->len = str.len;
new_str->str = &mem[sizeof(Str)];
if (!str_is_empty(str)) {
MemCopy(new_str->str, str.str, str.len);
}
return *new_str;
}
// split @str on any byte in @separators, place split strings in @vec
void str_split(Str str, Str separators, StrVec *vec)
{
if (vec->max_len == 0 || str.len == 0) {
return;
}
U32 start_pos = 0;
for (U32 i = 0; i < str.len; i++) {
U8 byte = str.str[i];
if (str_find_byte(separators, byte) != -1) {
if (vec->len >= vec->max_len) {
break;
}
Str sub_str = str_substr(str, start_pos, i - start_pos);
vec->strings[vec->len] = sub_str;
vec->len++;
start_pos = i + 1;
}
}
if (start_pos < str.len && vec->len < vec->max_len) {
Str sub_str = str_substr(str, start_pos, str.len - start_pos);
vec->strings[vec->len] = sub_str;
vec->len++;
}
}