diff --git a/library/alloc/src/str.rs b/library/alloc/src/str.rs index 1efbedf5dc42f..cf04402e3d984 100644 --- a/library/alloc/src/str.rs +++ b/library/alloc/src/str.rs @@ -308,7 +308,10 @@ impl str { pub fn replace(&self, from: P, to: &str) -> String { // Fast path for replacing a single ASCII character with another. if let Some(from_byte) = match from.as_utf8_pattern() { - Some(Utf8Pattern::StringPattern([from_byte])) => Some(*from_byte), + Some(Utf8Pattern::StringPattern(s)) => match s.as_bytes() { + [from_byte] => Some(*from_byte), + _ => None, + }, Some(Utf8Pattern::CharPattern(c)) => c.as_ascii().map(|ascii_char| ascii_char.to_u8()), _ => None, } { diff --git a/library/alloc/src/string.rs b/library/alloc/src/string.rs index 4e97dfd2d561e..e1285bc596484 100644 --- a/library/alloc/src/string.rs +++ b/library/alloc/src/string.rs @@ -2654,7 +2654,7 @@ impl<'b> Pattern for &'b String { #[inline] fn as_utf8_pattern(&self) -> Option> { - Some(Utf8Pattern::StringPattern(self.as_bytes())) + Some(Utf8Pattern::StringPattern(self.as_str())) } } diff --git a/library/core/src/str/pattern.rs b/library/core/src/str/pattern.rs index 25202ffd67313..77e0093d3ce84 100644 --- a/library/core/src/str/pattern.rs +++ b/library/core/src/str/pattern.rs @@ -161,7 +161,7 @@ pub trait Pattern: Sized { } } - /// Returns the pattern as utf-8 bytes if possible. + /// Returns the pattern as UTF-8 if possible. fn as_utf8_pattern(&self) -> Option> { None } @@ -172,7 +172,9 @@ pub trait Pattern: Sized { #[derive(Copy, Clone, Eq, PartialEq, Debug)] pub enum Utf8Pattern<'a> { /// Type returned by String and str types. - StringPattern(&'a [u8]), + /// This stores `str` rather than bytes so callers cannot describe + /// non-UTF-8 string patterns through this API. + StringPattern(&'a str), /// Type returned by char types. CharPattern(char), } @@ -1049,7 +1051,7 @@ impl<'b> Pattern for &'b str { #[inline] fn as_utf8_pattern(&self) -> Option> { - Some(Utf8Pattern::StringPattern(self.as_bytes())) + Some(Utf8Pattern::StringPattern(*self)) } }