diff --git a/src/header/string/mod.rs b/src/header/string/mod.rs index 1e1d018b35ddef03fe69c3fab56bf84e0585595d..48788f2bd1f305414628e9d8a0e671de0ecc9dc7 100644 --- a/src/header/string/mod.rs +++ b/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 } diff --git a/tests/Makefile b/tests/Makefile index 609d6b4c85b3b19de35c9a15124802fa07966323..163a50410ee26b47a9740cf781b41d1357e06267 100644 --- a/tests/Makefile +++ b/tests/Makefile @@ -46,6 +46,7 @@ EXPECT_BINS=\ stdlib/strtoul \ stdlib/system \ string/mem \ + string/strcat \ string/strchr \ string/strcpy \ string/strcspn \ diff --git a/tests/expected/string/strcat.stderr b/tests/expected/string/strcat.stderr new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tests/expected/string/strcat.stdout b/tests/expected/string/strcat.stdout new file mode 100644 index 0000000000000000000000000000000000000000..10bda51843e912c86901eea164d0b3f7c9a56df3 --- /dev/null +++ b/tests/expected/string/strcat.stdout @@ -0,0 +1,2 @@ +hello world +hello world diff --git a/tests/string/strcat.c b/tests/string/strcat.c new file mode 100644 index 0000000000000000000000000000000000000000..6913c55757f738faec1b952549ce925f0826e639 --- /dev/null +++ b/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; +}