X-Git-Url: https://git.lizzy.rs/?a=blobdiff_plain;f=library%2Fcore%2Fsrc%2Fstr%2Fmod.rs;h=4705c984bd426ffa2f6421cc19640eede2816b87;hb=ac264b53d114ed00828b3236b8b2279df09f1623;hp=eac4741cd260ad483969d3dfdc70f9cb838f2c45;hpb=ccffe18c3ebbb7abbaf267b2a98648a73946bff9;p=rust.git diff --git a/library/core/src/str/mod.rs b/library/core/src/str/mod.rs index eac4741cd26..4705c984bd4 100644 --- a/library/core/src/str/mod.rs +++ b/library/core/src/str/mod.rs @@ -414,12 +414,13 @@ pub fn from_utf8_mut(v: &mut [u8]) -> Result<&mut str, Utf8Error> { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] -pub unsafe fn from_utf8_unchecked(v: &[u8]) -> &str { - // SAFETY: the caller must guarantee that the bytes `v` - // are valid UTF-8, thus the cast to `*const str` is safe. - // Also, the pointer dereference is safe because that pointer - // comes from a reference which is guaranteed to be valid for reads. - unsafe { &*(v as *const [u8] as *const str) } +#[rustc_const_unstable(feature = "const_str_from_utf8_unchecked", issue = "75196")] +#[allow(unused_attributes)] +#[allow_internal_unstable(const_fn_transmute)] +pub const unsafe fn from_utf8_unchecked(v: &[u8]) -> &str { + // SAFETY: the caller must guarantee that the bytes `v` are valid UTF-8. + // Also relies on `&str` and `&[u8]` having the same layout. + unsafe { mem::transmute(v) } } /// Converts a slice of bytes to a string slice without checking @@ -2030,7 +2031,7 @@ fn index_mut(self, slice: &mut str) -> &mut Self::Output { /// # Panics /// /// Panics if `begin` does not point to the starting byte offset of - /// a character (as defined by `is_char_boundary`), or if `begin >= len`. + /// a character (as defined by `is_char_boundary`), or if `begin > len`. #[stable(feature = "str_checked_slicing", since = "1.20.0")] unsafe impl SliceIndex for ops::RangeFrom { type Output = str; @@ -2357,15 +2358,10 @@ pub fn is_char_boundary(&self, index: usize) -> bool { #[rustc_const_stable(feature = "str_as_bytes", since = "1.32.0")] #[inline(always)] #[allow(unused_attributes)] - #[allow_internal_unstable(const_fn_union)] + #[allow_internal_unstable(const_fn_transmute)] pub const fn as_bytes(&self) -> &[u8] { - #[repr(C)] - union Slices<'a> { - str: &'a str, - slice: &'a [u8], - } // SAFETY: const sound because we transmute two types with the same layout - unsafe { Slices { str: self }.slice } + unsafe { mem::transmute(self) } } /// Converts a mutable string slice to a mutable byte slice.