Skip to content

Commit 83ae4a9

Browse files
authored
Merge pull request #24 from rust-embedded-community/fix-tests
Fix strcpy and strncpy tests
2 parents 3b6d9e9 + a9f6293 commit 83ae4a9

File tree

2 files changed

+18
-23
lines changed

2 files changed

+18
-23
lines changed

src/strcpy.rs

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -30,16 +30,8 @@ mod test {
3030
let mut dest = *b"abcdef"; // no null terminator
3131
let result = unsafe { strcpy(dest.as_mut_ptr(), src.as_ptr()) };
3232
assert_eq!(
33-
unsafe { core::slice::from_raw_parts(result, 5) },
34-
*b"hi\0de"
33+
unsafe { core::slice::from_raw_parts(result, 6) },
34+
*b"hi\0def"
3535
);
3636
}
37-
38-
#[test]
39-
fn two() {
40-
let src = b"hi\0";
41-
let mut dest = [0u8; 2]; // no space for null terminator
42-
let result = unsafe { strcpy(dest.as_mut_ptr(), src.as_ptr()) };
43-
assert_eq!(unsafe { core::slice::from_raw_parts(result, 2) }, b"hi");
44-
}
4537
}

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)