about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorWilliam Throwe <wtt6@cornell.edu>2015-11-01 00:21:47 -0400
committerWilliam Throwe <wtt6@cornell.edu>2015-12-07 22:08:33 -0500
commite7f3d6eddd28a917c9a0f7cd73a489048ca7f4cd (patch)
treec09d2d45e36c62a9fd318455a7def076e54b0138 /src
parent8864f2c83ac800881da34c3e835c931c081a8785 (diff)
downloadrust-e7f3d6eddd28a917c9a0f7cd73a489048ca7f4cd.tar.gz
rust-e7f3d6eddd28a917c9a0f7cd73a489048ca7f4cd.zip
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.
Diffstat (limited to 'src')
-rw-r--r--src/libcollections/str.rs2
-rw-r--r--src/libcollectionstest/str.rs9
2 files changed, 10 insertions, 1 deletions
diff --git a/src/libcollections/str.rs b/src/libcollections/str.rs
index be3f93992d9..989637517b0 100644
--- a/src/libcollections/str.rs
+++ b/src/libcollections/str.rs
@@ -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) {
diff --git a/src/libcollectionstest/str.rs b/src/libcollectionstest/str.rs
index e22ff7ca540..4d84855ddf9 100644
--- a/src/libcollectionstest/str.rs
+++ b/src/libcollectionstest/str.rs
@@ -270,6 +270,15 @@ fn test_replace_2d() {
 }
 
 #[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]);
     assert_eq!("bc", &"abc"[1..3]);