Skip to content

Commit

Permalink
Auto merge of #111278 - EFanZh:implement-from-array-refs-for-vec, r=d…
Browse files Browse the repository at this point in the history
…tolnay

Implement `From<{&,&mut} [T; N]>` for `Vec<T>` where `T: Clone`

Currently, if `T` implements `Clone`, we can create a `Vec<T>` from an `&[T]` or an `&mut [T]`, can we also support creating a `Vec<T>` from an `&[T; N]` or an `&mut [T; N]`? Also, do I need to add `#[inline]` to the implementation?

ACP: rust-lang/libs-team#220. [Accepted]

Closes #100880.
  • Loading branch information
bors committed Sep 28, 2023
2 parents 2ba4eb2 + 27e10e2 commit aeaa5c3
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
30 changes: 30 additions & 0 deletions library/alloc/src/vec/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3154,6 +3154,36 @@ impl<T: Clone> From<&mut [T]> for Vec<T> {
}
}

#[cfg(not(no_global_oom_handling))]
#[stable(feature = "vec_from_array_ref", since = "CURRENT_RUSTC_VERSION")]
impl<T: Clone, const N: usize> From<&[T; N]> for Vec<T> {
/// Allocate a `Vec<T>` and fill it by cloning `s`'s items.
///
/// # Examples
///
/// ```
/// assert_eq!(Vec::from(&[1, 2, 3]), vec![1, 2, 3]);
/// ```
fn from(s: &[T; N]) -> Vec<T> {
Self::from(s.as_slice())
}
}

#[cfg(not(no_global_oom_handling))]
#[stable(feature = "vec_from_array_ref", since = "CURRENT_RUSTC_VERSION")]
impl<T: Clone, const N: usize> From<&mut [T; N]> for Vec<T> {
/// Allocate a `Vec<T>` and fill it by cloning `s`'s items.
///
/// # Examples
///
/// ```
/// assert_eq!(Vec::from(&mut [1, 2, 3]), vec![1, 2, 3]);
/// ```
fn from(s: &mut [T; N]) -> Vec<T> {
Self::from(s.as_mut_slice())
}
}

#[cfg(not(no_global_oom_handling))]
#[stable(feature = "vec_from_array", since = "1.44.0")]
impl<T, const N: usize> From<[T; N]> for Vec<T> {
Expand Down
10 changes: 10 additions & 0 deletions library/alloc/tests/vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2562,3 +2562,13 @@ fn test_box_zero_allocator() {
// Ensure all ZSTs have been freed.
assert!(alloc.state.borrow().0.is_empty());
}

#[test]
fn test_vec_from_array_ref() {
assert_eq!(Vec::from(&[1, 2, 3]), vec![1, 2, 3]);
}

#[test]
fn test_vec_from_array_mut_ref() {
assert_eq!(Vec::from(&mut [1, 2, 3]), vec![1, 2, 3]);
}

0 comments on commit aeaa5c3

Please sign in to comment.