Add strdup()
This commit is contained in:
parent
e56075fb46
commit
42a2c2af49
@ -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};
|
||||
|
@ -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);
|
||||
}
|
@ -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> 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};
|
||||
}
|
@ -1,3 +1,4 @@
|
||||
#include <luna/Alloc.h>
|
||||
#include <luna/String.h>
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user