Skip to content

Commit 1202ff2

Browse files
committed
Add to_bytes and to_bytes_with_nul harnesses
1 parent 0486200 commit 1202ff2

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

library/core/src/ffi/c_str.rs

+38
Original file line numberDiff line numberDiff line change
@@ -875,4 +875,42 @@ mod verify {
875875
assert!(c_str.is_safe());
876876
}
877877
}
878+
879+
// pub const fn to_bytes(&self) -> &[u8]
880+
#[kani::proof]
881+
#[kani::unwind(32)]
882+
fn check_to_bytes() {
883+
const MAX_SIZE: usize = 32;
884+
let string: [u8; MAX_SIZE] = kani::any();
885+
let slice = kani::slice::any_slice_of_array(&string);
886+
887+
let result = CStr::from_bytes_until_nul(slice);
888+
if let Ok(c_str) = result {
889+
// Find the index of the first null byte in the slice since
890+
// from_bytes_until_nul stops by there
891+
let end_idx = slice.iter().position(|x| *x == 0).unwrap();
892+
// Comparison does not include the null byte
893+
assert_eq!(c_str.to_bytes(), &slice[..end_idx]);
894+
assert!(c_str.is_safe());
895+
}
896+
}
897+
898+
// pub const fn to_bytes_with_nul(&self) -> &[u8]
899+
#[kani::proof]
900+
#[kani::unwind(33)] // 101.7 seconds when 33; 17.9 seconds for 17
901+
fn check_to_bytes_with_nul() {
902+
const MAX_SIZE: usize = 32;
903+
let string: [u8; MAX_SIZE] = kani::any();
904+
let slice = kani::slice::any_slice_of_array(&string);
905+
906+
let result = CStr::from_bytes_until_nul(slice);
907+
if let Ok(c_str) = result {
908+
// Find the index of the first null byte in the slice since
909+
// from_bytes_until_nul stops by there
910+
let end_idx = slice.iter().position(|x| *x == 0).unwrap();
911+
// Comparison includes the null byte
912+
assert_eq!(c_str.to_bytes_with_nul(), &slice[..end_idx + 1]);
913+
assert!(c_str.is_safe());
914+
}
915+
}
878916
}

0 commit comments

Comments
 (0)