diff options
| author | bors <bors@rust-lang.org> | 2020-08-14 14:08:05 +0000 |
|---|---|---|
| committer | bors <bors@rust-lang.org> | 2020-08-14 14:08:05 +0000 |
| commit | 55b9adfafa11b2ced5c0477c949fd875b19b3877 (patch) | |
| tree | e4268492c409f031a2727414bbec57bb2cee750c | |
| parent | 7996182bc1b48495014fa13799f503be01d3e5bc (diff) | |
| parent | 18377082f1a1ba2f07193f12b9d571d25b670ff7 (diff) | |
| download | rust-55b9adfafa11b2ced5c0477c949fd875b19b3877.tar.gz rust-55b9adfafa11b2ced5c0477c949fd875b19b3877.zip | |
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.
| -rw-r--r-- | library/core/src/str/mod.rs | 22 |
1 files changed, 9 insertions, 13 deletions
diff --git a/library/core/src/str/mod.rs b/library/core/src/str/mod.rs index eac4741cd26..934f581f3fa 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 @@ -2357,15 +2358,10 @@ impl str { #[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. |
