60 lines
1.3 KiB
C++
60 lines
1.3 KiB
C++
#include <luna/Alloc.h>
|
|
#include <luna/CString.h>
|
|
#include <luna/OwnedStringView.h>
|
|
|
|
OwnedStringView::OwnedStringView()
|
|
{
|
|
}
|
|
|
|
OwnedStringView::OwnedStringView(OwnedStringView&& other)
|
|
{
|
|
m_string = other.m_string;
|
|
m_length = other.m_length;
|
|
|
|
other.m_string = nullptr;
|
|
}
|
|
|
|
OwnedStringView::OwnedStringView(char* c_str)
|
|
{
|
|
m_string = c_str;
|
|
|
|
if (m_string) { m_length = strlen(m_string); }
|
|
}
|
|
|
|
OwnedStringView::OwnedStringView(char* c_str, usize length)
|
|
{
|
|
m_string = c_str;
|
|
m_length = length;
|
|
}
|
|
|
|
OwnedStringView::~OwnedStringView()
|
|
{
|
|
if (m_string) free_impl(m_string);
|
|
}
|
|
|
|
Result<OwnedStringView> OwnedStringView::clone() const
|
|
{
|
|
return from_string_literal(m_string);
|
|
}
|
|
|
|
Result<OwnedStringView> OwnedStringView::substring(usize begin, usize size) const
|
|
{
|
|
if (begin + size >= size) return err(EINVAL);
|
|
char* const dup = strndup(m_string + begin, size);
|
|
if (!dup) return err(ENOMEM);
|
|
return OwnedStringView { dup, size };
|
|
}
|
|
|
|
const char& OwnedStringView::operator[](usize index) const
|
|
{
|
|
expect(index < m_length, "index out of range");
|
|
return m_string[index];
|
|
}
|
|
|
|
Result<OwnedStringView> OwnedStringView::from_string_literal(const char* str)
|
|
{
|
|
char* const dup = strdup(str);
|
|
if (!dup) return err(ENOMEM);
|
|
return OwnedStringView { dup };
|
|
}
|