about summary refs log tree commit diff
path: root/library/core/src/array
diff options
context:
space:
mode:
authorGabriel Bjørnager Jensen <gabriel@achernar.io>2024-11-26 21:49:28 +0100
committerGabriel Bjørnager Jensen <gabriel@achernar.io>2024-11-26 21:49:28 +0100
commit4b8ca28a1e334564fbf7561c6ed6e098e2b9b1a7 (patch)
treed5efda27683b8d9afde857f8286abd4cf126b0e9 /library/core/src/array
parentdff3e7ccd4a18958c938136c4ccdc853fcc86194 (diff)
downloadrust-4b8ca28a1e334564fbf7561c6ed6e098e2b9b1a7.tar.gz
rust-4b8ca28a1e334564fbf7561c6ed6e098e2b9b1a7.zip
Add '<[T]>::as_array', '<[T]>::as_mut_array', '<*const [T]>::as_array', and '<*mut [T]>::as_mut_array' conversion methods;
Diffstat (limited to 'library/core/src/array')
-rw-r--r--library/core/src/array/mod.rs20
1 files changed, 4 insertions, 16 deletions
diff --git a/library/core/src/array/mod.rs b/library/core/src/array/mod.rs
index 67fbda34bb9..95c1eb460cd 100644
--- a/library/core/src/array/mod.rs
+++ b/library/core/src/array/mod.rs
@@ -214,8 +214,8 @@ impl<T, const N: usize> BorrowMut<[T]> for [T; N] {
     }
 }
 
-/// Tries to create an array `[T; N]` by copying from a slice `&[T]`. Succeeds if
-/// `slice.len() == N`.
+/// Tries to create an array `[T; N]` by copying from a slice `&[T]`.
+/// Succeeds if `slice.len() == N`.
 ///
 /// ```
 /// let bytes: [u8; 3] = [1, 0, 2];
@@ -282,13 +282,7 @@ impl<'a, T, const N: usize> TryFrom<&'a [T]> for &'a [T; N] {
 
     #[inline]
     fn try_from(slice: &'a [T]) -> Result<&'a [T; N], TryFromSliceError> {
-        if slice.len() == N {
-            let ptr = slice.as_ptr() as *const [T; N];
-            // SAFETY: ok because we just checked that the length fits
-            unsafe { Ok(&*ptr) }
-        } else {
-            Err(TryFromSliceError(()))
-        }
+        slice.as_array().ok_or(TryFromSliceError(()))
     }
 }
 
@@ -310,13 +304,7 @@ impl<'a, T, const N: usize> TryFrom<&'a mut [T]> for &'a mut [T; N] {
 
     #[inline]
     fn try_from(slice: &'a mut [T]) -> Result<&'a mut [T; N], TryFromSliceError> {
-        if slice.len() == N {
-            let ptr = slice.as_mut_ptr() as *mut [T; N];
-            // SAFETY: ok because we just checked that the length fits
-            unsafe { Ok(&mut *ptr) }
-        } else {
-            Err(TryFromSliceError(()))
-        }
+        slice.as_mut_array().ok_or(TryFromSliceError(()))
     }
 }