File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed
Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff 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 ( ) ;
You can’t perform that action at this time.
0 commit comments