Skip to content

Commit

Permalink
Add from_const_with_len_unchecked
Browse files Browse the repository at this point in the history
  • Loading branch information
Expyron authored and mbrubeck committed Jan 13, 2024
1 parent e29cccc commit c638a0b
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2384,6 +2384,20 @@ impl<T, const N: usize> SmallVec<[T; N]> {
data: SmallVecData::from_const(MaybeUninit::new(items)),
}
}

/// Constructs a new `SmallVec` on the stack from an array without
/// copying elements. Also sets the length. The user is responsible
/// for ensuring that `len <= N`.
///
/// This is a `const` version of [`SmallVec::from_buf_and_len_unchecked`] that is enabled by the feature `const_new`, with the limitation that it only works for arrays.
#[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
#[inline]
pub const unsafe fn from_const_with_len_unchecked(items: [T; N], len: usize) -> Self {
SmallVec {
capacity: len,
data: SmallVecData::from_const(MaybeUninit::new(items)),
}
}
}

#[cfg(feature = "const_generics")]
Expand Down
12 changes: 12 additions & 0 deletions src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -922,6 +922,12 @@ fn const_new() {
assert_eq!(v.len(), 2);
assert_eq!(v[0], 1);
assert_eq!(v[1], 4);
let v = const_new_with_len();
assert_eq!(v.capacity(), 4);
assert_eq!(v.len(), 3);
assert_eq!(v[0], 2);
assert_eq!(v[1], 5);
assert_eq!(v[2], 7);
}
#[cfg(feature = "const_new")]
const fn const_new_inner() -> SmallVec<[i32; 4]> {
Expand All @@ -935,6 +941,12 @@ const fn const_new_inline_sized() -> SmallVec<[i32; 4]> {
const fn const_new_inline_args() -> SmallVec<[i32; 2]> {
crate::smallvec_inline![1, 4]
}
#[cfg(feature = "const_new")]
const fn const_new_with_len() -> SmallVec<[i32; 4]> {
unsafe {
SmallVec::<[i32; 4]>::from_const_with_len_unchecked([2, 5, 7, 0], 3)
}
}

#[test]
fn empty_macro() {
Expand Down

0 comments on commit c638a0b

Please sign in to comment.