Skip to content

Commit 55b9adf

Browse files
committed
Auto merge of #75157 - rodrimati1992:patch-1, r=oli-obk
Constified str::from_utf8_unchecked This would be useful for const code to use an array to construct a string using guaranteed utf8 inputs, and then create a `&str` from it.
2 parents 7996182 + 1837708 commit 55b9adf

File tree

1 file changed

+9
-13
lines changed

1 file changed

+9
-13
lines changed

library/core/src/str/mod.rs

+9-13
Original file line numberDiff line numberDiff line change
@@ -414,12 +414,13 @@ pub fn from_utf8_mut(v: &mut [u8]) -> Result<&mut str, Utf8Error> {
414414
/// ```
415415
#[inline]
416416
#[stable(feature = "rust1", since = "1.0.0")]
417-
pub unsafe fn from_utf8_unchecked(v: &[u8]) -> &str {
418-
// SAFETY: the caller must guarantee that the bytes `v`
419-
// are valid UTF-8, thus the cast to `*const str` is safe.
420-
// Also, the pointer dereference is safe because that pointer
421-
// comes from a reference which is guaranteed to be valid for reads.
422-
unsafe { &*(v as *const [u8] as *const str) }
417+
#[rustc_const_unstable(feature = "const_str_from_utf8_unchecked", issue = "75196")]
418+
#[allow(unused_attributes)]
419+
#[allow_internal_unstable(const_fn_transmute)]
420+
pub const unsafe fn from_utf8_unchecked(v: &[u8]) -> &str {
421+
// SAFETY: the caller must guarantee that the bytes `v` are valid UTF-8.
422+
// Also relies on `&str` and `&[u8]` having the same layout.
423+
unsafe { mem::transmute(v) }
423424
}
424425

425426
/// Converts a slice of bytes to a string slice without checking
@@ -2357,15 +2358,10 @@ impl str {
23572358
#[rustc_const_stable(feature = "str_as_bytes", since = "1.32.0")]
23582359
#[inline(always)]
23592360
#[allow(unused_attributes)]
2360-
#[allow_internal_unstable(const_fn_union)]
2361+
#[allow_internal_unstable(const_fn_transmute)]
23612362
pub const fn as_bytes(&self) -> &[u8] {
2362-
#[repr(C)]
2363-
union Slices<'a> {
2364-
str: &'a str,
2365-
slice: &'a [u8],
2366-
}
23672363
// SAFETY: const sound because we transmute two types with the same layout
2368-
unsafe { Slices { str: self }.slice }
2364+
unsafe { mem::transmute(self) }
23692365
}
23702366

23712367
/// Converts a mutable string slice to a mutable byte slice.

0 commit comments

Comments
 (0)