StringView: Add split_once and to_uint

This commit is contained in:
apio 2023-04-20 20:08:34 +02:00
parent eb58b4acc8
commit fb79e12248
Signed by: apio
GPG Key ID: B8A7D06E42258954
3 changed files with 46 additions and 4 deletions

View File

@ -27,6 +27,10 @@ class String
Result<String> substring(usize begin, usize size) const;
Result<Vector<String>> split(StringView delim) const;
Result<Vector<String>> split_once(char delim) const
{
return view().split_once(delim);
}
static Result<String> format(const String& fmt, ...);
static Result<String> format(StringView fmt, ...);

View File

@ -41,6 +41,9 @@ class StringView
bool operator==(StringView other) const;
Result<Vector<String>> split(StringView delim) const;
Result<Vector<String>> split_once(char delim) const;
Result<usize> to_uint() const;
Iterator begin() const
{

View File

@ -1,4 +1,6 @@
#include <luna/CString.h>
#include <luna/NumberParsing.h>
#include <luna/ScopeGuard.h>
#include <luna/String.h>
#include <luna/StringView.h>
@ -62,9 +64,10 @@ Result<Vector<String>> StringView::split(StringView delim) const
String str;
char* copy = strndup(m_string, m_length);
auto guard = make_scope_guard([copy] { free_impl(copy); });
char* segment = strtok(copy, delim.chars());
if (!segment) goto end;
if (!segment) return result;
str = TRY(String::from_cstring(segment));
TRY(result.try_append(move(str)));
@ -72,14 +75,46 @@ Result<Vector<String>> StringView::split(StringView delim) const
while (true)
{
segment = strtok(nullptr, delim.chars());
if (!segment) goto end;
if (!segment) return result;
str = TRY(String::from_cstring(segment));
TRY(result.try_append(move(str)));
}
end:
free_impl(copy);
return result;
}
Result<Vector<String>> StringView::split_once(char delim) const
{
Vector<String> result;
char* copy = strndup(m_string, m_length);
auto guard = make_scope_guard([copy] { free_impl(copy); });
char* middle = strchr(copy, delim);
if (!middle)
{
auto str = TRY(String::from_cstring(copy));
TRY(result.try_append(move(str)));
return result;
}
*middle = '\0';
auto begin = TRY(String::from_cstring(copy));
auto end = TRY(String::from_cstring(middle + 1));
TRY(result.try_append(move(begin)));
TRY(result.try_append(move(end)));
return result;
}
Result<usize> StringView::to_uint() const
{
const char* endptr = nullptr;
auto result = parse_unsigned_integer(m_string, &endptr, 0);
if (endptr == m_string) return err(EINVAL);
return result;
}