Skip to content

Does [T]::array_chunks really need to be an iterator? #76354

Open
@scottmcm

Description

@scottmcm

After bit after reviewing the code in #75021 I had a thought: if this iterator is mostly just a wrapper on a slice iterator, does it even need to be an iterator at all?

The original .chunks() call does (as does .windows), because the slices it wants to return don't exist anywhere.

But the arrays returned by array_chunks are inline in the original slice allocation, so the API could just return the slice that the method is already creating, instead of hiding it in an iterator.

To be more concrete:

impl [T] { 
    pub fn array_chunks<const N: usize>(&self) -> (&[[T;N]], &[T]);
    pub fn array_chunks_mut<const N: usize>(&mut self) -> (&mut [[T;N]], &mut [T]);
}

Not only would this be more general (the ArrayChunks type doesn't currently expose the slice), but I think it would make it less likely that people would forget to correctly handle the .remainder(). (While still being easy to ignore it with .0 if they insist.) And returning tuples like this has precedent with split_* and align_to and such. (Many other names could work too, like .as_chunks(_mut).)

Also, such a method would be nice to have as the inverse of a hypothetical flatten: &[[T; N]] -> &[T]. (EDIT: No longer as hypothetical, #95629.)

array_chunks tracking issue #74985

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-arrayArea: `[T; N]`B-unstableBlocker: Implemented in the nightly compiler and unstable.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