File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11# Changelog
22
3+ ## Next (Unreleased)
4+
5+ * Adds ` TinyVec::with_initial_len `
6+
37## 1.12
48
59* Add ` schemars ` support.
Original file line number Diff line number Diff line change @@ -684,6 +684,33 @@ impl<A: Array> TinyVec<A> {
684684 }
685685 }
686686
687+ /// Makes a default-initialized TinyVec with the given initial length.
688+ ///
689+ /// If the requested length is less than or equal to the array capacity you
690+ /// get an inline vec. If it's greater than you get a heap vec.
691+ /// ```
692+ /// # use tinyvec::*;
693+ /// let t = TinyVec::<[u8; 10]>::with_initial_len(5);
694+ /// assert!(t.is_inline());
695+ /// assert_eq!(t.len(), 5);
696+ ///
697+ /// let t = TinyVec::<[u8; 10]>::with_initial_len(20);
698+ /// assert!(t.is_heap());
699+ /// assert_eq!(t.len(), 20);
700+ /// ```
701+ #[ inline]
702+ #[ must_use]
703+ pub fn with_initial_len ( len : usize ) -> Self
704+ where
705+ A :: Item : Clone ,
706+ {
707+ if len <= A :: CAPACITY {
708+ TinyVec :: Inline ( ArrayVec :: from_array_len ( A :: default ( ) , len) )
709+ } else {
710+ TinyVec :: Heap ( vec ! [ A :: Item :: default ( ) ; len] )
711+ }
712+ }
713+
687714 /// Converts a `TinyVec<[T; N]>` into a `Box<[T]>`.
688715 ///
689716 /// - For `TinyVec::Heap(Vec<T>)`, it takes the `Vec<T>` and converts it into
Original file line number Diff line number Diff line change @@ -33,6 +33,22 @@ fn TinyVec_capacity() {
3333 tv. move_to_the_heap ( ) ;
3434 tv. extend_from_slice ( & [ 1 , 2 , 3 , 4 ] ) ;
3535 assert_eq ! ( tv. capacity( ) , 4 ) ;
36+
37+ let tv = TinyVec :: < [ i32 ; 10 ] > :: with_capacity ( 5 ) ;
38+ assert ! ( tv. is_inline( ) ) ;
39+ assert ! ( tv. capacity( ) >= 5 ) ;
40+
41+ let tv = TinyVec :: < [ i32 ; 10 ] > :: with_capacity ( 20 ) ;
42+ assert ! ( tv. is_heap( ) ) ;
43+ assert ! ( tv. capacity( ) >= 20 ) ;
44+
45+ let tv = TinyVec :: < [ i32 ; 10 ] > :: with_initial_len ( 5 ) ;
46+ assert ! ( tv. is_inline( ) ) ;
47+ assert_eq ! ( tv. len( ) , 5 ) ;
48+
49+ let tv = TinyVec :: < [ i32 ; 10 ] > :: with_initial_len ( 20 ) ;
50+ assert ! ( tv. is_heap( ) ) ;
51+ assert_eq ! ( tv. len( ) , 20 ) ;
3652}
3753
3854#[ test]
You can’t perform that action at this time.
0 commit comments