Auto merge of #121125 - ehuss:fix-small-cstr, r=Mark-Simulacrum

Fix SmallCStr conversion from CStr

The conversion from CStr to SmallCStr was not including the null byte. SmallCStr requires a trailing null. This caused `as_c_str` to either panic if std is built with debug assertions, or to have some corrupt memory behavior.
This commit is contained in:
bors
2024-02-15 06:04:25 +00:00
2 changed files with 9 additions and 1 deletions
@@ -82,6 +82,6 @@ fn from_iter<T: IntoIterator<Item = &'a str>>(iter: T) -> Self {
impl From<&ffi::CStr> for SmallCStr {
fn from(s: &ffi::CStr) -> Self {
Self { data: SmallVec::from_slice(s.to_bytes()) }
Self { data: SmallVec::from_slice(s.to_bytes_with_nul()) }
}
}
@@ -43,3 +43,11 @@ fn long() {
fn internal_nul() {
let _ = SmallCStr::new("abcd\0def");
}
#[test]
fn from_cstr() {
let c = c"foo";
let s: SmallCStr = c.into();
assert_eq!(s.len_with_nul(), 4);
assert_eq!(s.as_c_str(), c"foo");
}