noh.h: Add noh_sv_copy_cstr and noh_sv_compare

This commit is contained in:
2026-05-14 21:39:51 +02:00
parent 4cb074feab
commit 538cfdafa5

View File

@@ -357,6 +357,9 @@ typedef struct {
const char *elems; const char *elems;
} Noh_String_View; } Noh_String_View;
// Copies a c-string to the arena and returns it as a Noh_String_View.
Noh_String_View noh_sv_copy_cstr(Noh_Arena *arena, const char *cstr);
// Appends a Noh_String_View view into a Noh_String. // Appends a Noh_String_View view into a Noh_String.
void noh_string_append_sv(Noh_String *string, Noh_String_View sv); void noh_string_append_sv(Noh_String *string, Noh_String_View sv);
@@ -403,6 +406,13 @@ Noh_String_View noh_sv_from_cstr(const char *cstr);
// Creates a string view from a string. // Creates a string view from a string.
Noh_String_View noh_sv_from_string(const Noh_String *string); Noh_String_View noh_sv_from_string(const Noh_String *string);
// Compares two string views.
// Returns:
// - 0 if the two strings are equal.
// - A negative value if a is smaller than b.
// - A positive value if a is greater than b.
int noh_sv_compare(Noh_String_View a, Noh_String_View b);
// Checks whether to string views contain the same string. // Checks whether to string views contain the same string.
bool noh_sv_eq(Noh_String_View a, Noh_String_View b); bool noh_sv_eq(Noh_String_View a, Noh_String_View b);
@@ -883,6 +893,13 @@ defer:
///////////////////////// String view ///////////////////////// ///////////////////////// String view /////////////////////////
Noh_String_View noh_sv_copy_cstr(Noh_Arena *arena, const char *cstr) {
size_t len = strlen(cstr);
char *buffer = noh_arena_alloc(arena, len);
memcpy(buffer, cstr, len);
return (Noh_String_View){ .elems = buffer, .count = len };
}
void noh_string_append_sv(Noh_String *string, Noh_String_View sv) { void noh_string_append_sv(Noh_String *string, Noh_String_View sv) {
noh_da_append_multiple(string, sv.elems, sv.count); noh_da_append_multiple(string, sv.elems, sv.count);
} }
@@ -999,6 +1016,18 @@ Noh_String_View noh_sv_from_string(const Noh_String *string) {
return result; return result;
} }
int noh_sv_compare(Noh_String_View a, Noh_String_View b) {
size_t count = a.count;
if (b.count < a.count) count = b.count;
for (size_t i = 0; i < count; i++) {
if (a.elems[i] == b.elems[i]) continue;
return a.elems[i] - b.elems[i];
}
return a.count - b.count;
}
bool noh_sv_eq(Noh_String_View a, Noh_String_View b) { bool noh_sv_eq(Noh_String_View a, Noh_String_View b) {
if (a.count != b.count) return false; if (a.count != b.count) return false;