Skip to content

Commit 179f63d

Browse files
committed
add array from_ref
1 parent e0bc267 commit 179f63d

File tree

3 files changed

+31
-1
lines changed

3 files changed

+31
-1
lines changed

library/core/src/array/mod.rs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,20 @@ mod iter;
1919
#[unstable(feature = "array_value_iter", issue = "65798")]
2020
pub use iter::IntoIter;
2121

22+
/// Converts a reference to `T` into a reference to an array of length 1 (without copying).
23+
#[unstable(feature = "array_from_ref", issue = "none")]
24+
pub fn from_ref<T>(s: &T) -> &[T; 1] {
25+
// SAFETY: Converting `&T` to `&[T; 1]` is sound.
26+
unsafe { &*(s as *const T).cast::<[T; 1]>() }
27+
}
28+
29+
/// Converts a mutable reference to `T` into a mutable reference to an array of length 1 (without copying).
30+
#[unstable(feature = "array_from_ref", issue = "none")]
31+
pub fn from_mut<T>(s: &mut T) -> &mut [T; 1] {
32+
// SAFETY: Converting `&mut T` to `&mut [T; 1]` is sound.
33+
unsafe { &mut *(s as *mut T).cast::<[T; 1]>() }
34+
}
35+
2236
/// Utility trait implemented only on arrays of fixed size
2337
///
2438
/// This trait can be used to implement other traits on fixed-size arrays

library/core/tests/array.rs

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use core::array::{FixedSizeArray, IntoIter};
1+
use core::array::{self, FixedSizeArray, IntoIter};
22
use core::convert::TryFrom;
33

44
#[test]
@@ -19,6 +19,21 @@ fn fixed_size_array() {
1919
assert_eq!(FixedSizeArray::as_mut_slice(&mut empty_zero_sized).len(), 0);
2020
}
2121

22+
#[test]
23+
fn array_from_ref() {
24+
let value: String = "Hello World!".into();
25+
let arr: &[String; 1] = array::from_ref(&value);
26+
assert_eq!(&[value.clone()], arr);
27+
}
28+
29+
#[test]
30+
fn array_from_mut() {
31+
let mut value: String = "Hello World".into();
32+
let arr: &mut [String; 1] = array::from_mut(&mut value);
33+
arr[0].push_str("!");
34+
assert_eq!(&value, "Hello World!");
35+
}
36+
2237
#[test]
2338
fn array_try_from() {
2439
macro_rules! test {

library/core/tests/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
#![feature(alloc_layout_extra)]
22
#![feature(array_chunks)]
3+
#![feature(array_from_ref)]
34
#![feature(array_methods)]
45
#![feature(array_map)]
56
#![feature(array_windows)]

0 commit comments

Comments
 (0)