diff --git a/src/librustc_mir/interpret/memory.rs b/src/librustc_mir/interpret/memory.rs index 896a7a25b5d..b468943cbf0 100644 --- a/src/librustc_mir/interpret/memory.rs +++ b/src/librustc_mir/interpret/memory.rs @@ -567,6 +567,22 @@ impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> Memory<'a, 'mir, 'tcx, M> { } } +/// Byte Accessors +impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> Memory<'a, 'mir, 'tcx, M> { + pub fn read_bytes( + &self, + ptr: Scalar, + size: Size, + ) -> EvalResult<'tcx, &[u8]> { + if size.bytes() == 0 { + Ok(&[]) + } else { + let ptr = ptr.to_ptr()?; + self.get(ptr.alloc_id)?.read_bytes(self, ptr, size) + } + } +} + /// Interning (for CTFE) impl<'a, 'mir, 'tcx, M> Memory<'a, 'mir, 'tcx, M> where diff --git a/src/librustc_mir/interpret/operand.rs b/src/librustc_mir/interpret/operand.rs index 3f5f0ebed72..0fb5b59e442 100644 --- a/src/librustc_mir/interpret/operand.rs +++ b/src/librustc_mir/interpret/operand.rs @@ -351,10 +351,7 @@ impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> EvalContext<'a, 'mir, 'tcx, M> mplace: MPlaceTy<'tcx, M::PointerTag>, ) -> EvalResult<'tcx, &str> { let len = mplace.len(self)?; - let ptr = mplace.ptr.to_ptr()?; - let bytes = self.memory - .get(ptr.alloc_id)? - .read_bytes(self, ptr, Size::from_bytes(len as u64))?; + let bytes = self.memory.read_bytes(mplace.ptr, Size::from_bytes(len as u64))?; let str = ::std::str::from_utf8(bytes) .map_err(|err| EvalErrorKind::ValidationFailure(err.to_string()))?; Ok(str) diff --git a/src/test/ui/consts/int_ptr_for_zst_slices.rs b/src/test/ui/consts/int_ptr_for_zst_slices.rs index 809cc15be0c..afa2c6a5b9e 100644 --- a/src/test/ui/consts/int_ptr_for_zst_slices.rs +++ b/src/test/ui/consts/int_ptr_for_zst_slices.rs @@ -1,6 +1,7 @@ +// compile-pass + #![feature(const_raw_ptr_deref)] const FOO: &str = unsafe { &*(1_usize as *const [u8; 0] as *const [u8] as *const str) }; -//~^ ERROR it is undefined behaviour to use this value fn main() {}