about summary refs log tree commit diff
path: root/compiler
diff options
context:
space:
mode:
authorbors <bors@rust-lang.org>2024-02-15 06:04:25 +0000
committerbors <bors@rust-lang.org>2024-02-15 06:04:25 +0000
commitbd6b3361339522cc258d1f4165e3340e4cb1add4 (patch)
treeb2701e086a07c05cfedc85ab71f59962eec12c1b /compiler
parentee9c7c940c07d8b67c9a6b2ec930db70dcd23a46 (diff)
parent217e5e484df9ade9bbca4ffe923792872aca7bd9 (diff)
downloadrust-bd6b3361339522cc258d1f4165e3340e4cb1add4.tar.gz
rust-bd6b3361339522cc258d1f4165e3340e4cb1add4.zip
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.
Diffstat (limited to 'compiler')
-rw-r--r--compiler/rustc_data_structures/src/small_c_str.rs2
-rw-r--r--compiler/rustc_data_structures/src/small_c_str/tests.rs8
2 files changed, 9 insertions, 1 deletions
diff --git a/compiler/rustc_data_structures/src/small_c_str.rs b/compiler/rustc_data_structures/src/small_c_str.rs
index 349fd7f9769..809ce3d4483 100644
--- a/compiler/rustc_data_structures/src/small_c_str.rs
+++ b/compiler/rustc_data_structures/src/small_c_str.rs
@@ -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()) }
     }
 }
diff --git a/compiler/rustc_data_structures/src/small_c_str/tests.rs b/compiler/rustc_data_structures/src/small_c_str/tests.rs
index 47277604b2b..7b975dadcb7 100644
--- a/compiler/rustc_data_structures/src/small_c_str/tests.rs
+++ b/compiler/rustc_data_structures/src/small_c_str/tests.rs
@@ -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");
+}