@@ -184,6 +184,18 @@ impl<T, const N: usize> const BorrowMut<[T]> for [T; N] {
184184 }
185185}
186186
187+ /// Tries to create an array `[T; N]` by copying from a slice `&[T]`. Succeeds if
188+ /// `slice.len() == N`.
189+ ///
190+ /// ```
191+ /// let bytes: [u8; 3] = [1, 0, 2];
192+ ///
193+ /// let bytes_head: [u8; 2] = <[u8; 2]>::try_from(&bytes[0..2]).unwrap();
194+ /// assert_eq!(1, u16::from_le_bytes(bytes_head));
195+ ///
196+ /// let bytes_tail: [u8; 2] = bytes[1..3].try_into().unwrap();
197+ /// assert_eq!(512, u16::from_le_bytes(bytes_tail));
198+ /// ```
187199#[ stable( feature = "try_from" , since = "1.34.0" ) ]
188200impl < T , const N : usize > TryFrom < & [ T ] > for [ T ; N ]
189201where
@@ -196,6 +208,18 @@ where
196208 }
197209}
198210
211+ /// Tries to create an array `[T; N]` by copying from a mutable slice `&mut [T]`.
212+ /// Succeeds if `slice.len() == N`.
213+ ///
214+ /// ```
215+ /// let mut bytes: [u8; 3] = [1, 0, 2];
216+ ///
217+ /// let bytes_head: [u8; 2] = <[u8; 2]>::try_from(&mut bytes[0..2]).unwrap();
218+ /// assert_eq!(1, u16::from_le_bytes(bytes_head));
219+ ///
220+ /// let bytes_tail: [u8; 2] = (&mut bytes[1..3]).try_into().unwrap();
221+ /// assert_eq!(512, u16::from_le_bytes(bytes_tail));
222+ /// ```
199223#[ stable( feature = "try_from_mut_slice_to_array" , since = "1.59.0" ) ]
200224impl < T , const N : usize > TryFrom < & mut [ T ] > for [ T ; N ]
201225where
@@ -208,6 +232,18 @@ where
208232 }
209233}
210234
235+ /// Tries to create an array ref `&[T; N]` from a slice ref `&[T]`. Succeeds if
236+ /// `slice.len() == N`.
237+ ///
238+ /// ```
239+ /// let bytes: [u8; 3] = [1, 0, 2];
240+ ///
241+ /// let bytes_head: &[u8; 2] = <&[u8; 2]>::try_from(&bytes[0..2]).unwrap();
242+ /// assert_eq!(1, u16::from_le_bytes(*bytes_head));
243+ ///
244+ /// let bytes_tail: &[u8; 2] = bytes[1..3].try_into().unwrap();
245+ /// assert_eq!(512, u16::from_le_bytes(*bytes_tail));
246+ /// ```
211247#[ stable( feature = "try_from" , since = "1.34.0" ) ]
212248impl < ' a , T , const N : usize > TryFrom < & ' a [ T ] > for & ' a [ T ; N ] {
213249 type Error = TryFromSliceError ;
@@ -223,6 +259,18 @@ impl<'a, T, const N: usize> TryFrom<&'a [T]> for &'a [T; N] {
223259 }
224260}
225261
262+ /// Tries to create a mutable array ref `&mut [T; N]` from a mutable slice ref
263+ /// `&mut [T]`. Succeeds if `slice.len() == N`.
264+ ///
265+ /// ```
266+ /// let mut bytes: [u8; 3] = [1, 0, 2];
267+ ///
268+ /// let bytes_head: &mut [u8; 2] = <&mut [u8; 2]>::try_from(&mut bytes[0..2]).unwrap();
269+ /// assert_eq!(1, u16::from_le_bytes(*bytes_head));
270+ ///
271+ /// let bytes_tail: &mut [u8; 2] = (&mut bytes[1..3]).try_into().unwrap();
272+ /// assert_eq!(512, u16::from_le_bytes(*bytes_tail));
273+ /// ```
226274#[ stable( feature = "try_from" , since = "1.34.0" ) ]
227275impl < ' a , T , const N : usize > TryFrom < & ' a mut [ T ] > for & ' a mut [ T ; N ] {
228276 type Error = TryFromSliceError ;
0 commit comments