diff options
| author | Pietro Albini <pietro@pietroalbini.org> | 2018-11-18 23:24:58 +0100 |
|---|---|---|
| committer | kennytm <kennytm@gmail.com> | 2018-11-19 22:06:39 +0800 |
| commit | f5dc12ebfcbd385d827ce0e03f2241b295308830 (patch) | |
| tree | fad689afa6fd0b9e0e1480038981380634b5be60 | |
| parent | 2a68c0075a1cf769ebc6f28667cd29fd11b852c1 (diff) | |
| parent | cdb1a799f8793c4c858abc05b437fa2e569f51e6 (diff) | |
| download | rust-f5dc12ebfcbd385d827ce0e03f2241b295308830.tar.gz rust-f5dc12ebfcbd385d827ce0e03f2241b295308830.zip | |
Rollup merge of #56016 - scottmcm:vecdeque-resize-with, r=joshtriplett
Add VecDeque::resize_with This already exists on `Vec`; I'm just adding it to `VecDeque`. I wanted to resize a `VecDeque<Vec<T>>` when I didn't know `T: Clone`, so I couldn't use `.resize(n, Vec::new())`. With this I could do `.resize_with(n, Vec::new)` instead, which doesn't need `T: Clone`. Tracking issue: https://github.com/rust-lang/rust/issues/41758
| -rw-r--r-- | src/liballoc/collections/vec_deque.rs | 40 |
1 files changed, 39 insertions, 1 deletions
diff --git a/src/liballoc/collections/vec_deque.rs b/src/liballoc/collections/vec_deque.rs index 88e76033f27..cbf104a8fcd 100644 --- a/src/liballoc/collections/vec_deque.rs +++ b/src/liballoc/collections/vec_deque.rs @@ -19,7 +19,7 @@ use core::cmp::Ordering; use core::fmt; -use core::iter::{repeat, FromIterator, FusedIterator}; +use core::iter::{repeat, repeat_with, FromIterator, FusedIterator}; use core::mem; use core::ops::Bound::{Excluded, Included, Unbounded}; use core::ops::{Index, IndexMut, RangeBounds}; @@ -1920,6 +1920,44 @@ impl<T: Clone> VecDeque<T> { self.truncate(new_len); } } + + /// Modifies the `VecDeque` in-place so that `len()` is equal to `new_len`, + /// either by removing excess elements from the back or by appending + /// elements generated by calling `generator` to the back. + /// + /// # Examples + /// + /// ``` + /// #![feature(vec_resize_with)] + /// + /// use std::collections::VecDeque; + /// + /// let mut buf = VecDeque::new(); + /// buf.push_back(5); + /// buf.push_back(10); + /// buf.push_back(15); + /// assert_eq!(buf, [5, 10, 15]); + /// + /// buf.resize_with(5, Default::default); + /// assert_eq!(buf, [5, 10, 15, 0, 0]); + /// + /// buf.resize_with(2, || unreachable!()); + /// assert_eq!(buf, [5, 10]); + /// + /// let mut state = 100; + /// buf.resize_with(5, || { state += 1; state }); + /// assert_eq!(buf, [5, 10, 101, 102, 103]); + /// ``` + #[unstable(feature = "vec_resize_with", issue = "41758")] + pub fn resize_with(&mut self, new_len: usize, generator: impl FnMut()->T) { + let len = self.len(); + + if new_len > len { + self.extend(repeat_with(generator).take(new_len - len)) + } else { + self.truncate(new_len); + } + } } /// Returns the index in the underlying buffer for a given logical element index. |
