diff --git a/src/string/src/lib.rs b/src/string/src/lib.rs index ca56dff0011bfac9dd88e78b810a6172d812e865..04b8c93bcd4c8bdfa55b40cf1e19ca55334d7172 100644 --- a/src/string/src/lib.rs +++ b/src/string/src/lib.rs @@ -299,8 +299,22 @@ pub unsafe extern "C" fn strspn(s1: *const c_char, s2: *const c_char) -> c_ulong } #[no_mangle] -pub extern "C" fn strstr(s1: *const c_char, s2: *const c_char) -> *mut c_char { - unimplemented!(); +pub unsafe extern "C" fn strstr(s1: *const c_char, s2: *const c_char) -> *mut c_char { + let mut i = 0; + while *s1.offset(i) != 0 { + let mut j = 0; + while *s2.offset(j) != 0 && *s1.offset(j + i) != 0 { + if *s2.offset(j) != *s1.offset(j + i) { + break; + } + j += 1; + if *s2.offset(j) == 0 { + return s1.offset(i) as *mut c_char; + } + } + i += 1; + } + ptr::null_mut() } #[no_mangle] diff --git a/tests/Makefile b/tests/Makefile index a2528896058cbcc1690c00a79b65746959f760c9..ecd259335b24cafe7848a32e85b2fe770029ef87 100644 --- a/tests/Makefile +++ b/tests/Makefile @@ -27,6 +27,7 @@ EXPECT_BINS=\ string/strchr \ string/strrchr \ string/strspn \ + string/strstr \ unlink \ write diff --git a/tests/expected/string/strstr.stderr b/tests/expected/string/strstr.stderr new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tests/expected/string/strstr.stdout b/tests/expected/string/strstr.stdout new file mode 100644 index 0000000000000000000000000000000000000000..e978edff7f142deb5af595baa3d297e01180e911 --- /dev/null +++ b/tests/expected/string/strstr.stdout @@ -0,0 +1,3 @@ +rust +libc we trust +NULL diff --git a/tests/string/strstr.c b/tests/string/strstr.c new file mode 100644 index 0000000000000000000000000000000000000000..1f6796a2f1609ab1c35b5bbe62bea8e6e7b10f49 --- /dev/null +++ b/tests/string/strstr.c @@ -0,0 +1,18 @@ +#include <string.h> +#include <stdio.h> + +int main(int argc, char* argv[]) { + // should be "rust" + char* str1 = strstr("In relibc we trust", "rust"); + printf("%s\n", (str1) ? str1 : "NULL"); + + // should be "libc we trust" + char* str2 = strstr("In relibc we trust", "libc"); + printf("%s\n", (str2) ? str2 : "NULL"); + + // should be "NULL" + char* str3 = strstr("In relibc we trust", "bugs"); + printf("%s\n", (str3) ? str3 : "NULL"); + + return 0; +}