From 12d2039f683a0c00722dd76116b5e2df87a20f2a Mon Sep 17 00:00:00 2001 From: apio Date: Sun, 22 Jan 2023 11:27:37 +0100 Subject: [PATCH] CString: Add strnlen() and strndup() --- luna/include/luna/CString.h | 4 ++++ luna/src/CString.cpp | 24 ++++++++++++++++++++++-- 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/luna/include/luna/CString.h b/luna/include/luna/CString.h index 68bc930f..db7991d9 100644 --- a/luna/include/luna/CString.h +++ b/luna/include/luna/CString.h @@ -7,12 +7,16 @@ extern "C" void* memset(void* buf, int c, usize n); int memcmp(const void* a, const void* b, usize n); void* memmove(void* dest, const void* src, usize n); + usize strlen(const char* str); + usize strnlen(const char* str, usize max); + int strcmp(const char* a, const char* b); usize wcslen(const wchar_t* str); char* strdup(const char* str); + char* strndup(const char* str, usize max); // Copies len bytes from src into dest and adds a null terminator. // FIXME: Replace this invented function with strlcpy(). diff --git a/luna/src/CString.cpp b/luna/src/CString.cpp index 1fbb41d2..b853c471 100644 --- a/luna/src/CString.cpp +++ b/luna/src/CString.cpp @@ -46,6 +46,14 @@ extern "C" return (usize)(i - str); } + usize strnlen(const char* str, usize max) + { + const char* i = str; + for (; max, *i; ++i, --max) + ; + return (usize)(i - str); + } + int strcmp(const char* a, const char* b) { while (*a && (*a == *b)) @@ -68,10 +76,22 @@ extern "C" { const usize len = strlen(str); - char* dest = (char*)malloc_impl(len + 1).value_or(nullptr); + char* dest = (char*)calloc_impl(len + 1, 1).value_or(nullptr); if (!dest) return nullptr; - memcpy(dest, str, len + 1); + memcpy(dest, str, len); + + return dest; + } + + char* strndup(const char* str, usize max) + { + const usize len = strnlen(str, max); + + char* dest = (char*)calloc_impl(len + 1, 1).value_or(nullptr); + if (!dest) return nullptr; + + memcpy(dest, str, len); return dest; }