Skip to content

Commit

Permalink
Rollup merge of rust-lang#95098 - shepmaster:vec-from-array-ref, r=dt…
Browse files Browse the repository at this point in the history
…olnay

impl From<&[T; N]> and From<&mut [T; N]> for Vec<T>

I really wanted to write:

```rust
fn example(a: impl Into<Vec<u8>>) {}

fn main() {
    example(b"raw");
}
```
  • Loading branch information
Dylan-DPC committed Mar 28, 2022
2 parents d88c03c + 5dd7027 commit 8bfc03f
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions library/alloc/src/vec/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2933,6 +2933,48 @@ impl<T, const N: usize> From<[T; N]> for Vec<T> {
}
}

#[cfg(not(no_global_oom_handling))]
#[stable(feature = "vec_from_array_ref", since = "1.61.0")]
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(b"raw"), vec![b'r', b'a', b'w']);
/// ```
#[cfg(not(test))]
fn from(s: &[T; N]) -> Vec<T> {
s.to_vec()
}

#[cfg(test)]
fn from(s: &[T; N]) -> Vec<T> {
crate::slice::to_vec(s, Global)
}
}

#[cfg(not(no_global_oom_handling))]
#[stable(feature = "vec_from_array_ref", since = "1.61.0")]
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]);
/// ```
#[cfg(not(test))]
fn from(s: &mut [T; N]) -> Vec<T> {
s.to_vec()
}

#[cfg(test)]
fn from(s: &mut [T; N]) -> Vec<T> {
crate::slice::to_vec(s, Global)
}
}

#[stable(feature = "vec_from_cow_slice", since = "1.14.0")]
impl<'a, T> From<Cow<'a, [T]>> for Vec<T>
where
Expand Down

0 comments on commit 8bfc03f

Please sign in to comment.