diff --git a/src/liballoc/slice.rs b/src/liballoc/slice.rs index 9d442b3e00ca0..6c0b1c33a1f76 100644 --- a/src/liballoc/slice.rs +++ b/src/liballoc/slice.rs @@ -392,6 +392,10 @@ impl [T] { /// Creates a vector by repeating a slice `n` times. /// + /// # Panics + /// + /// This function will panic if the capacity would overflow. + /// /// # Examples /// /// Basic usage: @@ -403,6 +407,16 @@ impl [T] { /// assert_eq!([1, 2].repeat(3), vec![1, 2, 1, 2, 1, 2]); /// } /// ``` + /// + /// A panic upon overflow: + /// + /// ```should_panic + /// #![feature(repeat_generic_slice)] + /// fn main() { + /// // this will panic at runtime + /// b"0123456789abcdef".repeat(usize::max_value()); + /// } + /// ``` #[unstable(feature = "repeat_generic_slice", reason = "it's on str, why not on slice?", issue = "48784")] @@ -417,7 +431,7 @@ impl [T] { // and `rem` is the remaining part of `n`. // Using `Vec` to access `set_len()`. - let mut buf = Vec::with_capacity(self.len() * n); + let mut buf = Vec::with_capacity(self.len().checked_mul(n).expect("capacity overflow")); // `2^expn` repetition is done by doubling `buf` `expn`-times. buf.extend(self); diff --git a/src/liballoc/str.rs b/src/liballoc/str.rs index c451a051c74dc..2af89562d69fe 100644 --- a/src/liballoc/str.rs +++ b/src/liballoc/str.rs @@ -515,6 +515,10 @@ impl str { /// Creates a new [`String`] by repeating a string `n` times. /// + /// # Panics + /// + /// This function will panic if the capacity would overflow. + /// /// [`String`]: string/struct.String.html /// /// # Examples @@ -524,6 +528,15 @@ impl str { /// ``` /// assert_eq!("abc".repeat(4), String::from("abcabcabcabc")); /// ``` + /// + /// A panic upon overflow: + /// + /// ```should_panic + /// fn main() { + /// // this will panic at runtime + /// "0123456789abcdef".repeat(usize::max_value()); + /// } + /// ``` #[stable(feature = "repeat_str", since = "1.16.0")] pub fn repeat(&self, n: usize) -> String { unsafe { String::from_utf8_unchecked(self.as_bytes().repeat(n)) }