This is an archive of the discontinued LLVM Phabricator instance.

[libc] Add memchr implementation.
ClosedPublic

Authored by cgyurgyik on Jun 28 2020, 12:28 PM.

Details

Summary

[libc] Adds memchr implementation with corresponding unit tests. Uses a simple loop to iterate through the string.

Diff Detail

Event Timeline

cgyurgyik created this revision.Jun 28 2020, 12:28 PM
cgyurgyik edited the summary of this revision. (Show Details)Jun 28 2020, 12:51 PM
cgyurgyik added reviewers: PaulkaToast, sivachandra.
sivachandra added inline comments.Jul 7 2020, 12:24 AM
libc/src/string/memchr.cpp
19

Do you need the explicit static cast? Without it, wouldn't the compile time implicit cast do the same thing?

23

I think you don't need need the cast to void*.

25

Return nullptr?

libc/test/src/string/memchr_test.cpp
19

To avoid the noisy casts to const char *, may be use a helper function call call_memchr here and in other tests.

20

I don't think you need the casts to void* here and in the rest of the tests.

23

Why not ASSERT_STREQ?

33

Ditto.

cgyurgyik updated this revision to Diff 276061.Jul 7 2020, 7:36 AM

Changes in accordance with Siva's review.

cgyurgyik marked 7 inline comments as done.Jul 7 2020, 7:48 AM
cgyurgyik added inline comments.
libc/src/string/memchr.cpp
19

Semantically they're the same thing. I just assumed that when narrowing or widening, its always better to be explicit.

libc/test/src/string/memchr_test.cpp
33

Since src is not null-terminated, ASSERT_STREQ is going to look beyond the end of the array. I could add a null terminator to the end of ret, but don't know if that's much better than this approach. Is there an approach you were thinking of?

sivachandra accepted this revision.Jul 7 2020, 8:51 AM
sivachandra marked an inline comment as done.
sivachandra added inline comments.
libc/config/linux/x86_64/entrypoints.txt
30

Add it to the aarch64 list as well?

libc/src/string/CMakeLists.txt
54

Do we need this dependency?

libc/test/src/string/memchr_test.cpp
33

Acknowledged.

This revision is now accepted and ready to land.Jul 7 2020, 8:51 AM
cgyurgyik updated this revision to Diff 276192.Jul 7 2020, 1:12 PM
cgyurgyik marked 5 inline comments as done.
cgyurgyik closed this revision.Jul 7 2020, 2:13 PM
sivachandra added inline comments.Jul 10 2020, 1:00 AM
libc/src/string/memchr.cpp
19

You still need a cast. I was asking about the explicit static cast, but at least the implicit cast is requried. That is:

unsigned char ch = c;
for (; n && *str != ch; --n, ++str)
...

Without this, and if char type were signed char, then this will happen:

char c = -1;
char mem[5] = {c, c, c, c, c};
memchr(mem, c, 5);

The unsigned char values in mem are all 255. But, they will get promoted to an int value of 255 and then compared with an int value of -1. So memchr will return nullptr.

Sorry for not catching this earlier.