From f0bb177899a8989ac33a39ec8c00938b908187f8 Mon Sep 17 00:00:00 2001 From: Expyron <5100376+Expyron@users.noreply.github.com> Date: Sat, 18 Nov 2023 10:03:44 +0100 Subject: [PATCH] Add `from_const_with_len_unchecked` --- src/lib.rs | 14 ++++++++++++++ src/tests.rs | 12 ++++++++++++ 2 files changed, 26 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index f9a6c8a..cadb5d8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -2384,6 +2384,20 @@ impl 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")] diff --git a/src/tests.rs b/src/tests.rs index 936ad6f..3eab846 100644 --- a/src/tests.rs +++ b/src/tests.rs @@ -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]> { @@ -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() {