Skip to content

ACP: add array::from_raw_parts() #602

Open
@daxpedda

Description

@daxpedda

Proposal

Problem statement

There is no "better" way to unsafely cast a [T; N] to a [U; N] or a &[T; N] to a &[U; N] apart from just pointer casting or using mem::transmute().

The idea here is that APIs like Vec::from_raw_parts() and slice::from_raw_parts() are harder to misuse and clearer then pointer casts. If instead pointer casting is the recommended way, this proposal is moot.

The example includes a comparison between both.

Motivating examples or use cases

#[repr(transparent)]
struct NonZeroWrapper<T: YourTrait>(T);

impl<T: YourTrait> NonZeroWrapper<T> {
    pub fn batch_computation<const N: usize>(values: &[Self; N]) -> [Self; N] {
        // No way to avoid pointer casts or `transmute()`.

        let t_values: &[T; N] = unsafe { &*(values as *const [Self; N]).cast() };
        let t_result = T::batch_computation(t_values);
        unsafe { (&*ManuallyDrop::new(t_result) as *const [T; N] as *const [Self; N]).read() }
    }
    
    pub fn batch_computation_vec(values: &[Self]) -> Vec<Self> {
        // Safety requirements are clear and the only obvious mistake is forgetting to use `ManuallyDrop`.

        let t_values = unsafe { slice::from_raw_parts(values.as_ptr().cast(), values.len()) };
        // This could be improved with `Vec::into_raw_parts()`.
        let mut t_result = ManuallyDrop::new(T::batch_computation_vec(t_values));
        unsafe { Vec::from_raw_parts(t_result.as_mut_ptr().cast(), t_result.len(), t_result.capacity()) }
    }
}

Solution sketch

I believe adding a method directly transforming a [T; N] to a [U; N] or a &[T; N] to a &[U; N] should be covered by the "safe transmute API". Instead what I'm proposing is to add an equivalent of Vec::from_raw_parts() and slice::from_raw_parts() for fixed arrays.

Equivalent of Vec::from_raw_parts():

impl<T, const N: usize> [T; N] {
    pub unsafe fn from_raw_parts(ptr: *mut T) -> [T; N] {
        ...
    }
}

Equivalent of slice::from_raw_parts():

pub const unsafe fn from_raw_parts<'a, T, const N: usize>(
    data: *const T,
) -> &'a [T; N] {
    ...
}

pub const unsafe fn from_raw_parts_mut<'a, T, const N: usize>(
    data: *mut T,
) -> &'a mut [T; N] {
    ...
}

The naming is not ideal.

Alternatives

To convert &[T; N] to a &[U; N] it is currently possible to just use slice::from_raw_parts() and then to convert it to a &[U; N] via TryInto.

I'm not aware of any way to convert a [T; N] to a [U; N] without just pointer casting or mem;;transmute_copy(). The simplest way seems to be ptr::read(<*mut [T; N]>::cast()).

Alternatively it seems also possible to use <[_; N]>::map() or array::from_fn() to do all this safely. The compiler seems to optimize this away to a memcpy.

Links and related work

This problem was encountered in RustCrypto/traits#1896.

What happens now?

This issue contains an API change proposal (or ACP) and is part of the libs-api team feature lifecycle. Once this issue is filed, the libs-api team will review open proposals as capability becomes available. Current response times do not have a clear estimate, but may be up to several months.

Possible responses

The libs team may respond in various different ways. First, the team will consider the problem (this doesn't require any concrete solution or alternatives to have been proposed):

  • We think this problem seems worth solving, and the standard library might be the right place to solve it.
  • We think that this probably doesn't belong in the standard library.

Second, if there's a concrete solution:

  • We think this specific solution looks roughly right, approved, you or someone else should implement this. (Further review will still happen on the subsequent implementation PR.)
  • We're not sure this is the right solution, and the alternatives or other materials don't give us enough information to be sure about that. Here are some questions we have that aren't answered, or rough ideas about alternatives we'd want to see discussed.

Metadata

Metadata

Assignees

No one assigned

    Labels

    T-libs-apiapi-change-proposalA proposal to add or alter unstable APIs in the standard libraries

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions