Skip to content

Commit a9f6293

Browse files
committed
Clean up strncpy
1 parent 4d40a9c commit a9f6293

File tree

1 file changed

+16
-13
lines changed

1 file changed

+16
-13
lines changed

src/strncpy.rs

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -13,17 +13,17 @@ pub unsafe extern "C" fn strncpy(
1313
src: *const CChar,
1414
count: usize,
1515
) -> *const CChar {
16-
let mut i = 0isize;
17-
while i < count as isize {
18-
*dest.offset(i) = *src.offset(i);
19-
let c = *dest.offset(i);
16+
let mut i = 0;
17+
while i < count {
18+
let c = *src.add(i);
19+
*dest.add(i) = c;
2020
i += 1;
2121
if c == 0 {
2222
break;
2323
}
2424
}
25-
for j in i..count as isize {
26-
*dest.offset(j) = 0;
25+
for j in i..count {
26+
*dest.add(j) = 0;
2727
}
2828
dest
2929
}
@@ -35,19 +35,22 @@ mod test {
3535
#[test]
3636
fn short() {
3737
let src = b"hi\0";
38-
let mut dest = *b"abcdef"; // no null terminator
38+
// no null terminator
39+
let mut dest = *b"abcdef";
40+
// pass in less than full length of dest, to see which bytes get zeroed
3941
let result = unsafe { strncpy(dest.as_mut_ptr(), src.as_ptr(), 5) };
42+
// two bytes of data, 3 bytes of zeros (= 5 bytes total), plus one byte unchanged
4043
assert_eq!(
41-
unsafe { core::slice::from_raw_parts(result, 5) },
42-
*b"hi\0\0\0"
44+
unsafe { core::slice::from_raw_parts(result, 6) },
45+
*b"hi\0\0\0f"
4346
);
4447
}
4548

4649
#[test]
4750
fn two() {
48-
let src = b"hi\0";
49-
let mut dest = [0u8; 2]; // no space for null terminator
50-
let result = unsafe { strncpy(dest.as_mut_ptr(), src.as_ptr(), 2) };
51-
assert_eq!(unsafe { core::slice::from_raw_parts(result, 2) }, b"hi");
51+
let src = b"hello\0";
52+
let mut dest = [0u8; 2]; // buffer deliberately too small
53+
let result = unsafe { strncpy(dest.as_mut_ptr(), src.as_ptr(), dest.len()) };
54+
assert_eq!(unsafe { core::slice::from_raw_parts(result, 2) }, b"he");
5255
}
5356
}

0 commit comments

Comments
 (0)