More functional-style stringview functions

This commit is contained in:
VegOwOtenks 2024-10-01 11:06:04 +02:00
parent baa4a148fe
commit 7d8ba6fc28
2 changed files with 36 additions and 0 deletions

View file

@ -119,6 +119,24 @@ StringView StringView_FindString(StringView haystack, StringView needle)
return (StringView) {NULL, 0};
}
StringView StringView_Drop(StringView string, size_t length)
{
return StringView_Slice(string, length, string.length);
}
StringView StringView_TakeWhile(StringView string, StringViewContinue function)
{
size_t length = 0;
for (length = 0; string.length != length && function(string.source[length]); length++);
return StringView_Take(string, length);
}
StringView StringView_Take(StringView string, size_t length)
{
return StringView_Slice(string, 0, length);
}
StringView StringView_Slice(StringView string, size_t start, size_t end)
{
if (end > string.length || start > string.length) {
@ -200,6 +218,16 @@ StringView StringView_StripRight(StringView sv, StringView strip)
return sv;
}
void* StringView_FoldLeft(StringView string, void* initial, StringViewFoldFunction function)
{
void* value = initial;
while (string.length != 0) {
value = function(string.source[0], value);
string = StringView_Drop(string, 1);
}
return value;
}
void StringView_Paste(char* destination, StringView source)
{

View file

@ -44,7 +44,12 @@ size_t StringView_Count(StringView string, StringView find);
size_t StringView_FindStringOffset(StringView haystack, StringView needle);
StringView StringView_FindString(StringView haystack, StringView needle);
typedef bool (*StringViewContinue) (char);
StringView StringView_Slice(StringView string, size_t start, size_t end); // start and end are offsets
StringView StringView_Drop(StringView string, size_t length);
StringView StringView_Take(StringView string, size_t length);
StringView StringView_TakeWhile(StringView string, StringViewContinue function);
bool StringView_Partition(StringView* left, StringView* right, StringView source, StringView delim);
bool StringView_NextSplit(StringView* dest, StringView* source, StringView delim);
@ -53,6 +58,9 @@ bool StringView_LastSplit(StringView* dest, StringView* source, StringView delim
StringView StringView_StripLeft(StringView sv, StringView strip);
StringView StringView_StripRight(StringView sv, StringView strip);
typedef void* (*StringViewFoldFunction) (char, void*);
void* StringView_FoldLeft(StringView string, void* initial, StringViewFoldFunction function);
void StringView_Paste(char* destination, StringView source);
int StringView_ParseInt(StringView source);