Skip to content

Commit

Permalink
std: Unsafe-wrap in Wtf8 impl
Browse files Browse the repository at this point in the history
  • Loading branch information
workingjubilee committed Jul 15, 2024
1 parent 8c3a9c1 commit e8fa3ef
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 5 deletions.
1 change: 0 additions & 1 deletion std/src/sys_common/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
#![allow(missing_docs)]
#![allow(missing_debug_implementations)]
#![allow(unsafe_op_in_unsafe_fn)]

#[cfg(test)]
mod tests;
Expand Down
14 changes: 10 additions & 4 deletions std/src/sys_common/wtf8.rs
Original file line number Diff line number Diff line change
Expand Up @@ -602,7 +602,8 @@ impl Wtf8 {
/// marked unsafe.
#[inline]
pub unsafe fn from_bytes_unchecked(value: &[u8]) -> &Wtf8 {
mem::transmute(value)
// SAFETY: start with &[u8], end with fancy &[u8]
unsafe { &*(value as *const [u8] as *const Wtf8) }
}

/// Creates a mutable WTF-8 slice from a mutable WTF-8 byte slice.
Expand All @@ -611,7 +612,8 @@ impl Wtf8 {
/// marked unsafe.
#[inline]
unsafe fn from_mut_bytes_unchecked(value: &mut [u8]) -> &mut Wtf8 {
mem::transmute(value)
// SAFETY: start with &mut [u8], end with fancy &mut [u8]
unsafe { &mut *(value as *mut [u8] as *mut Wtf8) }
}

/// Returns the length, in WTF-8 bytes.
Expand Down Expand Up @@ -942,8 +944,12 @@ pub fn check_utf8_boundary(slice: &Wtf8, index: usize) {
/// Copied from core::str::raw::slice_unchecked
#[inline]
pub unsafe fn slice_unchecked(s: &Wtf8, begin: usize, end: usize) -> &Wtf8 {
// memory layout of a &[u8] and &Wtf8 are the same
Wtf8::from_bytes_unchecked(slice::from_raw_parts(s.bytes.as_ptr().add(begin), end - begin))
// SAFETY: memory layout of a &[u8] and &Wtf8 are the same
unsafe {
let len = end - begin;
let start = s.as_bytes().as_ptr().add(begin);
Wtf8::from_bytes_unchecked(slice::from_raw_parts(start, len))
}
}

/// Copied from core::str::raw::slice_error_fail
Expand Down

0 comments on commit e8fa3ef

Please sign in to comment.