Skip to content

Commit

Permalink
Auto merge of #121125 - ehuss:fix-small-cstr, r=Mark-Simulacrum
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
bors committed Feb 15, 2024
2 parents ee9c7c9 + 217e5e4 commit bd6b336
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 1 deletion.
2 changes: 1 addition & 1 deletion compiler/rustc_data_structures/src/small_c_str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,6 @@ impl<'a> FromIterator<&'a str> for SmallCStr {

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()) }
}
}
8 changes: 8 additions & 0 deletions compiler/rustc_data_structures/src/small_c_str/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
}

0 comments on commit bd6b336

Please sign in to comment.