diff --git a/CHANGELOG.md b/CHANGELOG.md index 74dae1d..4449dff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## Next (Unreleased) + +* Adds `TinyVec::with_initial_len` + ## 1.12 * Add `schemars` support. diff --git a/src/tinyvec.rs b/src/tinyvec.rs index 76343bc..b58ac8f 100644 --- a/src/tinyvec.rs +++ b/src/tinyvec.rs @@ -684,6 +684,33 @@ impl TinyVec { } } + /// Makes a default-initialized TinyVec with the given initial length. + /// + /// If the requested length is less than or equal to the array capacity you + /// get an inline vec. If it's greater than you get a heap vec. + /// ``` + /// # use tinyvec::*; + /// let t = TinyVec::<[u8; 10]>::with_initial_len(5); + /// assert!(t.is_inline()); + /// assert_eq!(t.len(), 5); + /// + /// let t = TinyVec::<[u8; 10]>::with_initial_len(20); + /// assert!(t.is_heap()); + /// assert_eq!(t.len(), 20); + /// ``` + #[inline] + #[must_use] + pub fn with_initial_len(len: usize) -> Self + where + A::Item: Clone, + { + if len <= A::CAPACITY { + TinyVec::Inline(ArrayVec::from_array_len(A::default(), len)) + } else { + TinyVec::Heap(vec![A::Item::default(); len]) + } + } + /// Converts a `TinyVec<[T; N]>` into a `Box<[T]>`. /// /// - For `TinyVec::Heap(Vec)`, it takes the `Vec` and converts it into diff --git a/tests/tinyvec.rs b/tests/tinyvec.rs index c0f1b07..2be639e 100644 --- a/tests/tinyvec.rs +++ b/tests/tinyvec.rs @@ -33,6 +33,22 @@ fn TinyVec_capacity() { tv.move_to_the_heap(); tv.extend_from_slice(&[1, 2, 3, 4]); assert_eq!(tv.capacity(), 4); + + let tv = TinyVec::<[i32; 10]>::with_capacity(5); + assert!(tv.is_inline()); + assert!(tv.capacity() >= 5); + + let tv = TinyVec::<[i32; 10]>::with_capacity(20); + assert!(tv.is_heap()); + assert!(tv.capacity() >= 20); + + let tv = TinyVec::<[i32; 10]>::with_initial_len(5); + assert!(tv.is_inline()); + assert_eq!(tv.len(), 5); + + let tv = TinyVec::<[i32; 10]>::with_initial_len(20); + assert!(tv.is_heap()); + assert_eq!(tv.len(), 20); } #[test]