From 8f3f7305b53c145de921e87936ee55141dd6cc39 Mon Sep 17 00:00:00 2001 From: Trevor Spiteri Date: Wed, 23 Sep 2020 10:07:20 +0200 Subject: [PATCH] Add from_ref and from_mut to core::array --- library/core/src/array/mod.rs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/library/core/src/array/mod.rs b/library/core/src/array/mod.rs index c1d3aca6fdd4f..9e4262781e6ef 100644 --- a/library/core/src/array/mod.rs +++ b/library/core/src/array/mod.rs @@ -436,3 +436,21 @@ impl [T; N] { self } } + +/// 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(elem: &T) -> &[T; 1] { + // SAFETY: a reference is guaranteed to be valid for reads. The returned + // reference cannot be mutated as it is an immutable reference. + let ptr = elem as *const T as *const [T; 1]; + unsafe { &*ptr } +} + +/// 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_mut(elem: &mut T) -> &mut [T; 1] { + // SAFETY: a mutable reference is guaranteed to be valid for writes. + // The reference cannot be accessed by another pointer as it is an mutable reference. + let ptr = elem as *mut T as *mut [T; 1]; + unsafe { &mut *ptr } +}