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

Add from_ref and from_mut to core::array #77095

Closed
wants to merge 1 commit into from
Closed
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
18 changes: 18 additions & 0 deletions library/core/src/array/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -436,3 +436,21 @@ impl<T, const N: usize> [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<T>(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<T>(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 }
}