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:
parent
d759058b80
commit
be22cf6267
@ -9,6 +9,7 @@ set(FREESTANDING_SOURCES
|
||||
src/Bitmap.cpp
|
||||
src/Stack.cpp
|
||||
src/Alloc.cpp
|
||||
src/OwnedStringView.cpp
|
||||
)
|
||||
|
||||
set(SOURCES
|
||||
|
27
luna/include/luna/OwnedStringView.h
Normal file
27
luna/include/luna/OwnedStringView.h
Normal 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};
|
||||
};
|
36
luna/src/OwnedStringView.cpp
Normal file
36
luna/src/OwnedStringView.cpp
Normal 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};
|
||||
}
|
Loading…
Reference in New Issue
Block a user