Introduce OwnedStringView

A managed String which uses RAII to free its contents. It's not a proper string though, since it's read-only.
So it's a StringView... but an owned one.

Can't be copied automatically, must be either moved or copied manually by calling clone() on it.
This commit is contained in:
apio 2022-12-16 18:17:15 +01:00
parent d759058b80
commit be22cf6267
Signed by: apio
GPG Key ID: B8A7D06E42258954
3 changed files with 64 additions and 0 deletions

View File

@ -9,6 +9,7 @@ set(FREESTANDING_SOURCES
src/Bitmap.cpp
src/Stack.cpp
src/Alloc.cpp
src/OwnedStringView.cpp
)
set(SOURCES

View File

@ -0,0 +1,27 @@
#pragma once
class OwnedStringView
{
public:
OwnedStringView(char* c_str);
OwnedStringView();
OwnedStringView(OwnedStringView&&);
OwnedStringView(const OwnedStringView&) = delete;
~OwnedStringView();
Result<OwnedStringView> clone();
const char* chars()
{
return m_string;
}
usize length()
{
return m_length;
}
private:
char* m_string{nullptr};
usize m_length{0};
};

View File

@ -0,0 +1,36 @@
#include <luna/Alloc.h>
#include <luna/OwnedStringView.h>
#include <luna/String.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()
{
if (m_string) destroy_array(m_string);
}
Result<OwnedStringView> OwnedStringView::clone()
{
char* buf = TRY(make_array<char>(m_length + 1));
memcpy(buf, m_string, m_length + 1);
return OwnedStringView{buf};
}