Review of unsafe usage

Adapting @quinedot’s playground, not the original:

You could try if something like this (playground link) compiles to the desired result. In principle, doing .into_iter().map(…).collect() on a Vec<T> turning it back into Vec<T> or even into Vec<T1> where T1 has the same size and alignment as T should operate in-place due to specializations in the standard library using the InPlaceIterable trait. I haven’t got the time to check if this approach does indeed optimize in the desired way.

The idea is to have a Vec<Vec<&'static str>> outside of the loop, and start by turning it into Vec<Vec<&'lifetime str>> by variance, then working with that and after draining every inner vec, turn it back into Vec<Vec<&'static str>>. This works by using the into_iter-map-collect approach on two levels. I don’t know if the take(0) I’ve added helps or hurts, I thought it might help the optimizer to be sure that the vec is empty at this point, one should probably look at the assembly (or do benchmarking) with or without the take(0) call. Another thing I don’t know is if .map(|_| "") something like .map(|_| unreachable!()) is better or if it doesn’t make a difference.

2 Likes