diff options
| author | Guillaume Gomez <guillaume1.gomez@gmail.com> | 2016-10-11 17:51:26 +0200 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2016-10-11 17:51:26 +0200 |
| commit | 0b7fe4d67cc4d3b09bea212a9a94d41b36d5d50c (patch) | |
| tree | 21598ece634c0a905bed73f441b825d0c896c3c6 | |
| parent | 6717dba27629735c4305de018070db0e188f6b17 (diff) | |
| parent | 2b7222d3ececbdc9840a3d7bd34f6cca905b80ad (diff) | |
| download | rust-0b7fe4d67cc4d3b09bea212a9a94d41b36d5d50c.tar.gz rust-0b7fe4d67cc4d3b09bea212a9a94d41b36d5d50c.zip | |
Rollup merge of #36699 - bluss:repeat-str, r=alexcrichton
Add method str::repeat(self, usize) -> String It is relatively simple to repeat a string n times: `(0..n).map(|_| s).collect::<String>()`. It becomes slightly more complicated to do it “right” (sizing the allocation up front), which warrants a method that does it for us. This method is useful in writing testcases, or when generating text. `format!()` can be used to repeat single characters, but not repeating strings like this.
| -rw-r--r-- | src/libcollections/str.rs | 20 | ||||
| -rw-r--r-- | src/libcollectionstest/lib.rs | 1 | ||||
| -rw-r--r-- | src/libcollectionstest/str.rs | 7 |
3 files changed, 28 insertions, 0 deletions
diff --git a/src/libcollections/str.rs b/src/libcollections/str.rs index 609eb28348e..48a74bdecbb 100644 --- a/src/libcollections/str.rs +++ b/src/libcollections/str.rs @@ -1789,4 +1789,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 950e6ee2e9e..c2b34647c32 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(str_replacen)] diff --git a/src/libcollectionstest/str.rs b/src/libcollectionstest/str.rs index 560895f721b..cc56bbf4890 100644 --- a/src/libcollectionstest/str.rs +++ b/src/libcollectionstest/str.rs @@ -1286,6 +1286,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}; |
