Worth noting that as written the "trick" results in memory usage proportional to the size of the input rather than the output. If the filter rejects most of the input the difference could be quite noticeable.
I discussed this with a coworker earlier this week and the best they were able to come up with was
for &x in input {
out.push(x);
n += (x > threshold) as usize;
out.truncate(n);
}
which works but is ugly af imo.I think yours works. Alternatively in the loop:
if out.len() < n {
out.push(0);
}
out[n] = x;
n += (x > threshold) as usize;
In this case the if will be predicted well because it only triggers log(N) times, given how the std lib extends vectors.