Skip to content

Commit 6d14512

Browse files
committed
Remove mem::transmute used in CStr conversions
1 parent 36d663f commit 6d14512

File tree

1 file changed

+8
-7
lines changed

1 file changed

+8
-7
lines changed

src/libstd/ffi/c_str.rs

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -312,7 +312,7 @@ impl CString {
312312
pub unsafe fn from_raw(ptr: *mut c_char) -> CString {
313313
let len = libc::strlen(ptr) + 1; // Including the NUL byte
314314
let slice = slice::from_raw_parts(ptr, len as usize);
315-
CString { inner: mem::transmute(slice) }
315+
CString { inner: Box::from_raw(slice as *mut [c_char] as *mut [u8]) }
316316
}
317317

318318
/// Transfers ownership of the string to a C caller.
@@ -480,7 +480,7 @@ impl CString {
480480
/// ```
481481
#[stable(feature = "into_boxed_c_str", since = "1.20.0")]
482482
pub fn into_boxed_c_str(self) -> Box<CStr> {
483-
unsafe { mem::transmute(self.into_inner()) }
483+
unsafe { Box::from_raw(Box::into_raw(self.into_inner()) as *mut CStr) }
484484
}
485485

486486
// Bypass "move out of struct which implements [`Drop`] trait" restriction.
@@ -569,7 +569,7 @@ impl Borrow<CStr> for CString {
569569
impl<'a> From<&'a CStr> for Box<CStr> {
570570
fn from(s: &'a CStr) -> Box<CStr> {
571571
let boxed: Box<[u8]> = Box::from(s.to_bytes_with_nul());
572-
unsafe { mem::transmute(boxed) }
572+
unsafe { Box::from_raw(Box::into_raw(boxed) as *mut CStr) }
573573
}
574574
}
575575

@@ -593,7 +593,7 @@ impl From<CString> for Box<CStr> {
593593
impl Default for Box<CStr> {
594594
fn default() -> Box<CStr> {
595595
let boxed: Box<[u8]> = Box::from([0]);
596-
unsafe { mem::transmute(boxed) }
596+
unsafe { Box::from_raw(Box::into_raw(boxed) as *mut CStr) }
597597
}
598598
}
599599

@@ -817,7 +817,7 @@ impl CStr {
817817
#[inline]
818818
#[stable(feature = "cstr_from_bytes", since = "1.10.0")]
819819
pub unsafe fn from_bytes_with_nul_unchecked(bytes: &[u8]) -> &CStr {
820-
mem::transmute(bytes)
820+
&*(bytes as *const [u8] as *const CStr)
821821
}
822822

823823
/// Returns the inner pointer to this C string.
@@ -913,7 +913,7 @@ impl CStr {
913913
#[inline]
914914
#[stable(feature = "rust1", since = "1.0.0")]
915915
pub fn to_bytes_with_nul(&self) -> &[u8] {
916-
unsafe { mem::transmute(&self.inner) }
916+
unsafe { &*(&self.inner as *const [c_char] as *const [u8]) }
917917
}
918918

919919
/// Yields a [`&str`] slice if the `CStr` contains valid UTF-8.
@@ -1005,7 +1005,8 @@ impl CStr {
10051005
/// ```
10061006
#[stable(feature = "into_boxed_c_str", since = "1.20.0")]
10071007
pub fn into_c_string(self: Box<CStr>) -> CString {
1008-
unsafe { mem::transmute(self) }
1008+
let raw = Box::into_raw(self) as *mut [u8];
1009+
CString { inner: unsafe { Box::from_raw(raw) } }
10091010
}
10101011
}
10111012

0 commit comments

Comments
 (0)