Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add from_const_with_len_unchecked #329

Merged
merged 1 commit into from
Jan 13, 2024
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
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