Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion library/alloc/src/str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -308,7 +308,10 @@ impl str {
pub fn replace<P: Pattern>(&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,
} {
Expand Down
2 changes: 1 addition & 1 deletion library/alloc/src/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2654,7 +2654,7 @@ impl<'b> Pattern for &'b String {

#[inline]
fn as_utf8_pattern(&self) -> Option<Utf8Pattern<'_>> {
Some(Utf8Pattern::StringPattern(self.as_bytes()))
Some(Utf8Pattern::StringPattern(self.as_str()))
}
}

Expand Down
8 changes: 5 additions & 3 deletions library/core/src/str/pattern.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Utf8Pattern<'_>> {
None
}
Expand All @@ -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),
Comment thread
qaijuang marked this conversation as resolved.
/// Type returned by char types.
CharPattern(char),
}
Expand Down Expand Up @@ -1049,7 +1051,7 @@ impl<'b> Pattern for &'b str {

#[inline]
fn as_utf8_pattern(&self) -> Option<Utf8Pattern<'_>> {
Some(Utf8Pattern::StringPattern(self.as_bytes()))
Some(Utf8Pattern::StringPattern(*self))
}
}

Expand Down
Loading