|
21 | 21 |
|
22 | 22 | use borrow::{Borrow, BorrowMut};
|
23 | 23 | use cmp::Ordering;
|
| 24 | +use convert::TryFrom; |
24 | 25 | use fmt;
|
25 | 26 | use hash::{Hash, self};
|
26 | 27 | use marker::Unsize;
|
@@ -57,6 +58,30 @@ unsafe impl<T, A: Unsize<[T]>> FixedSizeArray<T> for A {
|
57 | 58 | }
|
58 | 59 | }
|
59 | 60 |
|
| 61 | +/// The error type returned when a conversion from a slice to an array fails. |
| 62 | +#[unstable(feature = "try_from", issue = "33417")] |
| 63 | +#[derive(Debug, Copy, Clone)] |
| 64 | +pub struct TryFromSliceError(()); |
| 65 | + |
| 66 | +impl fmt::Display for TryFromSliceError { |
| 67 | + #[inline] |
| 68 | + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 69 | + fmt::Display::fmt(self.__description(), f) |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +impl TryFromSliceError { |
| 74 | + #[unstable(feature = "array_error_internals", |
| 75 | + reason = "available through Error trait and this method should not \ |
| 76 | + be exposed publicly", |
| 77 | + issue = "0")] |
| 78 | + #[inline] |
| 79 | + #[doc(hidden)] |
| 80 | + pub fn __description(&self) -> &str { |
| 81 | + "could not convert slice to array" |
| 82 | + } |
| 83 | +} |
| 84 | + |
60 | 85 | macro_rules! __impl_slice_eq1 {
|
61 | 86 | ($Lhs: ty, $Rhs: ty) => {
|
62 | 87 | __impl_slice_eq1! { $Lhs, $Rhs, Sized }
|
@@ -123,6 +148,34 @@ macro_rules! array_impls {
|
123 | 148 | }
|
124 | 149 | }
|
125 | 150 |
|
| 151 | + #[unstable(feature = "try_from", issue = "33417")] |
| 152 | + impl<'a, T> TryFrom<&'a [T]> for &'a [T; $N] { |
| 153 | + type Error = TryFromSliceError; |
| 154 | + |
| 155 | + fn try_from(slice: &[T]) -> Result<&[T; $N], TryFromSliceError> { |
| 156 | + if slice.len() == $N { |
| 157 | + let ptr = slice.as_ptr() as *const [T; $N]; |
| 158 | + unsafe { Ok(&*ptr) } |
| 159 | + } else { |
| 160 | + Err(TryFromSliceError(())) |
| 161 | + } |
| 162 | + } |
| 163 | + } |
| 164 | + |
| 165 | + #[unstable(feature = "try_from", issue = "33417")] |
| 166 | + impl<'a, T> TryFrom<&'a mut [T]> for &'a mut [T; $N] { |
| 167 | + type Error = TryFromSliceError; |
| 168 | + |
| 169 | + fn try_from(slice: &mut [T]) -> Result<&mut [T; $N], TryFromSliceError> { |
| 170 | + if slice.len() == $N { |
| 171 | + let ptr = slice.as_mut_ptr() as *mut [T; $N]; |
| 172 | + unsafe { Ok(&mut *ptr) } |
| 173 | + } else { |
| 174 | + Err(TryFromSliceError(())) |
| 175 | + } |
| 176 | + } |
| 177 | + } |
| 178 | + |
126 | 179 | #[stable(feature = "rust1", since = "1.0.0")]
|
127 | 180 | impl<T: Hash> Hash for [T; $N] {
|
128 | 181 | fn hash<H: hash::Hasher>(&self, state: &mut H) {
|
|
0 commit comments