about summary refs log tree commit diff
diff options
context:
space:
mode:
-rw-r--r--src/libcollections/str.rs20
-rw-r--r--src/libcollectionstest/lib.rs1
-rw-r--r--src/libcollectionstest/str.rs7
3 files changed, 28 insertions, 0 deletions
diff --git a/src/libcollections/str.rs b/src/libcollections/str.rs
index 999c84ba705..eb3cbf59aa4 100644
--- a/src/libcollections/str.rs
+++ b/src/libcollections/str.rs
@@ -1746,4 +1746,24 @@ impl str {
             String::from_utf8_unchecked(slice.into_vec())
         }
     }
+
+    /// Create a [`String`] by repeating a string `n` times.
+    ///
+    /// [`String`]: string/struct.String.html
+    ///
+    /// # Examples
+    ///
+    /// Basic usage:
+    ///
+    /// ```
+    /// #![feature(repeat_str)]
+    ///
+    /// assert_eq!("abc".repeat(4), String::from("abcabcabcabc"));
+    /// ```
+    #[unstable(feature = "repeat_str", issue = "37079")]
+    pub fn repeat(&self, n: usize) -> String {
+        let mut s = String::with_capacity(self.len() * n);
+        s.extend((0..n).map(|_| self));
+        s
+    }
 }
diff --git a/src/libcollectionstest/lib.rs b/src/libcollectionstest/lib.rs
index 32a07e3e7e6..ac5a1217b49 100644
--- a/src/libcollectionstest/lib.rs
+++ b/src/libcollectionstest/lib.rs
@@ -19,6 +19,7 @@
 #![feature(enumset)]
 #![feature(pattern)]
 #![feature(rand)]
+#![feature(repeat_str)]
 #![feature(step_by)]
 #![feature(str_escape)]
 #![feature(test)]
diff --git a/src/libcollectionstest/str.rs b/src/libcollectionstest/str.rs
index a61925cd3be..ebf3b017651 100644
--- a/src/libcollectionstest/str.rs
+++ b/src/libcollectionstest/str.rs
@@ -1272,6 +1272,13 @@ fn test_cow_from() {
     }
 }
 
+#[test]
+fn test_repeat() {
+    assert_eq!("".repeat(3), "");
+    assert_eq!("abc".repeat(0), "");
+    assert_eq!("α".repeat(3), "ααα");
+}
+
 mod pattern {
     use std::str::pattern::Pattern;
     use std::str::pattern::{Searcher, ReverseSearcher};