From 1f5f6a5e3b5b43fa3809bde7cc40ac5c227cfe45 Mon Sep 17 00:00:00 2001 From: apio Date: Sat, 22 Oct 2022 11:57:25 +0200 Subject: [PATCH] libc: Add strcspn (with a test) --- libs/libc/include/string.h | 3 +++ libs/libc/src/string.cpp | 16 ++++++++++++++++ tests/libc/Test.c | 2 ++ tests/libc/string.c | 19 +++++++++++++++++++ 4 files changed, 40 insertions(+) diff --git a/libs/libc/include/string.h b/libs/libc/include/string.h index 6dddf2f3..86fd2352 100644 --- a/libs/libc/include/string.h +++ b/libs/libc/include/string.h @@ -48,6 +48,9 @@ extern "C" /* Concatenates at most max bytes of the string src into dest. */ char* strncat(char* dest, const char* src, size_t max); + /* Returns the length of the initial segment of str which consists entirely of bytes not in reject. */ + size_t strcspn(const char* str, const char* reject); + /* Compares strings a and b. You might prefer to use the safer strncmp function. */ int strcmp(const char* a, const char* b); diff --git a/libs/libc/src/string.cpp b/libs/libc/src/string.cpp index 01ee75ed..6d41c66f 100644 --- a/libs/libc/src/string.cpp +++ b/libs/libc/src/string.cpp @@ -119,6 +119,22 @@ extern "C" return *(const unsigned char*)a - *(const unsigned char*)b; } + size_t strcspn(const char* str, const char* reject) + { + const char* s = str; + while (*s) + { + const char* rp = reject; + while (*rp) + { + if (*s == *rp) return s - str; + rp++; + } + s++; + } + return s - str; + } + char* strcat(char* dest, const char* src) { size_t dest_len = strlen(dest); diff --git a/tests/libc/Test.c b/tests/libc/Test.c index 517c5e9a..e62efc9c 100644 --- a/tests/libc/Test.c +++ b/tests/libc/Test.c @@ -2,10 +2,12 @@ DEFINE_TEST(strlen); DEFINE_TEST(strnlen); +DEFINE_TEST(strcspn); int main() { START_TEST_CASE(string.h); RUN_TEST(strlen); RUN_TEST(strnlen); + RUN_TEST(strcspn); } \ No newline at end of file diff --git a/tests/libc/string.c b/tests/libc/string.c index f3d1bf2f..1deed45f 100644 --- a/tests/libc/string.c +++ b/tests/libc/string.c @@ -40,5 +40,24 @@ DEFINE_TEST(strnlen) EXPECT_EQ(len, sizeof(buf)); + TEST_SUCCESS(); +} + +DEFINE_TEST(strcspn) +{ + START_TEST(strcspn); + + const char* str = "This string has vowels"; + const char* vowels = "aeiou"; + + size_t len = strcspn(str, vowels); + + EXPECT_EQ(len, 2); + + str = "WWWWW"; + len = strcspn(str, vowels); + + EXPECT_EQ(len, 5); + TEST_SUCCESS(); } \ No newline at end of file