Browse Source

Implement strstr(), add strstr test

Andrii Zymohliad 7 years ago
parent
commit
a1de0ef8a1

+ 16 - 2
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]

+ 1 - 0
tests/Makefile

@@ -27,6 +27,7 @@ EXPECT_BINS=\
 	string/strchr \
 	string/strrchr \
 	string/strspn \
+	string/strstr \
 	unlink \
 	write
 

+ 0 - 0
tests/expected/string/strstr.stderr


+ 3 - 0
tests/expected/string/strstr.stdout

@@ -0,0 +1,3 @@
+rust
+libc we trust
+NULL

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