From 42a2c2af49c9c0846ff844df1c7af3c3cce4a1b2 Mon Sep 17 00:00:00 2001 From: apio Date: Fri, 16 Dec 2022 20:37:57 +0100 Subject: [PATCH] Add strdup() --- luna/include/luna/OwnedStringView.h | 6 ++++++ luna/include/luna/String.h | 2 ++ luna/src/OwnedStringView.cpp | 8 ++++---- luna/src/String.cpp | 13 +++++++++++++ 4 files changed, 25 insertions(+), 4 deletions(-) diff --git a/luna/include/luna/OwnedStringView.h b/luna/include/luna/OwnedStringView.h index 91b78da2..b5ce7622 100644 --- a/luna/include/luna/OwnedStringView.h +++ b/luna/include/luna/OwnedStringView.h @@ -22,6 +22,12 @@ class OwnedStringView return m_length; } + const char& operator[](usize index) const + { + expect(index < m_length, "OwnedStringView: index out of range"); + return m_string[index]; + } + private: char* m_string{nullptr}; usize m_length{0}; diff --git a/luna/include/luna/String.h b/luna/include/luna/String.h index 0dddc00b..0eca451c 100644 --- a/luna/include/luna/String.h +++ b/luna/include/luna/String.h @@ -8,4 +8,6 @@ extern "C" int memcmp(const void* a, const void* b, usize n); void* memmove(void* dest, const void* src, usize n); usize strlen(const char* str); + + char* strdup(const char* str); } \ No newline at end of file diff --git a/luna/src/OwnedStringView.cpp b/luna/src/OwnedStringView.cpp index 1bf1b4ec..a904a7ca 100644 --- a/luna/src/OwnedStringView.cpp +++ b/luna/src/OwnedStringView.cpp @@ -23,14 +23,14 @@ OwnedStringView::OwnedStringView(char* c_str) OwnedStringView::~OwnedStringView() { - if (m_string) destroy_array(m_string); + if (m_string) raw_free(m_string); } Result OwnedStringView::clone() const { - char* buf = TRY(make_array(m_length + 1)); + char* const c_str = strdup(m_string); - memcpy(buf, m_string, m_length + 1); + if (!c_str) return err(ENOMEM); - return OwnedStringView{buf}; + return OwnedStringView{c_str}; } \ No newline at end of file diff --git a/luna/src/String.cpp b/luna/src/String.cpp index 85535188..70b71d4f 100644 --- a/luna/src/String.cpp +++ b/luna/src/String.cpp @@ -1,3 +1,4 @@ +#include #include extern "C" @@ -44,4 +45,16 @@ extern "C" ; return (usize)(i - str); } + + char* strdup(const char* str) + { + const usize len = strlen(str); + + char* dest = (char*)raw_malloc(len + 1); + if (!dest) return nullptr; + + memcpy(dest, str, len + 1); + + return dest; + } } \ No newline at end of file