Add strdup()

This commit is contained in:
apio 2022-12-16 20:37:57 +01:00
parent e56075fb46
commit 42a2c2af49
Signed by: apio
GPG Key ID: B8A7D06E42258954
4 changed files with 25 additions and 4 deletions

View File

@ -22,6 +22,12 @@ class OwnedStringView
return m_length; return m_length;
} }
const char& operator[](usize index) const
{
expect(index < m_length, "OwnedStringView: index out of range");
return m_string[index];
}
private: private:
char* m_string{nullptr}; char* m_string{nullptr};
usize m_length{0}; usize m_length{0};

View File

@ -8,4 +8,6 @@ extern "C"
int memcmp(const void* a, const void* b, usize n); int memcmp(const void* a, const void* b, usize n);
void* memmove(void* dest, const void* src, usize n); void* memmove(void* dest, const void* src, usize n);
usize strlen(const char* str); usize strlen(const char* str);
char* strdup(const char* str);
} }

View File

@ -23,14 +23,14 @@ OwnedStringView::OwnedStringView(char* c_str)
OwnedStringView::~OwnedStringView() OwnedStringView::~OwnedStringView()
{ {
if (m_string) destroy_array(m_string); if (m_string) raw_free(m_string);
} }
Result<OwnedStringView> OwnedStringView::clone() const Result<OwnedStringView> OwnedStringView::clone() const
{ {
char* buf = TRY(make_array<char>(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};
} }

View File

@ -1,3 +1,4 @@
#include <luna/Alloc.h>
#include <luna/String.h> #include <luna/String.h>
extern "C" extern "C"
@ -44,4 +45,16 @@ extern "C"
; ;
return (usize)(i - str); 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;
}
} }