Browse Source

implement strrchr

Justin Raymond 7 years ago
parent
commit
826cf0c61c
3 changed files with 34 additions and 2 deletions
  1. 11 2
      src/string/src/lib.rs
  2. 1 0
      tests/Makefile
  3. 22 0
      tests/string/strrchr.c

+ 11 - 2
src/string/src/lib.rs

@@ -223,8 +223,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 *s.offset(i) != 0 && i >= 0 {
+        if *s.offset(i) == c {
+            return s.offset(i) as *mut c_char;
+        }
+        i -= 1;
+    }
+    ptr::null_mut()
 }
 
 #[no_mangle]

+ 1 - 0
tests/Makefile

@@ -25,6 +25,7 @@ BINS=\
 	sprintf \
 	stdlib/strtol \
 	string/strncmp \
+	string/strrchr \
 	unlink \
 	write
 

+ 22 - 0
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;
+}