Skip to content

Commit

Permalink
lib/test_string.c: add some testcases for strchr and strnchr
Browse files Browse the repository at this point in the history
Make sure that the trailing NUL is considered part of the string and can
be found.

Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Peter Rosin <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
  • Loading branch information
peda-r authored and torvalds committed Jul 17, 2019
1 parent 33d6e0f commit d1a5dc5
Showing 1 changed file with 77 additions and 0 deletions.
77 changes: 77 additions & 0 deletions lib/test_string.c
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,73 @@ static __init int memset64_selftest(void)
return 0;
}

static __init int strchr_selftest(void)
{
const char *test_string = "abcdefghijkl";
const char *empty_string = "";
char *result;
int i;

for (i = 0; i < strlen(test_string) + 1; i++) {
result = strchr(test_string, test_string[i]);
if (result - test_string != i)
return i + 'a';
}

result = strchr(empty_string, '\0');
if (result != empty_string)
return 0x101;

result = strchr(empty_string, 'a');
if (result)
return 0x102;

result = strchr(test_string, 'z');
if (result)
return 0x103;

return 0;
}

static __init int strnchr_selftest(void)
{
const char *test_string = "abcdefghijkl";
const char *empty_string = "";
char *result;
int i, j;

for (i = 0; i < strlen(test_string) + 1; i++) {
for (j = 0; j < strlen(test_string) + 2; j++) {
result = strnchr(test_string, j, test_string[i]);
if (j <= i) {
if (!result)
continue;
return ((i + 'a') << 8) | j;
}
if (result - test_string != i)
return ((i + 'a') << 8) | j;
}
}

result = strnchr(empty_string, 0, '\0');
if (result)
return 0x10001;

result = strnchr(empty_string, 1, '\0');
if (result != empty_string)
return 0x10002;

result = strnchr(empty_string, 1, 'a');
if (result)
return 0x10003;

result = strnchr(NULL, 0, '\0');
if (result)
return 0x10004;

return 0;
}

static __init int string_selftest_init(void)
{
int test, subtest;
Expand All @@ -131,6 +198,16 @@ static __init int string_selftest_init(void)
if (subtest)
goto fail;

test = 4;
subtest = strchr_selftest();
if (subtest)
goto fail;

test = 5;
subtest = strnchr_selftest();
if (subtest)
goto fail;

pr_info("String selftests succeeded\n");
return 0;
fail:
Expand Down

0 comments on commit d1a5dc5

Please sign in to comment.