Rollup merge of #76310 - scottmcm:array-try_from-vec, r=dtolnay

Add `[T; N]: TryFrom<Vec<T>>` (insta-stable)

This is very similar to the [existing](https://doc.rust-lang.org/nightly/std/convert/trait.TryFrom.html#impl-TryFrom%3CBox%3C%5BT%5D%3E%3E) `Box<[T; N]>: TryFrom<Box<[T]>>`, but allows avoiding the `shrink_to_fit` if you have a vector and not a boxed slice.

Like the slice equivalents of this, it fails if the length of the vector is not exactly `N`.
This uses `Vec<T>` as the `Error` type to return the input, like how the `Rc<[T]> -> Rc<[T; N]>` (and Arc) ones also reflect the input directly in the error type.

```rust
#[stable(feature = "array_try_from_vec", since = "1.47.0")]
impl<T, const N: usize> TryFrom<Vec<T>> for [T; N] {
    type Error = Vec<T>;
    fn try_from(mut vec: Vec<T>) -> Result<[T; N], Vec<T>>;
}
```

Inspired by this zulip thread: https://rust-lang.zulipchat.com/#narrow/stream/219381-t-libs/topic/APIs.20for.20getting.20stuff.20from.20a.20Vec.20by.20owned/near/209048103
This commit is contained in:
Ralf Jung 2020-09-19 11:47:39 +02:00 committed by GitHub
commit bac2f39350
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 52 additions and 0 deletions

View File

@ -55,6 +55,7 @@
#![stable(feature = "rust1", since = "1.0.0")]
use core::cmp::{self, Ordering};
use core::convert::TryFrom;
use core::fmt;
use core::hash::{Hash, Hasher};
use core::intrinsics::{arith_offset, assume};
@ -2754,6 +2755,57 @@ impl From<&str> for Vec<u8> {
}
}
#[stable(feature = "array_try_from_vec", since = "1.48.0")]
impl<T, const N: usize> TryFrom<Vec<T>> for [T; N] {
type Error = Vec<T>;
/// Gets the entire contents of the `Vec<T>` as an array,
/// if its size exactly matches that of the requested array.
///
/// # Examples
///
/// ```
/// use std::convert::TryInto;
/// assert_eq!(vec![1, 2, 3].try_into(), Ok([1, 2, 3]));
/// assert_eq!(<Vec<i32>>::new().try_into(), Ok([]));
/// ```
///
/// If the length doesn't match, the input comes back in `Err`:
/// ```
/// use std::convert::TryInto;
/// let r: Result<[i32; 4], _> = (0..10).collect::<Vec<_>>().try_into();
/// assert_eq!(r, Err(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]));
/// ```
///
/// If you're fine with just getting a prefix of the `Vec<T>`,
/// you can call [`.truncate(N)`](Vec::truncate) first.
/// ```
/// use std::convert::TryInto;
/// let mut v = String::from("hello world").into_bytes();
/// v.sort();
/// v.truncate(2);
/// let [a, b]: [_; 2] = v.try_into().unwrap();
/// assert_eq!(a, b' ');
/// assert_eq!(b, b'd');
/// ```
fn try_from(mut vec: Vec<T>) -> Result<[T; N], Vec<T>> {
if vec.len() != N {
return Err(vec);
}
// SAFETY: `.set_len(0)` is always sound.
unsafe { vec.set_len(0) };
// SAFETY: A `Vec`'s pointer is always aligned properly, and
// the alignment the array needs is the same as the items.
// We checked earlier that we have sufficient items.
// The items will not double-drop as the `set_len`
// tells the `Vec` not to also drop them.
let array = unsafe { ptr::read(vec.as_ptr() as *const [T; N]) };
Ok(array)
}
}
////////////////////////////////////////////////////////////////////////////////
// Clone-on-write
////////////////////////////////////////////////////////////////////////////////