@@ -774,6 +774,57 @@ impl<T, const N: usize> [T; N] {
774
774
}
775
775
}
776
776
777
+ /// Unsafely converts a slice of `N` elements to an array reference of `N` elements.
778
+ ///
779
+ /// # Safety
780
+ ///
781
+ /// The caller must ensure that the slice has at least `N` elements. Violating this constraint
782
+ /// causes Undefined Behaviour.
783
+ ///
784
+ /// # Examples
785
+ ///
786
+ /// ```
787
+ /// #![feature(array_from_slice)]
788
+ ///
789
+ /// let v = [1, 0, 3, 0, 5, 6];
790
+ /// // SAFETY: `&v[2..5]` is a slice of 3 elements.
791
+ /// let r = unsafe { <&[i32; 3]>::from_slice_unchecked(&v[2..5]) };
792
+ /// assert_eq!(r, &[3, 0, 5]);
793
+ /// ```
794
+ #[ inline]
795
+ #[ must_use]
796
+ const unsafe fn from_slice_unchecked < T , const N : usize > ( s : & [ T ] ) -> & [ T ; N ] {
797
+ // SAFETY: caller guarantees that `s` is a slice of at least `N` elements.
798
+ unsafe { & * ( s. as_ptr ( ) as * const [ T ; N ] ) }
799
+ }
800
+
801
+ /// Unsafely converts a mutable slice of `N` elements to a mutable array reference of `N` elements.
802
+ ///
803
+ /// # Safety
804
+ ///
805
+ /// The caller must ensure that the slice has at least `N` elements. Violating this constraint
806
+ /// causes Undefined Behaviour.
807
+ ///
808
+ /// # Examples
809
+ ///
810
+ /// ```
811
+ /// #![feature(array_from_slice)]
812
+ ///
813
+ /// let mut v = [1, 0, 3, 0, 5, 6];
814
+ /// // SAFETY: `&mut v[2..5]` is a slice of 3 elements.
815
+ /// let r = unsafe { <&mut [i32; 3]>::from_mut_slice_unchecked(&mut v[2..5]) };
816
+ /// assert_eq!(r, &[3, 0, 5]);
817
+ /// r[1] = 9;
818
+ /// assert_eq!(r, &[3, 9, 5]);
819
+ /// assert_eq!(v, [1, 0, 3, 9, 5, 6]);
820
+ /// ```
821
+ #[ inline]
822
+ #[ must_use]
823
+ const unsafe fn from_mut_slice_unchecked < T , const N : usize > ( s : & mut [ T ] ) -> & mut [ T ; N ] {
824
+ // SAFETY: caller guarantees that `s` is a slice of at least `N` elements.
825
+ unsafe { & mut * ( s. as_ptr ( ) as * mut [ T ; N ] ) }
826
+ }
827
+
777
828
/// Populate an array from the first `N` elements of `iter`
778
829
///
779
830
/// # Panics
0 commit comments