From e8b9376573a1defbdc5ba496523c9e94031818a5 Mon Sep 17 00:00:00 2001 From: Danny Holman Date: Fri, 16 Feb 2024 12:39:37 -0600 Subject: kernel: string: add more functions to string library Add more functions to the string library to process buffers and strings. Signed-off-by: Danny Holman --- include/kernel/string.h | 5 ++++ kernel/string.c | 64 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+) diff --git a/include/kernel/string.h b/include/kernel/string.h index 8761211..f9a8eed 100644 --- a/include/kernel/string.h +++ b/include/kernel/string.h @@ -7,6 +7,11 @@ int memcmp(const void *str1, const void *str2, size_t n); void* memcpy(void* __restrict dest, const void* __restrict src, size_t n); void* memmove(void* __restrict dest, const void* __restrict src, size_t n); void* memset(void *str, int c, size_t n); +int strncmp(const char *str1, const char *str2, size_t n); +int strcmp(const char *str1, const char *str2); size_t strlen(const char *str); +char* strcpy(char* __restrict dest, const char* __restrict src); +char* strcat(char* __restrict dest, const char* __restrict src); +char* strtok(char* __restrict str, const char* __restrict delim); #endif diff --git a/kernel/string.c b/kernel/string.c index 30fe40d..35dc16e 100644 --- a/kernel/string.c +++ b/kernel/string.c @@ -31,6 +31,16 @@ void* memcpy(void* __restrict dest, const void* __restrict src, size_t n) { return dest; } +char* strcpy(char* __restrict dest, const char* __restrict src) { + if (strlen(src) > strlen(dest)) + return NULL; + return (char*)memcpy(dest, src, strlen(src)); +} + +char* strcat(char* __restrict dest, const char* __restrict src) { + return (char*)memcpy(&dest[strlen(dest)], src, strlen(src)); +} + void* memmove(void* __restrict dest, const void* __restrict src, size_t n) { if (dest == src) return dest; @@ -50,9 +60,63 @@ void* memset(void *str, int c, size_t n) { return str; } +int strncmp(const char *str1, const char *str2, size_t n) { + return memcmp(str1, str2, n); +} + +int strcmp(const char *str1, const char *str2) { + size_t str1_sz = strlen(str1); + size_t str2_sz = strlen(str2); + if (str1_sz > str2_sz) + return memcmp(str1, str2, str2_sz); + return memcmp(str1, str2, str1_sz); +} + size_t strlen(const char *str) { size_t i = 0; while (str[i] != '\0') i++; return i; } + +int _is_delim(char c, const char *delim) { + while (*delim != '\0') { + if (c == *delim) + return 1; + delim++; + } + return 0; +} + +char* strtok(char* __restrict str, const char* __restrict delim) { + static char *old_str; + + if (str == NULL) + str = old_str; + + while (1) { + if (_is_delim(*str, delim)) { + str++; + continue; + } + + if (*str == '\0') + return NULL; + break; + } + + char *ret = str; + while (1) { + if (*str == '\0') { + old_str = str; + return ret; + } + + if (_is_delim(*str, delim)) { + *str = '\0'; + old_str = str + 1; + return ret; + } + str++; + } +} -- cgit v1.2.3