Skip to content

Commit 18842f8

Browse files
committed
auto merge of #20143 : csouth3/rust/vecmap-reserve, r=Gankro
Implement `reserve_len` and `reserve_len_exact` for `VecMap` in accordance with rust-lang/rfcs#509.
2 parents 3c60bc0 + 868acdf commit 18842f8

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

src/libcollections/vec_map.rs

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,52 @@ impl<V> VecMap<V> {
138138
self.v.capacity()
139139
}
140140

141+
/// Reserves capacity for the given `VecMap` to contain `len` distinct keys.
142+
/// In the case of `VecMap` this means reallocations will not occur as long
143+
/// as all inserted keys are less than `len`.
144+
///
145+
/// The collection may reserve more space to avoid frequent reallocations.
146+
///
147+
/// # Examples
148+
///
149+
/// ```
150+
/// use std::collections::VecMap;
151+
/// let mut map: VecMap<&str> = VecMap::new();
152+
/// map.reserve_len(10);
153+
/// assert!(map.capacity() >= 10);
154+
/// ```
155+
#[unstable = "matches collection reform specification, waiting for dust to settle"]
156+
pub fn reserve_len(&mut self, len: uint) {
157+
let cur_len = self.v.len();
158+
if len >= cur_len {
159+
self.v.reserve(len - cur_len);
160+
}
161+
}
162+
163+
/// Reserves the minimum capacity for the given `VecMap` to contain `len` distinct keys.
164+
/// In the case of `VecMap` this means reallocations will not occur as long as all inserted
165+
/// keys are less than `len`.
166+
///
167+
/// Note that the allocator may give the collection more space than it requests.
168+
/// Therefore capacity cannot be relied upon to be precisely minimal. Prefer
169+
/// `reserve_len` if future insertions are expected.
170+
///
171+
/// # Examples
172+
///
173+
/// ```
174+
/// use std::collections::VecMap;
175+
/// let mut map: VecMap<&str> = VecMap::new();
176+
/// map.reserve_len_exact(10);
177+
/// assert!(map.capacity() >= 10);
178+
/// ```
179+
#[unstable = "matches collection reform specification, waiting for dust to settle"]
180+
pub fn reserve_len_exact(&mut self, len: uint) {
181+
let cur_len = self.v.len();
182+
if len >= cur_len {
183+
self.v.reserve_exact(len - cur_len);
184+
}
185+
}
186+
141187
/// Returns an iterator visiting all keys in ascending order by the keys.
142188
/// The iterator's element type is `uint`.
143189
#[unstable = "matches collection reform specification, waiting for dust to settle"]

0 commit comments

Comments
 (0)