diff --git a/src/string/src/lib.rs b/src/string/src/lib.rs index b639cf2e53b4b1dad6a2750b893cd576ee0877d0..962c8f761dfb3d3d1497b5ae180a1f3cdd77e8f1 100644 --- a/src/string/src/lib.rs +++ b/src/string/src/lib.rs @@ -255,8 +255,17 @@ pub extern "C" fn strpbrk(s1: *const c_char, s2: *const c_char) -> *mut c_char { } #[no_mangle] -pub extern "C" fn strrchr(s: *const c_char, c: c_int) -> *mut c_char { - unimplemented!(); +pub unsafe extern "C" fn strrchr(s: *const c_char, c: c_int) -> *mut c_char { + let len = strlen(s) as isize; + let c = c as i8; + let mut i = len - 1; + while i >= 0 { + if *s.offset(i) == c { + return s.offset(i) as *mut c_char; + } + i -= 1; + } + ptr::null_mut() } #[no_mangle] diff --git a/tests/.gitignore b/tests/.gitignore index 929fcc62d71ecb4731df70568aeaf5dd358dab3e..c5a743e74f6964efc7476545fcce4229e2653fc7 100644 --- a/tests/.gitignore +++ b/tests/.gitignore @@ -32,6 +32,7 @@ /string/strncmp /string/strcspn /string/strchr +/string/strrchr /string/strspn /unlink /write diff --git a/tests/Makefile b/tests/Makefile index 49c313a55d49fde2eeb18b7968a88d71037c00c2..ea41ffa7a2a7761ab75e4e116579d9ef4276f051 100644 --- a/tests/Makefile +++ b/tests/Makefile @@ -27,6 +27,7 @@ BINS=\ string/strncmp \ string/strcspn \ string/strchr \ + string/strrchr \ string/strspn \ unlink \ write diff --git a/tests/string/strrchr.c b/tests/string/strrchr.c new file mode 100644 index 0000000000000000000000000000000000000000..7edc98040b36fb4cdafd327384c9d840a74c0ee3 --- /dev/null +++ b/tests/string/strrchr.c @@ -0,0 +1,22 @@ +#include <string.h> +#include <stdio.h> + + +int main(int argc, char* argv[]) { + char s0[] = "hello, world"; + char* ptr = strrchr(s0, 'l'); + if (ptr != &s0[10]) { + printf("%p != %p\n", ptr, &s0[10]); + printf("strrchr FAIL , exit with status code %d\n", 1); + return 1; + } + char s1[] = ""; + ptr = strrchr(s1, 'a'); + if (ptr != NULL) { + printf("%p != 0\n", ptr); + printf("strrchr FAIL, exit with status code %d\n", 1); + return 1; + } + printf("strrch PASS, exiting with status code %d\n", 0); + return 0; +}