diff options
| author | Diggory Blake <diggsey@googlemail.com> | 2018-03-26 23:24:31 +0100 |
|---|---|---|
| committer | Diggory Blake <diggsey@googlemail.com> | 2018-03-27 01:39:11 +0100 |
| commit | 04f6692aaf78809c041ba6145bde2dcbeec9725e (patch) | |
| tree | b02d9698234c023d503e8c7e5303eca5dc5caa1a /src/liballoc/vec_deque.rs | |
| parent | f5631d9ac7745dd6eaea2bc6c236d5f8e54e9a18 (diff) | |
| download | rust-04f6692aaf78809c041ba6145bde2dcbeec9725e.tar.gz rust-04f6692aaf78809c041ba6145bde2dcbeec9725e.zip | |
Implement `shrink_to` method on collections
Diffstat (limited to 'src/liballoc/vec_deque.rs')
| -rw-r--r-- | src/liballoc/vec_deque.rs | 35 |
1 files changed, 34 insertions, 1 deletions
diff --git a/src/liballoc/vec_deque.rs b/src/liballoc/vec_deque.rs index 0658777f0a0..be6e8d0f22f 100644 --- a/src/liballoc/vec_deque.rs +++ b/src/liballoc/vec_deque.rs @@ -676,9 +676,42 @@ impl<T> VecDeque<T> { /// ``` #[stable(feature = "deque_extras_15", since = "1.5.0")] pub fn shrink_to_fit(&mut self) { + self.shrink_to(0); + } + + /// Shrinks the capacity of the `VecDeque` with a lower bound. + /// + /// The capacity will remain at least as large as both the length + /// and the supplied value. + /// + /// Panics if the current capacity is smaller than the supplied + /// minimum capacity. + /// + /// # Examples + /// + /// ``` + /// #![feature(shrink_to)] + /// use std::collections::VecDeque; + /// + /// let mut buf = VecDeque::with_capacity(15); + /// buf.extend(0..4); + /// assert_eq!(buf.capacity(), 15); + /// buf.shrink_to(6); + /// assert!(buf.capacity() >= 6); + /// buf.shrink_to(0); + /// assert!(buf.capacity() >= 4); + /// ``` + #[unstable(feature = "shrink_to", reason = "new API", issue="0")] + pub fn shrink_to(&mut self, min_capacity: usize) { + assert!(self.capacity() >= min_capacity, "Tried to shrink to a larger capacity"); + // +1 since the ringbuffer always leaves one space empty // len + 1 can't overflow for an existing, well-formed ringbuffer. - let target_cap = cmp::max(self.len() + 1, MINIMUM_CAPACITY + 1).next_power_of_two(); + let target_cap = cmp::max( + cmp::max(min_capacity, self.len()) + 1, + MINIMUM_CAPACITY + 1 + ).next_power_of_two(); + if target_cap < self.cap() { // There are three cases of interest: // All elements are out of desired bounds |
