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<Box<[T]>> for Box<[T; N]> #47245

Closed
wants to merge 8 commits into from
Closed
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
74 changes: 74 additions & 0 deletions src/liballoc/boxed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ use raw_vec::RawVec;
use core::any::Any;
use core::borrow;
use core::cmp::Ordering;
use core::convert::TryFrom;
use core::fmt;
use core::hash::{self, Hash, Hasher};
use core::iter::FusedIterator;
Expand Down Expand Up @@ -623,6 +624,79 @@ impl From<Box<str>> for Box<[u8]> {
}
}

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

Choose a reason for hiding this comment

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

Please add a brief example involving TryFromSliceError. See FromUtf8Error for examples of examples.


#[unstable(feature = "try_from", issue = "33417")]
impl<T> fmt::Debug for TryFromSliceError<T> {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("TryFromSliceError").finish()
}
}

#[unstable(feature = "try_from", issue = "33417")]
impl<T> fmt::Display for TryFromSliceError<T> {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(self.__description(), f)
}
}

impl<T> TryFromSliceError<T> {
#[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 boxed slice to boxed array"
}

/// Returns the boxed slice that was attempted to convert to a boxed array.
///
/// This method is meant to avoid allocation. It will consume the error,
/// moving out the boxed slice, so that a copy of the slice does not need to
/// be made.
#[unstable(feature = "try_from", issue = "33417")]
#[inline]
pub fn into_boxed_slice(self) -> Box<[T]> {
Copy link
Member

Choose a reason for hiding this comment

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

Please add an example showing a case in which this method is useful. The point of the example wouldn't be to show how to call this method (we can assume readers know how to call methods when they get to browsing TryFrom documentation) but to show why someone would want to call this method.

self.0
}
}

macro_rules! array_impls {
($($N:expr)+) => {
Copy link
Member

Choose a reason for hiding this comment

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

You forgot to add $(...)+ around the item.

[00:05:12]    Compiling alloc v0.0.0 (file:///checkout/src/liballoc)
[00:05:12] error: variable 'N' is still repeating at this depth
[00:05:12]    --> liballoc/boxed.rs:665:47
[00:05:12]     |
[00:05:12] 665 |         impl<T> TryFrom<Box<[T]>> for Box<[T; $N]> {
[00:05:12]     |                                               ^^
[00:05:12] 
[00:05:12] error: Could not compile `alloc`.

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

#[inline]
fn try_from(slice: Box<[T]>) -> Result<Box<[T; $N]>, TryFromSliceError<T>> {
Copy link
Member

Choose a reason for hiding this comment

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

Please add a test so that we don't break this implementation later. Something similar to the test in #44764 should work.

if slice.len() == $N {
let ptr = Box::into_raw(slice) as *mut [T; $N];
unsafe { Ok(Box::from_raw(ptr)) }
Copy link
Member

Choose a reason for hiding this comment

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

@alexcrichton is this a valid operation?

Copy link
Member

Choose a reason for hiding this comment

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

AFAIK yeah this should be safe, the destructor for Box<T> should deallocate with the size of T which in this case would be mem::size_of::<T>() * N

} else {
Err(TryFromSliceError(slice))
}
}
}
)+
}
}

array_impls! {
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
}

impl Box<Any> {
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
Expand Down
1 change: 1 addition & 0 deletions src/liballoc/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@
#![feature(staged_api)]
#![feature(str_internals)]
#![feature(trusted_len)]
#![feature(try_from)]
#![feature(unboxed_closures)]
#![feature(unicode)]
#![feature(unique)]
Expand Down
2 changes: 2 additions & 0 deletions src/libcore/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,7 @@ macro_rules! array_impls {
impl<'a, T> TryFrom<&'a [T]> for &'a [T; $N] {
type Error = TryFromSliceError;

#[inline]
fn try_from(slice: &[T]) -> Result<&[T; $N], TryFromSliceError> {
if slice.len() == $N {
let ptr = slice.as_ptr() as *const [T; $N];
Expand All @@ -166,6 +167,7 @@ macro_rules! array_impls {
impl<'a, T> TryFrom<&'a mut [T]> for &'a mut [T; $N] {
type Error = TryFromSliceError;

#[inline]
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];
Expand Down
8 changes: 8 additions & 0 deletions src/libstd/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
use alloc::allocator;
use any::TypeId;
use borrow::Cow;
use boxed;
use cell;
use char;
use convert;
Expand Down Expand Up @@ -290,6 +291,13 @@ impl Error for array::TryFromSliceError {
}
}

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

#[stable(feature = "rust1", since = "1.0.0")]
impl Error for num::ParseFloatError {
fn description(&self) -> &str {
Expand Down