From 14a681c53eafebcf8a7c68fe2e2974262333057b Mon Sep 17 00:00:00 2001 From: Michael Shaw Date: Tue, 9 May 2023 23:00:07 -0400 Subject: [PATCH] string: add strsplit --- Makefile | 2 +- include/stdio.h | 2 +- include/string.h | 1 + lib/stdio.c | 2 +- lib/string.c | 41 +++++++++++++++++++++++++++++++++++++++++ 5 files changed, 45 insertions(+), 3 deletions(-) diff --git a/Makefile b/Makefile index 540eafa..82d6e7c 100644 --- a/Makefile +++ b/Makefile @@ -16,7 +16,7 @@ define DEFAULT_VAR = endef # User controllable CFLAGS. -CFLAGS ?= -g -O0 -pipe -Wall -Wextra +CFLAGS ?= -g -O2 -pipe -Wall -Wextra # User controllable linker flags. We set none by default. LDFLAGS ?= diff --git a/include/stdio.h b/include/stdio.h index 9fa1b79..b25219b 100644 --- a/include/stdio.h +++ b/include/stdio.h @@ -16,6 +16,6 @@ #define LOG_INFO "[LOG] " int printf(const char *restrict fmt, ...); -int snprintf(char *str, char *restrict fmt, size_t size, ...); +int snprintf(char *str, const char *restrict fmt, size_t size, ...); #endif /* _SDTIO_H_ */ diff --git a/include/string.h b/include/string.h index 41a1430..65d6556 100644 --- a/include/string.h +++ b/include/string.h @@ -10,6 +10,7 @@ void *memcpy(void *dest, const void *src, size_t num); int memcmp(const void *aa, const void *bb, size_t num); void *memset(void *str, int c, size_t n); char *strcpy(char *dest, const char *src); +char **strsplit(const char *str, char delim, int *num); size_t strlen(const char *c); int atoi(const char *a); diff --git a/lib/stdio.c b/lib/stdio.c index 5677201..cd7dafb 100644 --- a/lib/stdio.c +++ b/lib/stdio.c @@ -21,7 +21,7 @@ static int printf_write(const char *restrict s) } /* this is seriously the approach i'm going with for now */ -int snprintf(char *str, char *restrict fmt, size_t size, ...) +int snprintf(char *str, const char *restrict fmt, size_t size, ...) { int ret = 0; char c; diff --git a/lib/string.c b/lib/string.c index d7ae83e..5c8e414 100644 --- a/lib/string.c +++ b/lib/string.c @@ -1,5 +1,6 @@ /* SPDX-License-Identifier: GPL-2.0-only */ #include +#include void *memcpy(void *dest, const void *src, size_t num) { @@ -74,3 +75,43 @@ int atoi(const char *a) } return ret; } + +char *strchr(const char *s, int c) +{ + while (*s) { + if (*s == c) + return (char *)s; + s++; + } + return NULL; +} + +char **strsplit(const char *s, char delim, int *n) +{ + int num = 0; + for (int i = 0; s[i]; i++) { + if (s[i] == delim) + num++; + } + + char **ret = kmalloc((num + 2) * sizeof(char *), ALLOC_KERN); + int idx = 0; + int last = 0; + for (int i = 0; s[i]; i++) { + if (s[i] == delim) { + ret[idx] = kmalloc(i - last + 1, ALLOC_KERN); + memcpy(ret[idx], s + last, i - last); + ret[idx][i - last] = 0; + idx++; + last = i + 1; + } + } + ret[idx] = kmalloc(strlen(s) - last + 1, ALLOC_KERN); + memcpy(ret[idx], s + last, strlen(s) - last); + ret[idx][strlen(s) - last] = 0; + idx++; + ret[idx] = NULL; + if (n) + *n = idx; + return ret; +}