Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Changelog

## Next (Unreleased)

* Adds `TinyVec::with_initial_len`

## 1.12

* Add `schemars` support.
Expand Down
27 changes: 27 additions & 0 deletions src/tinyvec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -684,6 +684,33 @@ impl<A: Array> TinyVec<A> {
}
}

/// 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<T>)`, it takes the `Vec<T>` and converts it into
Expand Down
16 changes: 16 additions & 0 deletions tests/tinyvec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
Loading