diff --git a/library/alloc/src/slice.rs b/library/alloc/src/slice.rs index da9b40c2c3ce0..e6b540f093ba5 100644 --- a/library/alloc/src/slice.rs +++ b/library/alloc/src/slice.rs @@ -639,9 +639,7 @@ impl [u8] { #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")] #[inline] pub fn to_ascii_uppercase(&self) -> Vec { - let mut me = self.to_vec(); - me.make_ascii_uppercase(); - me + self.iter().map(|b| b.to_ascii_uppercase()).collect() } /// Returns a vector containing a copy of this slice where each byte @@ -660,9 +658,7 @@ impl [u8] { #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")] #[inline] pub fn to_ascii_lowercase(&self) -> Vec { - let mut me = self.to_vec(); - me.make_ascii_lowercase(); - me + self.iter().map(|b| b.to_ascii_lowercase()).collect() } } diff --git a/library/alloc/src/str.rs b/library/alloc/src/str.rs index fd0d66cf028b3..ee9e82368899f 100644 --- a/library/alloc/src/str.rs +++ b/library/alloc/src/str.rs @@ -844,9 +844,10 @@ impl str { #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")] #[inline] pub fn to_ascii_uppercase(&self) -> String { - let mut s = self.to_owned(); - s.make_ascii_uppercase(); - s + let bytes = self.as_bytes().to_ascii_uppercase(); + // SAFETY: ASCII case conversion only maps a-z to A-Z and leaves + // all other bytes unchanged as valid UTF-8 + unsafe { String::from_utf8_unchecked(bytes) } } /// Returns a copy of this string where each character is mapped to its @@ -876,9 +877,10 @@ impl str { #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")] #[inline] pub fn to_ascii_lowercase(&self) -> String { - let mut s = self.to_owned(); - s.make_ascii_lowercase(); - s + let bytes = self.as_bytes().to_ascii_lowercase(); + // SAFETY: ASCII case conversion only maps A-Z to a-z and leaves + // all other bytes unchanged as valid UTF-8 + unsafe { String::from_utf8_unchecked(bytes) } } }