Skip to content

Commit bd6b336

Browse files
committed
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.
2 parents ee9c7c9 + 217e5e4 commit bd6b336

File tree

2 files changed

+9
-1
lines changed

2 files changed

+9
-1
lines changed

Diff for: compiler/rustc_data_structures/src/small_c_str.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,6 @@ impl<'a> FromIterator<&'a str> for SmallCStr {
8282

8383
impl From<&ffi::CStr> for SmallCStr {
8484
fn from(s: &ffi::CStr) -> Self {
85-
Self { data: SmallVec::from_slice(s.to_bytes()) }
85+
Self { data: SmallVec::from_slice(s.to_bytes_with_nul()) }
8686
}
8787
}

Diff for: compiler/rustc_data_structures/src/small_c_str/tests.rs

+8
Original file line numberDiff line numberDiff line change
@@ -43,3 +43,11 @@ fn long() {
4343
fn internal_nul() {
4444
let _ = SmallCStr::new("abcd\0def");
4545
}
46+
47+
#[test]
48+
fn from_cstr() {
49+
let c = c"foo";
50+
let s: SmallCStr = c.into();
51+
assert_eq!(s.len_with_nul(), 4);
52+
assert_eq!(s.as_c_str(), c"foo");
53+
}

0 commit comments

Comments
 (0)