OwnedStringView: Add a method to extract a substring
Some checks failed
continuous-integration/drone/push Build is failing

This commit is contained in:
apio 2023-01-22 11:27:54 +01:00
parent 12d2039f68
commit cf8d3c6ff9
Signed by: apio
GPG Key ID: B8A7D06E42258954
2 changed files with 17 additions and 0 deletions

View File

@ -5,6 +5,7 @@ class OwnedStringView
{ {
public: public:
OwnedStringView(char* c_str); OwnedStringView(char* c_str);
OwnedStringView(char* c_str, usize length);
OwnedStringView(); OwnedStringView();
OwnedStringView(OwnedStringView&&); OwnedStringView(OwnedStringView&&);
OwnedStringView(const OwnedStringView&) = delete; OwnedStringView(const OwnedStringView&) = delete;
@ -12,6 +13,8 @@ class OwnedStringView
Result<OwnedStringView> clone() const; Result<OwnedStringView> clone() const;
Result<OwnedStringView> substring(usize begin, usize size) const;
static Result<OwnedStringView> from_string_literal(const char* str); static Result<OwnedStringView> from_string_literal(const char* str);
const char* chars() const const char* chars() const

View File

@ -21,6 +21,12 @@ OwnedStringView::OwnedStringView(char* c_str)
if (m_string) { m_length = strlen(m_string); } if (m_string) { m_length = strlen(m_string); }
} }
OwnedStringView::OwnedStringView(char* c_str, usize length)
{
m_string = c_str;
m_length = length;
}
OwnedStringView::~OwnedStringView() OwnedStringView::~OwnedStringView()
{ {
if (m_string) free_impl(m_string); if (m_string) free_impl(m_string);
@ -31,6 +37,14 @@ Result<OwnedStringView> OwnedStringView::clone() const
return from_string_literal(m_string); 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 const char& OwnedStringView::operator[](usize index) const
{ {
expect(index < m_length, "index out of range"); expect(index < m_length, "index out of range");