Skip to content

Commit 12ff256

Browse files
committed
implement into_array for Vec<T>
1 parent e95e732 commit 12ff256

1 file changed

Lines changed: 21 additions & 0 deletions

File tree

library/alloc/src/vec/mod.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1740,6 +1740,27 @@ impl<T, A: Allocator> Vec<T, A> {
17401740
}
17411741
}
17421742

1743+
/// Converts the Vec into a boxed array. This conversion will discard any spare capacity, if there is any, see [`Vec::shrink_to_fit`].
1744+
/// If you merely wish for a reference to an array, use [`as_array`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.as_array).
1745+
///
1746+
/// If `N` is not exactly equal to [`Vec::len`], then this method returns `None`.
1747+
///
1748+
/// # Examples
1749+
///
1750+
/// ```
1751+
/// #![feature(alloc_slice_into_array)]
1752+
/// let vec: Vec<i32> = vec![1, 2, 3];
1753+
/// let box_array: Box<[i32; 3]> = vec.clone().into_array().unwrap();
1754+
/// let not_enough_elements: Option<Box<[i32; 4]>> = vec.into_array::<4>();
1755+
/// assert!(not_enough_elements.is_none());
1756+
/// ```
1757+
#[cfg(not(no_global_oom_handling))]
1758+
#[unstable(feature = "alloc_slice_into_array", issue = "148082")]
1759+
#[must_use]
1760+
pub fn into_array<const N: usize>(self) -> Option<Box<[T; N], A>> {
1761+
(self.len() == N).then(|| self.into_boxed_slice().into_array().unwrap())
1762+
}
1763+
17431764
/// Shortens the vector, keeping the first `len` elements and dropping
17441765
/// the rest.
17451766
///

0 commit comments

Comments
 (0)