From 0ca1df4dc64abab33b1b26eac81691f56ad81683 Mon Sep 17 00:00:00 2001 From: Tim Schumacher Date: Wed, 22 Sep 2021 08:56:34 +0000 Subject: [PATCH] LibC: Implement wmemchr --- Tests/LibC/TestWchar.cpp | 32 +++++++++++++++++++++++++++++++ Userland/Libraries/LibC/wchar.cpp | 10 ++++++++++ Userland/Libraries/LibC/wchar.h | 1 + 3 files changed, 43 insertions(+) diff --git a/Tests/LibC/TestWchar.cpp b/Tests/LibC/TestWchar.cpp index 949d9ad83c..82e658366a 100644 --- a/Tests/LibC/TestWchar.cpp +++ b/Tests/LibC/TestWchar.cpp @@ -65,6 +65,38 @@ TEST_CASE(wcsstr) EXPECT_EQ(ret, nullptr); } +TEST_CASE(wmemchr) +{ + const wchar_t* input = L"abcde"; + wchar_t* ret; + + // Empty haystack returns nothing. + ret = wmemchr(L"", L'c', 0); + EXPECT_EQ(ret, nullptr); + + // Not included character returns nothing. + ret = wmemchr(input, L'z', 5); + EXPECT_EQ(ret, nullptr); + + // Match at string start. + ret = wmemchr(input, L'a', 5); + EXPECT_EQ(ret, input); + + // Match at string end. + ret = wmemchr(input, L'e', 5); + EXPECT_EQ(ret, input + 4); + + input = L"abcde\0fg"; + + // Handle finding null characters. + ret = wmemchr(input, L'\0', 8); + EXPECT_EQ(ret, input + 5); + + // Don't stop at null characters. + ret = wmemchr(input, L'f', 8); + EXPECT_EQ(ret, input + 6); +} + TEST_CASE(wcscoll) { // Check if wcscoll is sorting correctly. At the moment we are doing raw char comparisons, diff --git a/Userland/Libraries/LibC/wchar.cpp b/Userland/Libraries/LibC/wchar.cpp index db255185af..a3927111d3 100644 --- a/Userland/Libraries/LibC/wchar.cpp +++ b/Userland/Libraries/LibC/wchar.cpp @@ -375,4 +375,14 @@ wchar_t* wcsstr(const wchar_t* haystack, const wchar_t* needle) return nullptr; } + +wchar_t* wmemchr(const wchar_t* s, wchar_t c, size_t n) +{ + for (size_t i = 0; i < n; i++) { + if (s[i] == c) + return const_cast(&s[i]); + } + + return nullptr; +} } diff --git a/Userland/Libraries/LibC/wchar.h b/Userland/Libraries/LibC/wchar.h index 70ea7006a8..5ec7f9e253 100644 --- a/Userland/Libraries/LibC/wchar.h +++ b/Userland/Libraries/LibC/wchar.h @@ -43,5 +43,6 @@ int wctob(wint_t); int mbsinit(const mbstate_t*); wchar_t* wcspbrk(const wchar_t*, const wchar_t*); wchar_t* wcsstr(const wchar_t*, const wchar_t*); +wchar_t* wmemchr(const wchar_t*, wchar_t, size_t); __END_DECLS