diff options
| author | Clement Sibille <clements+git@lisible.xyz> | 2024-05-19 23:33:44 +0900 |
|---|---|---|
| committer | Clement Sibille <clements+git@lisible.xyz> | 2024-05-19 23:33:44 +0900 |
| commit | 399be44fbc3767e7c1ff505119f9e07ee25b1078 (patch) | |
| tree | ff51f3967754aa91577292ead342e8c9348f2c7c /src/lisiblestd/string.c | |
| parent | 5a26e1f481fe85f08093a414e27c1056b85c6715 (diff) | |
Add String_eq and update the String API
Diffstat (limited to 'src/lisiblestd/string.c')
| -rw-r--r-- | src/lisiblestd/string.c | 32 |
1 files changed, 23 insertions, 9 deletions
diff --git a/src/lisiblestd/string.c b/src/lisiblestd/string.c index 3de3272..2b191b2 100644 --- a/src/lisiblestd/string.c +++ b/src/lisiblestd/string.c @@ -4,21 +4,18 @@ #include <string.h> -bool String_from_str(Allocator *allocator, String *string, const char *str) { +String String_new(Allocator *allocator, const char *str) { LSTD_ASSERT(allocator != NULL); - LSTD_ASSERT(string != NULL); LSTD_ASSERT(str != NULL); usize length = strlen(str); - char *value = Allocator_allocate_array(allocator, length + 1, sizeof(char)); - if (!value) { - return false; - } + char *value = Allocator_allocate(allocator, length + 1); + LSTD_ASSERT(value != NULL); + + strncpy(value, str, length); value[length] = '\0'; - string->value = value; - string->length = length; - return true; + return (String){.value = value, .length = length}; } void String_destroy(Allocator *allocator, String *string) { @@ -27,7 +24,24 @@ void String_destroy(Allocator *allocator, String *string) { Allocator_free(allocator, string->value); } +bool String_eq(const String *lhs, const String *rhs) { + if (lhs == NULL || rhs == NULL || lhs->length != rhs->length) { + return false; + } + + return strncmp(lhs->value, rhs->value, lhs->length) == 0; +} + +StringView String_view(const String *str) { + return (StringView){.value = str->value, .length = str->length}; +} + usize String_length(const String *string) { LSTD_ASSERT(string != NULL); return string->length; } + +StringView StringView_from_str(const char *data) { + LSTD_ASSERT(data != NULL); + return (StringView){.value = data, .length = strlen(data)}; +} |
