Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 9 additions & 9 deletions libc/src/string/string_utils.h
Original file line number Diff line number Diff line change
Expand Up @@ -127,27 +127,27 @@ find_first_character_wide_read(const unsigned char *src, unsigned char ch,
size_t cur = 0;

// Step 1: read 1 byte at a time to align to block size
for (; reinterpret_cast<uintptr_t>(char_ptr) % sizeof(Word) != 0 && cur < n;
++char_ptr, ++cur) {
for (; cur < n && reinterpret_cast<uintptr_t>(char_ptr) % sizeof(Word) != 0;
++cur, ++char_ptr) {
if (*char_ptr == ch)
return const_cast<unsigned char *>(char_ptr);
}

const Word ch_mask = repeat_byte<Word>(ch);

// Step 2: read blocks
for (const Word *block_ptr = reinterpret_cast<const Word *>(char_ptr);
!has_zeroes<Word>((*block_ptr) ^ ch_mask) && cur < n;
++block_ptr, cur += sizeof(Word)) {
char_ptr = reinterpret_cast<const unsigned char *>(block_ptr);
}
const Word *block_ptr = reinterpret_cast<const Word *>(char_ptr);
for (; cur < n && !has_zeroes<Word>((*block_ptr) ^ ch_mask);
cur += sizeof(Word), ++block_ptr)
;
char_ptr = reinterpret_cast<const unsigned char *>(block_ptr);

// Step 3: find the match in the block
for (; *char_ptr != ch && cur < n; ++char_ptr, ++cur) {
for (; cur < n && *char_ptr != ch; ++cur, ++char_ptr) {
;
}

if (*char_ptr != ch || cur >= n)
if (cur >= n || *char_ptr != ch)
return static_cast<void *>(nullptr);

return const_cast<unsigned char *>(char_ptr);
Expand Down
5 changes: 5 additions & 0 deletions libc/test/src/string/memchr_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,11 @@ const char *call_memchr(const void *src, int c, size_t size) {
return reinterpret_cast<const char *>(LIBC_NAMESPACE::memchr(src, c, size));
}

TEST(LlvmLibcMemChrTest, WideReadMultiIteration) {
const char *src = "abcdefghijklmnopqrst$\n";
ASSERT_STREQ(call_memchr(src, '$', 22), "$\n");
}

TEST(LlvmLibcMemChrTest, FindsCharacterAfterNullTerminator) {
// memchr should continue searching after a null terminator.
const size_t size = 5;
Expand Down
Loading