Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit e8fa3ef

Browse files
committedJul 15, 2024
std: Unsafe-wrap in Wtf8 impl
1 parent 8c3a9c1 commit e8fa3ef

File tree

2 files changed

+10
-5
lines changed

2 files changed

+10
-5
lines changed
 

‎std/src/sys_common/mod.rs

-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@
1616
1717
#![allow(missing_docs)]
1818
#![allow(missing_debug_implementations)]
19-
#![allow(unsafe_op_in_unsafe_fn)]
2019

2120
#[cfg(test)]
2221
mod tests;

‎std/src/sys_common/wtf8.rs

+10-4
Original file line numberDiff line numberDiff line change
@@ -602,7 +602,8 @@ impl Wtf8 {
602602
/// marked unsafe.
603603
#[inline]
604604
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) }
606607
}
607608

608609
/// Creates a mutable WTF-8 slice from a mutable WTF-8 byte slice.
@@ -611,7 +612,8 @@ impl Wtf8 {
611612
/// marked unsafe.
612613
#[inline]
613614
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) }
615617
}
616618

617619
/// Returns the length, in WTF-8 bytes.
@@ -942,8 +944,12 @@ pub fn check_utf8_boundary(slice: &Wtf8, index: usize) {
942944
/// Copied from core::str::raw::slice_unchecked
943945
#[inline]
944946
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+
}
947953
}
948954

949955
/// Copied from core::str::raw::slice_error_fail

0 commit comments

Comments
 (0)
Failed to load comments.