std: Unsafe-wrap in Wtf8 impl · model-checking/verify-rust-std@e8fa3ef (original) (raw)

Original file line number Diff line number Diff line change
@@ -602,7 +602,8 @@ impl Wtf8 {
602 602 /// marked unsafe.
603 603 #[inline]
604 604 pub unsafe fn from_bytes_unchecked(value: &[u8]) -> &Wtf8 {
605 - mem::transmute(value)
605 +// SAFETY: start with &[u8], end with fancy &[u8]
606 +unsafe { &*(value as *const [u8] as *const Wtf8) }
606 607 }
607 608
608 609 /// Creates a mutable WTF-8 slice from a mutable WTF-8 byte slice.
@@ -611,7 +612,8 @@ impl Wtf8 {
611 612 /// marked unsafe.
612 613 #[inline]
613 614 unsafe fn from_mut_bytes_unchecked(value: &mut [u8]) -> &mut Wtf8 {
614 - mem::transmute(value)
615 +// SAFETY: start with &mut [u8], end with fancy &mut [u8]
616 +unsafe { &mut *(value as *mut [u8] as *mut Wtf8) }
615 617 }
616 618
617 619 /// Returns the length, in WTF-8 bytes.
@@ -942,8 +944,12 @@ pub fn check_utf8_boundary(slice: &Wtf8, index: usize) {
942 944 /// Copied from core::str::raw::slice_unchecked
943 945 #[inline]
944 946 pub unsafe fn slice_unchecked(s: &Wtf8, begin: usize, end: usize) -> &Wtf8 {
945 -// memory layout of a &[u8] and &Wtf8 are the same
946 -Wtf8::from_bytes_unchecked(slice::from_raw_parts(s.bytes.as_ptr().add(begin), end - begin))
947 +// SAFETY: memory layout of a &[u8] and &Wtf8 are the same
948 +unsafe {
949 +let len = end - begin;
950 +let start = s.as_bytes().as_ptr().add(begin);
951 +Wtf8::from_bytes_unchecked(slice::from_raw_parts(start, len))
952 +}
947 953 }
948 954
949 955 /// Copied from core::str::raw::slice_error_fail