Skip to content

slice -> array conversion function #71705

Open
@leonardo-m

Description

@leonardo-m

See the discussion here:
https://internals.rust-lang.org/t/more-about-slice-array-conversions/12251

I suggest to add two related functions (mutable and not mutable versions) that allows to replace code similar to this:

row.get_mut(8*x .. 8*x + 8).unwrap().try_into().unwrap()

In a shorter, simpler and less bug-prone way, and with only one unwrap (in this specific case there's no need to specify the length as const generic value because it's inferred by the result. In other cases you specify it with a turbofish):

row.array_from_mut(8 * x).unwrap()

The two slice methods could be like (currently they can't be const fn):

pub fn array_from<const LEN: usize>(&self, pos: usize) -> Option<&[T; LEN]> {
    if let Some(piece) = self.get(pos .. pos + LEN) {
        let temp_ptr: *const [T] = piece;
        unsafe {
            Some( std::mem::transmute(temp_ptr as *const [T; LEN]) )
        }
    } else {
        None
    }
}

pub fn array_from_mut<const LEN: usize>(&mut self, pos: usize) -> Option<&mut [T; LEN]> {
    if let Some(piece) = self.get_mut(pos .. pos + LEN) {
        let temp_ptr: *mut [T] = piece;
        unsafe {
            Some( std::mem::transmute(temp_ptr as *mut [T; LEN]) )
        }
    } else {
        None
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-arrayArea: `[T; N]`A-const-genericsArea: const generics (parameters and arguments)A-sliceArea: `[T]`C-feature-requestCategory: A feature request, i.e: not implemented / a PR.T-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions