Skip to content

Commit cdb1a79

Browse files
committed
Add VecDeque::resize_with
1 parent ee82173 commit cdb1a79

File tree

1 file changed

+39
-1
lines changed

1 file changed

+39
-1
lines changed

src/liballoc/collections/vec_deque.rs

+39-1
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919

2020
use core::cmp::Ordering;
2121
use core::fmt;
22-
use core::iter::{repeat, FromIterator, FusedIterator};
22+
use core::iter::{repeat, repeat_with, FromIterator, FusedIterator};
2323
use core::mem;
2424
use core::ops::Bound::{Excluded, Included, Unbounded};
2525
use core::ops::{Index, IndexMut, RangeBounds};
@@ -1920,6 +1920,44 @@ impl<T: Clone> VecDeque<T> {
19201920
self.truncate(new_len);
19211921
}
19221922
}
1923+
1924+
/// Modifies the `VecDeque` in-place so that `len()` is equal to `new_len`,
1925+
/// either by removing excess elements from the back or by appending
1926+
/// elements generated by calling `generator` to the back.
1927+
///
1928+
/// # Examples
1929+
///
1930+
/// ```
1931+
/// #![feature(vec_resize_with)]
1932+
///
1933+
/// use std::collections::VecDeque;
1934+
///
1935+
/// let mut buf = VecDeque::new();
1936+
/// buf.push_back(5);
1937+
/// buf.push_back(10);
1938+
/// buf.push_back(15);
1939+
/// assert_eq!(buf, [5, 10, 15]);
1940+
///
1941+
/// buf.resize_with(5, Default::default);
1942+
/// assert_eq!(buf, [5, 10, 15, 0, 0]);
1943+
///
1944+
/// buf.resize_with(2, || unreachable!());
1945+
/// assert_eq!(buf, [5, 10]);
1946+
///
1947+
/// let mut state = 100;
1948+
/// buf.resize_with(5, || { state += 1; state });
1949+
/// assert_eq!(buf, [5, 10, 101, 102, 103]);
1950+
/// ```
1951+
#[unstable(feature = "vec_resize_with", issue = "41758")]
1952+
pub fn resize_with(&mut self, new_len: usize, generator: impl FnMut()->T) {
1953+
let len = self.len();
1954+
1955+
if new_len > len {
1956+
self.extend(repeat_with(generator).take(new_len - len))
1957+
} else {
1958+
self.truncate(new_len);
1959+
}
1960+
}
19231961
}
19241962

19251963
/// Returns the index in the underlying buffer for a given logical element index.

0 commit comments

Comments
 (0)