Skip to content

Commit 2b7222d

Browse files
committed
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.
1 parent a5dbf8a commit 2b7222d

File tree

3 files changed

+28
-0
lines changed

3 files changed

+28
-0
lines changed

src/libcollections/str.rs

+20
Original file line numberDiff line numberDiff line change
@@ -1746,4 +1746,24 @@ impl str {
17461746
String::from_utf8_unchecked(slice.into_vec())
17471747
}
17481748
}
1749+
1750+
/// Create a [`String`] by repeating a string `n` times.
1751+
///
1752+
/// [`String`]: string/struct.String.html
1753+
///
1754+
/// # Examples
1755+
///
1756+
/// Basic usage:
1757+
///
1758+
/// ```
1759+
/// #![feature(repeat_str)]
1760+
///
1761+
/// assert_eq!("abc".repeat(4), String::from("abcabcabcabc"));
1762+
/// ```
1763+
#[unstable(feature = "repeat_str", issue = "37079")]
1764+
pub fn repeat(&self, n: usize) -> String {
1765+
let mut s = String::with_capacity(self.len() * n);
1766+
s.extend((0..n).map(|_| self));
1767+
s
1768+
}
17491769
}

src/libcollectionstest/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
#![feature(enumset)]
2020
#![feature(pattern)]
2121
#![feature(rand)]
22+
#![feature(repeat_str)]
2223
#![feature(step_by)]
2324
#![feature(str_escape)]
2425
#![feature(test)]

src/libcollectionstest/str.rs

+7
Original file line numberDiff line numberDiff line change
@@ -1272,6 +1272,13 @@ fn test_cow_from() {
12721272
}
12731273
}
12741274

1275+
#[test]
1276+
fn test_repeat() {
1277+
assert_eq!("".repeat(3), "");
1278+
assert_eq!("abc".repeat(0), "");
1279+
assert_eq!("α".repeat(3), "ααα");
1280+
}
1281+
12751282
mod pattern {
12761283
use std::str::pattern::Pattern;
12771284
use std::str::pattern::{Searcher, ReverseSearcher};

0 commit comments

Comments
 (0)