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 disagree in the sense that you can rewrite the code to use the trick and also not allocate in advance. Nothing about the trick requires you to allocate up front: before writing to out[n] you can extend the vector if it’s out of bounds. Or, after incrementing n, do out.push(0).

You should try writing it out. Doing it without introducing another unpredictable branch is harder than it looks.

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.