Skip to content

Commit 27e10e2

Browse files
committed
Implement From<{&,&mut} [T; N]> for Vec<T>
1 parent 55be59d commit 27e10e2

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

library/alloc/src/vec/mod.rs

+30
Original file line numberDiff line numberDiff line change
@@ -3101,6 +3101,36 @@ impl<T: Clone> From<&mut [T]> for Vec<T> {
31013101
}
31023102
}
31033103

3104+
#[cfg(not(no_global_oom_handling))]
3105+
#[stable(feature = "vec_from_array_ref", since = "CURRENT_RUSTC_VERSION")]
3106+
impl<T: Clone, const N: usize> From<&[T; N]> for Vec<T> {
3107+
/// Allocate a `Vec<T>` and fill it by cloning `s`'s items.
3108+
///
3109+
/// # Examples
3110+
///
3111+
/// ```
3112+
/// assert_eq!(Vec::from(&[1, 2, 3]), vec![1, 2, 3]);
3113+
/// ```
3114+
fn from(s: &[T; N]) -> Vec<T> {
3115+
Self::from(s.as_slice())
3116+
}
3117+
}
3118+
3119+
#[cfg(not(no_global_oom_handling))]
3120+
#[stable(feature = "vec_from_array_ref", since = "CURRENT_RUSTC_VERSION")]
3121+
impl<T: Clone, const N: usize> From<&mut [T; N]> for Vec<T> {
3122+
/// Allocate a `Vec<T>` and fill it by cloning `s`'s items.
3123+
///
3124+
/// # Examples
3125+
///
3126+
/// ```
3127+
/// assert_eq!(Vec::from(&mut [1, 2, 3]), vec![1, 2, 3]);
3128+
/// ```
3129+
fn from(s: &mut [T; N]) -> Vec<T> {
3130+
Self::from(s.as_mut_slice())
3131+
}
3132+
}
3133+
31043134
#[cfg(not(no_global_oom_handling))]
31053135
#[stable(feature = "vec_from_array", since = "1.44.0")]
31063136
impl<T, const N: usize> From<[T; N]> for Vec<T> {

library/alloc/tests/vec.rs

+10
Original file line numberDiff line numberDiff line change
@@ -2563,3 +2563,13 @@ fn test_box_zero_allocator() {
25632563
// Ensure all ZSTs have been freed.
25642564
assert!(alloc.state.borrow().0.is_empty());
25652565
}
2566+
2567+
#[test]
2568+
fn test_vec_from_array_ref() {
2569+
assert_eq!(Vec::from(&[1, 2, 3]), vec![1, 2, 3]);
2570+
}
2571+
2572+
#[test]
2573+
fn test_vec_from_array_mut_ref() {
2574+
assert_eq!(Vec::from(&mut [1, 2, 3]), vec![1, 2, 3]);
2575+
}

0 commit comments

Comments
 (0)