Skip to content

Commit c638a0b

Browse files
Expyronmbrubeck
authored andcommitted
Add from_const_with_len_unchecked
1 parent e29cccc commit c638a0b

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

src/lib.rs

+14
Original file line numberDiff line numberDiff line change
@@ -2384,6 +2384,20 @@ impl<T, const N: usize> SmallVec<[T; N]> {
23842384
data: SmallVecData::from_const(MaybeUninit::new(items)),
23852385
}
23862386
}
2387+
2388+
/// Constructs a new `SmallVec` on the stack from an array without
2389+
/// copying elements. Also sets the length. The user is responsible
2390+
/// for ensuring that `len <= N`.
2391+
///
2392+
/// 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.
2393+
#[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
2394+
#[inline]
2395+
pub const unsafe fn from_const_with_len_unchecked(items: [T; N], len: usize) -> Self {
2396+
SmallVec {
2397+
capacity: len,
2398+
data: SmallVecData::from_const(MaybeUninit::new(items)),
2399+
}
2400+
}
23872401
}
23882402

23892403
#[cfg(feature = "const_generics")]

src/tests.rs

+12
Original file line numberDiff line numberDiff line change
@@ -922,6 +922,12 @@ fn const_new() {
922922
assert_eq!(v.len(), 2);
923923
assert_eq!(v[0], 1);
924924
assert_eq!(v[1], 4);
925+
let v = const_new_with_len();
926+
assert_eq!(v.capacity(), 4);
927+
assert_eq!(v.len(), 3);
928+
assert_eq!(v[0], 2);
929+
assert_eq!(v[1], 5);
930+
assert_eq!(v[2], 7);
925931
}
926932
#[cfg(feature = "const_new")]
927933
const fn const_new_inner() -> SmallVec<[i32; 4]> {
@@ -935,6 +941,12 @@ const fn const_new_inline_sized() -> SmallVec<[i32; 4]> {
935941
const fn const_new_inline_args() -> SmallVec<[i32; 2]> {
936942
crate::smallvec_inline![1, 4]
937943
}
944+
#[cfg(feature = "const_new")]
945+
const fn const_new_with_len() -> SmallVec<[i32; 4]> {
946+
unsafe {
947+
SmallVec::<[i32; 4]>::from_const_with_len_unchecked([2, 5, 7, 0], 3)
948+
}
949+
}
938950

939951
#[test]
940952
fn empty_macro() {

0 commit comments

Comments
 (0)