Skip to content

Commit 031fd9b

Browse files
authored
Rollup merge of rust-lang#95098 - shepmaster:vec-from-array-ref, r=dtolnay
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"); } ```
2 parents 7062db2 + 5dd7027 commit 031fd9b

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

library/alloc/src/vec/mod.rs

+42
Original file line numberDiff line numberDiff line change
@@ -2933,6 +2933,48 @@ impl<T, const N: usize> From<[T; N]> for Vec<T> {
29332933
}
29342934
}
29352935

2936+
#[cfg(not(no_global_oom_handling))]
2937+
#[stable(feature = "vec_from_array_ref", since = "1.61.0")]
2938+
impl<T: Clone, const N: usize> From<&[T; N]> for Vec<T> {
2939+
/// Allocate a `Vec<T>` and fill it by cloning `s`'s items.
2940+
///
2941+
/// # Examples
2942+
///
2943+
/// ```
2944+
/// assert_eq!(Vec::from(b"raw"), vec![b'r', b'a', b'w']);
2945+
/// ```
2946+
#[cfg(not(test))]
2947+
fn from(s: &[T; N]) -> Vec<T> {
2948+
s.to_vec()
2949+
}
2950+
2951+
#[cfg(test)]
2952+
fn from(s: &[T; N]) -> Vec<T> {
2953+
crate::slice::to_vec(s, Global)
2954+
}
2955+
}
2956+
2957+
#[cfg(not(no_global_oom_handling))]
2958+
#[stable(feature = "vec_from_array_ref", since = "1.61.0")]
2959+
impl<T: Clone, const N: usize> From<&mut [T; N]> for Vec<T> {
2960+
/// Allocate a `Vec<T>` and fill it by cloning `s`'s items.
2961+
///
2962+
/// # Examples
2963+
///
2964+
/// ```
2965+
/// assert_eq!(Vec::from(&mut [1, 2, 3]), vec![1, 2, 3]);
2966+
/// ```
2967+
#[cfg(not(test))]
2968+
fn from(s: &mut [T; N]) -> Vec<T> {
2969+
s.to_vec()
2970+
}
2971+
2972+
#[cfg(test)]
2973+
fn from(s: &mut [T; N]) -> Vec<T> {
2974+
crate::slice::to_vec(s, Global)
2975+
}
2976+
}
2977+
29362978
#[stable(feature = "vec_from_cow_slice", since = "1.14.0")]
29372979
impl<'a, T> From<Cow<'a, [T]>> for Vec<T>
29382980
where

0 commit comments

Comments
 (0)