strlcpy/strlcat api for portability's sake.
those functions differently than the strn* ones as they do not pad with zero to remaining bytes but guarantees a null terminator.
This commit is contained in:
@@ -461,3 +461,25 @@ pub unsafe extern "C" fn strxfrm(s1: *mut c_char, s2: *const c_char, n: size_t)
|
||||
}
|
||||
len
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn strlcpy(dst: *mut c_char, src: *const c_char, n: size_t) -> size_t {
|
||||
let mut i = 0;
|
||||
|
||||
while *src.add(i) != 0 && i < n {
|
||||
*dst.add(i) = *src.add(i);
|
||||
i += 1;
|
||||
}
|
||||
|
||||
*dst.add(i) = 0;
|
||||
|
||||
i as size_t
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn strlcat(dst: *mut c_char, src: *const c_char, n: size_t) -> size_t {
|
||||
let len = strlen(dst) as isize;
|
||||
let mut d = dst.offset(len);
|
||||
|
||||
strlcpy(d, src, n)
|
||||
}
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
strcpy works!
|
||||
strncpy works!
|
||||
strncpy shaaaaaaaaa
|
||||
strlcpy works!
|
||||
copied 14
|
||||
strlcpy works! and strlcat!
|
||||
copied 13
|
||||
|
||||
@@ -16,4 +16,14 @@ int main(void) {
|
||||
dst[19] = 0;
|
||||
strncpy(dst, "strncpy should work here too", 10);
|
||||
puts(dst);
|
||||
|
||||
// The string should be properly terminated regardless
|
||||
char ndst[28];
|
||||
|
||||
size_t r = strlcpy(ndst, "strlcpy works!", 28);
|
||||
puts(ndst);
|
||||
printf("copied %lu\n", r);
|
||||
r = strlcat(ndst, " and strlcat!", 28);
|
||||
puts(ndst);
|
||||
printf("copied %lu\n", r);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user