Skip to content

Suggest as_chunks when people use chunks_exact with a constant lengthΒ #15882

@scottmcm

Description

@scottmcm

What it does

Suggest https://doc.rust-lang.org/std/primitive.slice.html#method.as_chunks (stable in 1.88) when people are using https://doc.rust-lang.org/std/primitive.slice.html#method.chunks_exact with a constant. And similarly for chunks_exact_mut.

(When the argument to chunks_exact is not a constant, this does nothing.)

Advantage

  • It gives a slice-of-arrays, rather than an iterator, which is more flexible.
  • If the chunks are iterated, the element type is an array, enabling things like array patterns (let [a, b, c, d] = *chunk;) that don't need bounds checks and avoiding noisy slice-to-array conversions like u32::from_le_bytes(chunk.try_into().unwrap()).
  • It emphasizes the existence of the remainder, which might be ignored (say with a _ pattern) but with chunks_exact it's often accidentally ignored.

Drawbacks

If you need to flip back and forth between constant and non-constant lengths, the code transformation isn't trivial.

Example

let mut it = foo.chunks_exact(4);
for chunk in &mut it { ... }
for elem in it.remainder() { ... }

Could be written as:

let (chunks, tail) = foo.as_chunks::<4>();
for chunk in chunks { ... }
for elem in tail { ... }

Comparison with existing lints

No response

Additional Context

See discussion in rust-lang/rust#53340 (comment)

Ideally this would apply for chunks too (not just chunks_exact), but for that one the transformations involved would be more complicated.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintArea: New lints

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions