Skip to content

Commit

Permalink
LibC: Implement wcsstr
Browse files Browse the repository at this point in the history
  • Loading branch information
timschumi authored and bgianfo committed Oct 3, 2021
1 parent 1b078f8 commit 5ac2e84
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 0 deletions.
30 changes: 30 additions & 0 deletions Tests/LibC/TestWchar.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,36 @@ TEST_CASE(wcspbrk)
EXPECT_EQ(ret, input + 2);
}

TEST_CASE(wcsstr)
{
const wchar_t* input = L"abcde";
wchar_t* ret;

// Empty needle should return haystack.
ret = wcsstr(input, L"");
EXPECT_EQ(ret, input);

// Test exact match.
ret = wcsstr(input, input);
EXPECT_EQ(ret, input);

// Test match at string start.
ret = wcsstr(input, L"ab");
EXPECT_EQ(ret, input);

// Test match at string end.
ret = wcsstr(input, L"de");
EXPECT_EQ(ret, input + 3);

// Test no match.
ret = wcsstr(input, L"z");
EXPECT_EQ(ret, nullptr);

// Test needle that is longer than the haystack.
ret = wcsstr(input, L"abcdef");
EXPECT_EQ(ret, nullptr);
}

TEST_CASE(wcscoll)
{
// Check if wcscoll is sorting correctly. At the moment we are doing raw char comparisons,
Expand Down
20 changes: 20 additions & 0 deletions Userland/Libraries/LibC/wchar.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -355,4 +355,24 @@ wchar_t* wcspbrk(const wchar_t* wcs, const wchar_t* accept)

return nullptr;
}

wchar_t* wcsstr(const wchar_t* haystack, const wchar_t* needle)
{
size_t nlen = wcslen(needle);

if (nlen == 0)
return const_cast<wchar_t*>(haystack);

size_t hlen = wcslen(haystack);

while (hlen >= nlen) {
if (wcsncmp(haystack, needle, nlen) == 0)
return const_cast<wchar_t*>(haystack);

haystack++;
hlen--;
}

return nullptr;
}
}
1 change: 1 addition & 0 deletions Userland/Libraries/LibC/wchar.h
Original file line number Diff line number Diff line change
Expand Up @@ -42,5 +42,6 @@ int wcscoll(const wchar_t*, const wchar_t*);
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*);

__END_DECLS

0 comments on commit 5ac2e84

Please sign in to comment.