← All lints

copy_sort_writeback

L0522Idiomswarn

Copy-mutate-writeback on a slice

copying xs[l..r] to sort/reverse/rotate and writing it back: mutate xs[l..r] in place

Flagged
var xs = [5, 4, 3, 2, 1]
let sub = xs[1..4].sorted()
for i in 1..4: xs[i] = sub[i - 1]
print(xs)
Write instead
var xs = [5, 4, 3, 2, 1]
xs[1..4].sort()
print(xs)

Why

Copying a contiguous slice xs[l..r] into a temporary List, sorting/reversing/rotating it, and writing the elements back into xs[l..r] allocates an unnecessary copy. Mutable slice views lend xs[l..r] in O(1)O(1) via IndexedMut, so xs[l..r].sort(...) / .reverse() / .rotate_left(...) runs in place with no copy. cpl fix rewrites the copy-mutate-writeback sequence when the temporary is not read afterward.

The practice it serves

A hand-written pattern the language or the standard library already says in one step. Family: S.seq: ordering and ranks.

Not flagged

A near miss: close to the pattern, but not it.

Near miss
var xs = [5, 4, 3, 2, 1]
let sub = xs[1..4].sorted()
print(sub, xs)

Turn it off

For one block, wrap it in with lint(copy_sort_writeback: allow):. For a project, add copy_sort_writeback = "allow" under [lints] in cp.toml.

Generated from spec/lints/copy_sort_writeback, the same record the linter is built from.