80 lines
1.5 KiB
C++
80 lines
1.5 KiB
C++
#include <luna/CString.h>
|
|
#include <luna/String.h>
|
|
#include <luna/StringView.h>
|
|
|
|
static const char* empty = "";
|
|
|
|
StringView::StringView()
|
|
{
|
|
m_string = empty;
|
|
m_length = 0;
|
|
}
|
|
|
|
StringView::StringView(const StringView& other)
|
|
{
|
|
m_string = other.m_string;
|
|
m_length = other.m_length;
|
|
}
|
|
|
|
StringView::StringView(const char* c_str)
|
|
{
|
|
check(c_str);
|
|
m_string = c_str;
|
|
m_length = strlen(m_string);
|
|
}
|
|
|
|
StringView::StringView(const char* c_str, usize length)
|
|
{
|
|
check(c_str);
|
|
m_string = c_str;
|
|
m_length = length;
|
|
}
|
|
|
|
const char& StringView::operator[](usize index) const
|
|
{
|
|
expect(index < m_length, "index out of range");
|
|
return m_string[index];
|
|
}
|
|
|
|
bool StringView::operator==(const char* other) const
|
|
{
|
|
return !strcmp(m_string, other);
|
|
}
|
|
|
|
bool StringView::operator==(StringView other) const
|
|
{
|
|
return !strcmp(m_string, other.m_string);
|
|
}
|
|
|
|
Result<Vector<String>> StringView::split(StringView delim) const
|
|
{
|
|
Vector<String> result;
|
|
String str;
|
|
|
|
char* copy = strndup(m_string, m_length);
|
|
|
|
char* segment = strtok(copy, delim.chars());
|
|
if (!segment) goto end;
|
|
|
|
str = TRY(String::from_cstring(segment));
|
|
TRY(result.try_append(move(str)));
|
|
|
|
while (true)
|
|
{
|
|
segment = strtok(nullptr, delim.chars());
|
|
if (!segment) goto end;
|
|
|
|
str = TRY(String::from_cstring(segment));
|
|
TRY(result.try_append(move(str)));
|
|
}
|
|
|
|
end:
|
|
free_impl(copy);
|
|
return result;
|
|
}
|
|
|
|
Result<String> StringView::to_string()
|
|
{
|
|
return String::from_cstring(m_string);
|
|
}
|