From be22cf62670b3b7e92b9c06475bbb24f93819445 Mon Sep 17 00:00:00 2001 From: apio Date: Fri, 16 Dec 2022 18:17:15 +0100 Subject: [PATCH] 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. --- luna/CMakeLists.txt | 1 + luna/include/luna/OwnedStringView.h | 27 ++++++++++++++++++++++ luna/src/OwnedStringView.cpp | 36 +++++++++++++++++++++++++++++ 3 files changed, 64 insertions(+) create mode 100644 luna/include/luna/OwnedStringView.h create mode 100644 luna/src/OwnedStringView.cpp diff --git a/luna/CMakeLists.txt b/luna/CMakeLists.txt index afdc8c8e..655dc333 100644 --- a/luna/CMakeLists.txt +++ b/luna/CMakeLists.txt @@ -9,6 +9,7 @@ set(FREESTANDING_SOURCES src/Bitmap.cpp src/Stack.cpp src/Alloc.cpp + src/OwnedStringView.cpp ) set(SOURCES diff --git a/luna/include/luna/OwnedStringView.h b/luna/include/luna/OwnedStringView.h new file mode 100644 index 00000000..4dd59332 --- /dev/null +++ b/luna/include/luna/OwnedStringView.h @@ -0,0 +1,27 @@ +#pragma once + +class OwnedStringView +{ + public: + OwnedStringView(char* c_str); + OwnedStringView(); + OwnedStringView(OwnedStringView&&); + OwnedStringView(const OwnedStringView&) = delete; + ~OwnedStringView(); + + Result clone(); + + const char* chars() + { + return m_string; + } + + usize length() + { + return m_length; + } + + private: + char* m_string{nullptr}; + usize m_length{0}; +}; \ No newline at end of file diff --git a/luna/src/OwnedStringView.cpp b/luna/src/OwnedStringView.cpp new file mode 100644 index 00000000..d81a30cf --- /dev/null +++ b/luna/src/OwnedStringView.cpp @@ -0,0 +1,36 @@ +#include +#include +#include + +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::clone() +{ + char* buf = TRY(make_array(m_length + 1)); + + memcpy(buf, m_string, m_length + 1); + + return OwnedStringView{buf}; +} \ No newline at end of file