add array from_ref
This commit is contained in:
parent
e0bc267512
commit
179f63dafc
@ -19,6 +19,20 @@ mod iter;
|
||||
#[unstable(feature = "array_value_iter", issue = "65798")]
|
||||
pub use iter::IntoIter;
|
||||
|
||||
/// Converts a reference to `T` into a reference to an array of length 1 (without copying).
|
||||
#[unstable(feature = "array_from_ref", issue = "none")]
|
||||
pub fn from_ref<T>(s: &T) -> &[T; 1] {
|
||||
// SAFETY: Converting `&T` to `&[T; 1]` is sound.
|
||||
unsafe { &*(s as *const T).cast::<[T; 1]>() }
|
||||
}
|
||||
|
||||
/// Converts a mutable reference to `T` into a mutable reference to an array of length 1 (without copying).
|
||||
#[unstable(feature = "array_from_ref", issue = "none")]
|
||||
pub fn from_mut<T>(s: &mut T) -> &mut [T; 1] {
|
||||
// SAFETY: Converting `&mut T` to `&mut [T; 1]` is sound.
|
||||
unsafe { &mut *(s as *mut T).cast::<[T; 1]>() }
|
||||
}
|
||||
|
||||
/// Utility trait implemented only on arrays of fixed size
|
||||
///
|
||||
/// This trait can be used to implement other traits on fixed-size arrays
|
||||
|
@ -1,4 +1,4 @@
|
||||
use core::array::{FixedSizeArray, IntoIter};
|
||||
use core::array::{self, FixedSizeArray, IntoIter};
|
||||
use core::convert::TryFrom;
|
||||
|
||||
#[test]
|
||||
@ -19,6 +19,21 @@ fn fixed_size_array() {
|
||||
assert_eq!(FixedSizeArray::as_mut_slice(&mut empty_zero_sized).len(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn array_from_ref() {
|
||||
let value: String = "Hello World!".into();
|
||||
let arr: &[String; 1] = array::from_ref(&value);
|
||||
assert_eq!(&[value.clone()], arr);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn array_from_mut() {
|
||||
let mut value: String = "Hello World".into();
|
||||
let arr: &mut [String; 1] = array::from_mut(&mut value);
|
||||
arr[0].push_str("!");
|
||||
assert_eq!(&value, "Hello World!");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn array_try_from() {
|
||||
macro_rules! test {
|
||||
|
@ -1,5 +1,6 @@
|
||||
#![feature(alloc_layout_extra)]
|
||||
#![feature(array_chunks)]
|
||||
#![feature(array_from_ref)]
|
||||
#![feature(array_methods)]
|
||||
#![feature(array_map)]
|
||||
#![feature(array_windows)]
|
||||
|
Loading…
Reference in New Issue
Block a user