Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement TryFrom<&[T]> for &[T; N] #44764

Merged
merged 8 commits into from
Nov 1, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions src/libcore/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@

use borrow::{Borrow, BorrowMut};
use cmp::Ordering;
use convert::TryFrom;
use fmt;
use hash::{Hash, self};
use marker::Unsize;
Expand Down Expand Up @@ -57,6 +58,30 @@ unsafe impl<T, A: Unsize<[T]>> FixedSizeArray<T> for A {
}
}

/// The error type returned when a conversion from a slice to an array fails.
#[unstable(feature = "try_from", issue = "33417")]
#[derive(Debug, Copy, Clone)]
pub struct TryFromSliceError(());
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should probably implement Error in libstd.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should the Display implementation also be in libstd or libcore?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See e45e8ab


impl fmt::Display for TryFromSliceError {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(self.__description(), f)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not use the description method from the Error trait?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Error is declined in libstd, not libcore

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Defined* (I'm on mobile)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see, never mind.

}
}

impl TryFromSliceError {
#[unstable(feature = "array_error_internals",
reason = "available through Error trait and this method should not \
be exposed publicly",
issue = "0")]
#[inline]
#[doc(hidden)]
pub fn __description(&self) -> &str {
"could not convert slice to array"
}
}

macro_rules! __impl_slice_eq1 {
($Lhs: ty, $Rhs: ty) => {
__impl_slice_eq1! { $Lhs, $Rhs, Sized }
Expand Down Expand Up @@ -123,6 +148,34 @@ macro_rules! array_impls {
}
}

#[unstable(feature = "try_from", issue = "33417")]
impl<'a, T> TryFrom<&'a [T]> for &'a [T; $N] {
type Error = TryFromSliceError;

fn try_from(slice: &[T]) -> Result<&[T; $N], TryFromSliceError> {
if slice.len() == $N {
let ptr = slice.as_ptr() as *const [T; $N];
unsafe { Ok(&*ptr) }
} else {
Err(TryFromSliceError(()))
}
}
}

#[unstable(feature = "try_from", issue = "33417")]
impl<'a, T> TryFrom<&'a mut [T]> for &'a mut [T; $N] {
type Error = TryFromSliceError;

fn try_from(slice: &mut [T]) -> Result<&mut [T; $N], TryFromSliceError> {
if slice.len() == $N {
let ptr = slice.as_mut_ptr() as *mut [T; $N];
unsafe { Ok(&mut *ptr) }
} else {
Err(TryFromSliceError(()))
}
}
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Hash> Hash for [T; $N] {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
Expand Down
23 changes: 23 additions & 0 deletions src/libcore/tests/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use core::array::FixedSizeArray;
use core::convert::TryFrom;

#[test]
fn fixed_size_array() {
Expand All @@ -26,3 +27,25 @@ fn fixed_size_array() {
assert_eq!(FixedSizeArray::as_mut_slice(&mut empty_array).len(), 0);
assert_eq!(FixedSizeArray::as_mut_slice(&mut empty_zero_sized).len(), 0);
}

#[test]
fn array_try_from() {
macro_rules! test {
($($N:expr)+) => {
$({
type Array = [u8; $N];
let array: Array = [0; $N];
let slice: &[u8] = &array[..];

let result = <&Array>::try_from(slice);
assert_eq!(&array, result.unwrap());
})+
}
}
test! {
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29
30 31 32
}
}
8 changes: 8 additions & 0 deletions src/libstd/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ use borrow::Cow;
use cell;
use char;
use convert;
use core::array;
use fmt::{self, Debug, Display};
use mem::transmute;
use num;
Expand Down Expand Up @@ -282,6 +283,13 @@ impl Error for num::TryFromIntError {
}
}

#[unstable(feature = "try_from", issue = "33417")]
impl Error for array::TryFromSliceError {
fn description(&self) -> &str {
self.__description()
}
}

#[stable(feature = "rust1", since = "1.0.0")]
impl Error for num::ParseFloatError {
fn description(&self) -> &str {
Expand Down
2 changes: 2 additions & 0 deletions src/libstd/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,7 @@
#![feature(allow_internal_unsafe)]
#![feature(allow_internal_unstable)]
#![feature(align_offset)]
#![feature(array_error_internals)]
#![feature(asm)]
#![feature(box_syntax)]
#![feature(cfg_target_has_atomic)]
Expand All @@ -257,6 +258,7 @@
#![feature(core_intrinsics)]
#![feature(dropck_eyepatch)]
#![feature(exact_size_is_empty)]
#![feature(fixed_size_array)]
#![feature(float_from_str_radix)]
#![feature(fn_traits)]
#![feature(fnbox)]
Expand Down