Skip to content

Commit 0b7fe4d

Browse files
Rollup merge of rust-lang#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.
2 parents 6717dba + 2b7222d commit 0b7fe4d

File tree

3 files changed

+28
-0
lines changed

3 files changed

+28
-0
lines changed

src/libcollections/str.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1789,4 +1789,24 @@ impl str {
17891789
String::from_utf8_unchecked(slice.into_vec())
17901790
}
17911791
}
1792+
1793+
/// Create a [`String`] by repeating a string `n` times.
1794+
///
1795+
/// [`String`]: string/struct.String.html
1796+
///
1797+
/// # Examples
1798+
///
1799+
/// Basic usage:
1800+
///
1801+
/// ```
1802+
/// #![feature(repeat_str)]
1803+
///
1804+
/// assert_eq!("abc".repeat(4), String::from("abcabcabcabc"));
1805+
/// ```
1806+
#[unstable(feature = "repeat_str", issue = "37079")]
1807+
pub fn repeat(&self, n: usize) -> String {
1808+
let mut s = String::with_capacity(self.len() * n);
1809+
s.extend((0..n).map(|_| self));
1810+
s
1811+
}
17921812
}

src/libcollectionstest/lib.rs

Lines changed: 1 addition & 0 deletions
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(str_replacen)]

src/libcollectionstest/str.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1286,6 +1286,13 @@ fn test_cow_from() {
12861286
}
12871287
}
12881288

1289+
#[test]
1290+
fn test_repeat() {
1291+
assert_eq!("".repeat(3), "");
1292+
assert_eq!("abc".repeat(0), "");
1293+
assert_eq!("α".repeat(3), "ααα");
1294+
}
1295+
12891296
mod pattern {
12901297
use std::str::pattern::Pattern;
12911298
use std::str::pattern::{Searcher, ReverseSearcher};

0 commit comments

Comments
 (0)