From 99de3728f95d1a3fa6063aa4ef2974a45cf35f4c Mon Sep 17 00:00:00 2001 From: Amanieu d'Antras Date: Wed, 22 Apr 2020 22:22:48 +0100 Subject: [PATCH] Only use read_unaligned in transmute_copy if necessary --- src/libcore/mem/mod.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/libcore/mem/mod.rs b/src/libcore/mem/mod.rs index 07f7d28bb7546..e42b73ddd23a9 100644 --- a/src/libcore/mem/mod.rs +++ b/src/libcore/mem/mod.rs @@ -923,7 +923,12 @@ pub fn drop(_x: T) {} #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub unsafe fn transmute_copy(src: &T) -> U { - ptr::read_unaligned(src as *const T as *const U) + // If U has a higher alignment requirement, src may not be suitably aligned. + if align_of::() > align_of::() { + ptr::read_unaligned(src as *const T as *const U) + } else { + ptr::read(src as *const T as *const U) + } } /// Opaque type representing the discriminant of an enum.