Skip to content

Commit 868acdf

Browse files
committed
Implement reserve_len and reserve_len_exact for VecMap
1 parent 34d6800 commit 868acdf

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
@@ -139,6 +139,52 @@ impl<V> VecMap<V> {
139139
self.v.capacity()
140140
}
141141

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

0 commit comments

Comments
 (0)