Skip to content

Commit

Permalink
Let str::replace take a pattern
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
wthrowe committed Dec 8, 2015
1 parent 8864f2c commit e7f3d6e
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/libcollections/str.rs
Expand Up @@ -1706,7 +1706,7 @@ impl str {
/// assert_eq!(s, s.replace("cookie monster", "little lamb"));
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn replace(&self, from: &str, to: &str) -> String {
pub fn replace<'a, P: Pattern<'a>>(&'a self, from: P, to: &str) -> String {
let mut result = String::new();
let mut last_end = 0;
for (start, part) in self.match_indices(from) {
Expand Down
9 changes: 9 additions & 0 deletions src/libcollectionstest/str.rs
Expand Up @@ -269,6 +269,15 @@ fn test_replace_2d() {
assert_eq!(data.replace(d, repl), data);
}

#[test]
fn test_replace_pattern() {
let data = "abcdαβγδabcdαβγδ";
assert_eq!(data.replace("dαβ", "😺😺😺"), "abc😺😺😺γδabc😺😺😺γδ");
assert_eq!(data.replace('γ', "😺😺😺"), "abcdαβ😺😺😺δabcdαβ😺😺😺δ");
assert_eq!(data.replace(&['a', 'γ'] as &[_], "😺😺😺"), "😺😺😺bcdαβ😺😺😺δ😺😺😺bcdαβ😺😺😺δ");
assert_eq!(data.replace(|c| c == 'γ', "😺😺😺"), "abcdαβ😺😺😺δabcdαβ😺😺😺δ");
}

#[test]
fn test_slice() {
assert_eq!("ab", &"abc"[0..2]);
Expand Down

0 comments on commit e7f3d6e

Please sign in to comment.