]> git.lizzy.rs Git - rust.git/blobdiff - src/liballoc/slice.rs
std: Check for overflow in `str::repeat`
[rust.git] / src / liballoc / slice.rs
index 9d442b3e00ca074ea7b6d1584272923bc8b922ef..6c0b1c33a1f7673ee3c4a2ed40a789214a20be4d 100644 (file)
@@ -392,6 +392,10 @@ pub fn into_vec(self: Box<Self>) -> Vec<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 @@ pub fn into_vec(self: Box<Self>) -> Vec<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 @@ pub fn repeat(&self, n: usize) -> Vec<T> where T: Copy {
         // 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);