Skip to content

Commit e7f3d6e

Browse files
committed
Let str::replace take a pattern
It appears this was left out of RFC #528 because it might be useful to also generalize the second argument in some way. That doesn't seem to prevent generalizing the first argument now, however. This is a [breaking-change] because it could cause type-inference to fail where it previously succeeded.
1 parent 8864f2c commit e7f3d6e

File tree

2 files changed

+10
-1
lines changed

2 files changed

+10
-1
lines changed

src/libcollections/str.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1706,7 +1706,7 @@ impl str {
17061706
/// assert_eq!(s, s.replace("cookie monster", "little lamb"));
17071707
/// ```
17081708
#[stable(feature = "rust1", since = "1.0.0")]
1709-
pub fn replace(&self, from: &str, to: &str) -> String {
1709+
pub fn replace<'a, P: Pattern<'a>>(&'a self, from: P, to: &str) -> String {
17101710
let mut result = String::new();
17111711
let mut last_end = 0;
17121712
for (start, part) in self.match_indices(from) {

src/libcollectionstest/str.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -269,6 +269,15 @@ fn test_replace_2d() {
269269
assert_eq!(data.replace(d, repl), data);
270270
}
271271

272+
#[test]
273+
fn test_replace_pattern() {
274+
let data = "abcdαβγδabcdαβγδ";
275+
assert_eq!(data.replace("dαβ", "😺😺😺"), "abc😺😺😺γδabc😺😺😺γδ");
276+
assert_eq!(data.replace('γ', "😺😺😺"), "abcdαβ😺😺😺δabcdαβ😺😺😺δ");
277+
assert_eq!(data.replace(&['a', 'γ'] as &[_], "😺😺😺"), "😺😺😺bcdαβ😺😺😺δ😺😺😺bcdαβ😺😺😺δ");
278+
assert_eq!(data.replace(|c| c == 'γ', "😺😺😺"), "abcdαβ😺😺😺δabcdαβ😺😺😺δ");
279+
}
280+
272281
#[test]
273282
fn test_slice() {
274283
assert_eq!("ab", &"abc"[0..2]);

0 commit comments

Comments
 (0)