This is an archive of the discontinued LLVM Phabricator instance.

[libc] add strncmp to strings
ClosedPublic

Authored by michaelrj on Jul 27 2021, 11:33 AM.

Details

Summary

Add strncmp as a function to strings.h. Also adds unit tests, and adds
strncmp as an entrypoint for all current platforms.

Diff Detail

Event Timeline

michaelrj created this revision.Jul 27 2021, 11:33 AM
michaelrj requested review of this revision.Jul 27 2021, 11:33 AM
sivachandra added inline comments.Jul 27 2021, 4:33 PM
libc/src/string/strncmp.cpp
19

Nitty comment: Why can it not be just n == 0?

22

Another nitty comment - This for statement is hard to read. Can we make it simpler like this:

for (; n > 0; --n, ++left, ++right) {
  char lc = *left;
  if (lc == '\0' || lc != *right)
    break;
}
24

Just pointing out as I am not sure what is right here: casting to unsigned char can remove the potential sign and lead to -1 > 0. Even strcmp is set up this way so may be clean up both of them in a follow up patch.

libc/test/src/string/strncmp_test.cpp
159

Fix.

cheng.w added inline comments.
libc/src/string/strncmp.cpp
19

nit: We could omit the braces since the body of if is simple.

michaelrj marked 4 inline comments as done.

address comments

libc/src/string/strncmp.cpp
24

given that these are supposed to be strings, I would assume that unsigned char is correct. Testing with my system libc, it appears that this is what it does as well. I ran strncmp on the following char array: [-1, 'a', '\0'] compared to "abc" with length 3 and got the value 158, which is 255 - 97 ('a' = 97).

sivachandra accepted this revision.Jul 28 2021, 11:14 AM
sivachandra added inline comments.
libc/src/string/strncmp.cpp
24

Thanks for checking!

This revision is now accepted and ready to land.Jul 28 2021, 11:14 AM
This revision was automatically updated to reflect the committed changes.