-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Open
Labels
A-lintArea: New lintsArea: New lints
Description
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 likeu32::from_le_bytes(chunk.try_into().unwrap())
. - It emphasizes the existence of the remainder, which might be ignored (say with a
_
pattern) but withchunks_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.
ada4a
Metadata
Metadata
Assignees
Labels
A-lintArea: New lintsArea: New lints