@@ -154,6 +154,39 @@ pub const fn from_mut<T>(s: &mut T) -> &mut [T; 1] {
154
154
unsafe { & mut * ( s as * mut T ) . cast :: < [ T ; 1 ] > ( ) }
155
155
}
156
156
157
+ /// Tries to create an array `[T; N]` by copying from a slice `&[T]`.
158
+ /// Succeeds if `slice.len() == N`.
159
+ ///
160
+ /// # Example
161
+ ///
162
+ /// ```
163
+ /// #![feature(array_try_from_slice)]
164
+ ///
165
+ /// use core::array;
166
+ ///
167
+ /// let data = array::try_from_slice(&[255, 127, 63, 31]).unwrap();
168
+ ///
169
+ /// let value = u32::from_le_bytes(data);
170
+ /// assert_eq!(value, 0x1F3F7FFF);
171
+ /// ```
172
+ #[ inline]
173
+ #[ unstable( feature = "array_try_from_slice" , issue = "133440" ) ]
174
+ #[ rustc_const_unstable( feature = "array_try_from_slice" , issue = "133440" ) ]
175
+ pub const fn try_from_slice < T , const N : usize > ( slice : & [ T ] ) -> Result < [ T ; N ] , TryFromSliceError >
176
+ where
177
+ T : Copy ,
178
+ {
179
+ if slice. len ( ) == N {
180
+ let ptr = slice. as_ptr ( ) as * const [ T ; N ] ;
181
+
182
+ // SAFETY: The underlying array of a slice can be reinterpreted as an actual array `[T; N]` if `N` is not greater than the slice's length.
183
+ let me = unsafe { * ptr } ;
184
+ Ok ( me)
185
+ } else {
186
+ Err ( TryFromSliceError ( ( ) ) )
187
+ }
188
+ }
189
+
157
190
/// The error type returned when a conversion from a slice to an array fails.
158
191
#[ stable( feature = "try_from" , since = "1.34.0" ) ]
159
192
#[ rustc_allowed_through_unstable_modules]
@@ -214,8 +247,8 @@ impl<T, const N: usize> BorrowMut<[T]> for [T; N] {
214
247
}
215
248
}
216
249
217
- /// Tries to create an array `[T; N]` by copying from a slice `&[T]`. Succeeds if
218
- /// `slice.len() == N`.
250
+ /// Tries to create an array `[T; N]` by copying from a slice `&[T]`.
251
+ /// Succeeds if `slice.len() == N`.
219
252
///
220
253
/// ```
221
254
/// let bytes: [u8; 3] = [1, 0, 2];
@@ -235,7 +268,7 @@ where
235
268
236
269
#[ inline]
237
270
fn try_from ( slice : & [ T ] ) -> Result < [ T ; N ] , TryFromSliceError > {
238
- < & Self > :: try_from ( slice) . copied ( )
271
+ try_from_slice ( slice)
239
272
}
240
273
}
241
274
@@ -260,7 +293,7 @@ where
260
293
261
294
#[ inline]
262
295
fn try_from ( slice : & mut [ T ] ) -> Result < [ T ; N ] , TryFromSliceError > {
263
- < Self > :: try_from ( & * slice)
296
+ try_from_slice ( slice)
264
297
}
265
298
}
266
299
0 commit comments