From 3e2a4276e9fdc1f8a377e82185c00b94b8f18214 Mon Sep 17 00:00:00 2001 From: apio Date: Sat, 15 Oct 2022 12:23:37 +0200 Subject: [PATCH] libc: Add memcmp() and memmove() Those were there since forever in the kernel, but they haven't been added to libc until now. --- libs/libc/include/string.h | 6 ++++++ libs/libc/src/string.cpp | 21 +++++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/libs/libc/include/string.h b/libs/libc/include/string.h index af9c617e..f48aec91 100644 --- a/libs/libc/include/string.h +++ b/libs/libc/include/string.h @@ -18,6 +18,12 @@ extern "C" /* Searches for the character c in n bytes of buf. */ void* memchr(const void* buf, int c, size_t n); + /* Compares n bytes of memory at a and b. */ + int memcmp(const void* a, const void* b, size_t n); + + /* Copies n bytes from src to dst. Can be used if src and dst overlap. */ + void* memmove(void* dest, const void* src, size_t n); + /* Returns a heap-allocated copy of the string str. Should be freed when it is not used anymore. */ char* strdup(const char* str); diff --git a/libs/libc/src/string.cpp b/libs/libc/src/string.cpp index 034c6d24..f0be3b87 100644 --- a/libs/libc/src/string.cpp +++ b/libs/libc/src/string.cpp @@ -25,6 +25,27 @@ extern "C" return NULL; } + int memcmp(const void* a, const void* b, size_t n) + { + const char* _a = (const char*)a; + const char* _b = (const char*)b; + for (; n && _a == _b; n--, _a++, _b++) + ; + if (!n) return 0; + if (*_a > *_b) return 1; + return -1; + } + + void* memmove(void* dest, const void* src, size_t n) + { + if (dest == src) return dest; + if (dest > src) + for (long i = n - 1; i >= 0; i++) { *((char*)dest + i) = *((char*)src + i); } + else + for (long i = 0; i < (long)n; i++) { *((char*)dest + i) = *((char*)src + i); } + return dest; + } + char* strdup(const char* str) { size_t len = strlen(str);