Skip to content

Commit 631e1c2

Browse files
author
bors-servo
authored
Auto merge of #63 - mbrubeck:with_capacity, r=emilio
Add a with_capacity constructor Closes #62. <!-- Reviewable:start --> --- This change is [<img src="https://reviewable.io/review_button.svg" height="34" align="absmiddle" alt="Reviewable"/>](https://reviewable.io/reviews/servo/rust-smallvec/63) <!-- Reviewable:end -->
2 parents ffbbbc8 + e5fe01e commit 631e1c2

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

lib.rs

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -273,6 +273,26 @@ impl<A: Array> SmallVec<A> {
273273
}
274274
}
275275

276+
/// Construct an empty vector with enough capacity pre-allocated to store at least `n`
277+
/// elements.
278+
///
279+
/// Will create a heap allocation only if `n` is larger than the inline capacity.
280+
///
281+
/// ```
282+
/// # use smallvec::SmallVec;
283+
///
284+
/// let v: SmallVec<[u8; 3]> = SmallVec::with_capacity(100);
285+
///
286+
/// assert!(v.is_empty());
287+
/// assert!(v.capacity() >= 100);
288+
/// ```
289+
#[inline]
290+
pub fn with_capacity(n: usize) -> Self {
291+
let mut v = SmallVec::new();
292+
v.reserve_exact(n);
293+
v
294+
}
295+
276296
/// Construct a new `SmallVec` from a `Vec<A::Item>` without copying
277297
/// elements.
278298
///
@@ -1156,6 +1176,19 @@ pub mod tests {
11561176
assert!(Some(SmallVec::<[&u32; 2]>::new()).is_some());
11571177
}
11581178

1179+
#[test]
1180+
fn test_with_capacity() {
1181+
let v: SmallVec<[u8; 3]> = SmallVec::with_capacity(1);
1182+
assert!(v.is_empty());
1183+
assert!(!v.spilled());
1184+
assert_eq!(v.capacity(), 3);
1185+
1186+
let v: SmallVec<[u8; 3]> = SmallVec::with_capacity(10);
1187+
assert!(v.is_empty());
1188+
assert!(v.spilled());
1189+
assert_eq!(v.capacity(), 10);
1190+
}
1191+
11591192
#[test]
11601193
fn drain() {
11611194
let mut v: SmallVec<[u8; 2]> = SmallVec::new();
@@ -1663,6 +1696,7 @@ pub mod tests {
16631696
assert_eq!(small_vec.as_ref(), data.as_ref());
16641697
}
16651698

1699+
#[cfg(feature = "serde")]
16661700
extern crate bincode;
16671701

16681702
#[cfg(feature = "serde")]

0 commit comments

Comments
 (0)