From 1d0ea3fdfe74d13fb35880ca8b7aef3bc1134e57 Mon Sep 17 00:00:00 2001 From: Matt Brubeck Date: Tue, 19 Sep 2017 12:20:08 -0700 Subject: [PATCH] Add a with_capacity constructor Closes #62. --- lib.rs | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/lib.rs b/lib.rs index 208ebba..d63d8ea 100644 --- a/lib.rs +++ b/lib.rs @@ -273,6 +273,26 @@ impl SmallVec { } } + /// Construct an empty vector with enough capacity pre-allocated to store at least `n` + /// elements. + /// + /// Will create a heap allocation only if `n` is larger than the inline capacity. + /// + /// ``` + /// # use smallvec::SmallVec; + /// + /// let v: SmallVec<[u8; 3]> = SmallVec::with_capacity(100); + /// + /// assert!(v.is_empty()); + /// assert!(v.capacity() >= 100); + /// ``` + #[inline] + pub fn with_capacity(n: usize) -> Self { + let mut v = SmallVec::new(); + v.reserve_exact(n); + v + } + /// Construct a new `SmallVec` from a `Vec` without copying /// elements. /// @@ -1156,6 +1176,19 @@ pub mod tests { assert!(Some(SmallVec::<[&u32; 2]>::new()).is_some()); } + #[test] + fn test_with_capacity() { + let v: SmallVec<[u8; 3]> = SmallVec::with_capacity(1); + assert!(v.is_empty()); + assert!(!v.spilled()); + assert_eq!(v.capacity(), 3); + + let v: SmallVec<[u8; 3]> = SmallVec::with_capacity(10); + assert!(v.is_empty()); + assert!(v.spilled()); + assert_eq!(v.capacity(), 10); + } + #[test] fn drain() { let mut v: SmallVec<[u8; 2]> = SmallVec::new();