Bladeren bron

Fix strcat

Jeremy Soller 6 jaren geleden
bovenliggende
commit
9325183b21
5 gewijzigde bestanden met toevoegingen van 28 en 11 verwijderingen
  1. 13 11
      src/header/string/mod.rs
  2. 1 0
      tests/Makefile
  3. 0 0
      tests/expected/string/strcat.stderr
  4. 2 0
      tests/expected/string/strcat.stdout
  5. 12 0
      tests/string/strcat.c

+ 13 - 11
src/header/string/mod.rs

@@ -147,11 +147,6 @@ pub unsafe extern "C" fn memset(s: *mut c_void, c: c_int, n: size_t) -> *mut c_v
     s
 }
 
-#[no_mangle]
-pub unsafe extern "C" fn strcat(s1: *mut c_char, s2: *const c_char) -> *mut c_char {
-    strncat(s1, s2, usize::MAX)
-}
-
 #[no_mangle]
 pub unsafe extern "C" fn strchr(mut s: *const c_char, c: c_int) -> *mut c_char {
     let c = c as c_char;
@@ -283,18 +278,25 @@ pub unsafe extern "C" fn strnlen(s: *const c_char, size: size_t) -> size_t {
     i as size_t
 }
 
+#[no_mangle]
+pub unsafe extern "C" fn strcat(s1: *mut c_char, s2: *const c_char) -> *mut c_char {
+    strncat(s1, s2, usize::MAX)
+}
+
 #[no_mangle]
 pub unsafe extern "C" fn strncat(s1: *mut c_char, s2: *const c_char, n: size_t) -> *mut c_char {
-    let mut idx = strlen(s1 as *const _) as isize;
-    for i in 0..n as isize {
-        if *s2.offset(i) == 0 {
+    let len = strlen(s1 as *const c_char);
+    let mut i = 0;
+    while i < n {
+        let b = *s2.offset(i as isize);
+        if b == 0 {
             break;
         }
 
-        *s1.offset(idx) = *s2.offset(i);
-        idx += 1;
+        *s1.offset((len + i) as isize) = b;
+        i += 1;
     }
-    *s1.offset(idx) = 0;
+    *s1.offset((len + i) as isize) = 0;
 
     s1
 }

+ 1 - 0
tests/Makefile

@@ -46,6 +46,7 @@ EXPECT_BINS=\
 	stdlib/strtoul \
 	stdlib/system \
 	string/mem \
+	string/strcat \
 	string/strchr \
 	string/strcpy \
 	string/strcspn \

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


+ 2 - 0
tests/expected/string/strcat.stdout

@@ -0,0 +1,2 @@
+hello world
+hello world

+ 12 - 0
tests/string/strcat.c

@@ -0,0 +1,12 @@
+#include <string.h>
+#include <stdio.h>
+
+int main(int argc, char* argv[]) {
+    char dest1[12] = "hello";
+	  printf("%s\n", strcat(dest1, " world")); // should be hello world
+
+    char dest2[12] = "hello";
+  	printf("%s\n", strncat(dest2, " world foobar", 6)); // should be hello world
+
+    return 0;
+}