You should avoid unsafe unless there are 2 situations:
- You are doing something which impossible to do in safe code e.g. FFI-calls. It is a main reason why unsafe ever exists.
- You proved using benchmarks that unsafe provide big speed-up and this code is bottleneck.
Your arguing
I know I could easily do a checked cast and unwrap it, but that feels a bit silly because of how certain I am that the check can never fail.
is valid about current version of your code but you would need to keep this unsafe in mind during all further development.
Unsafe greatly increase cognitive complexity of code. You cannot change any place in your function without keeping unsafe in mind, for example.
I doubt that utf8 validation adds more overhead than possible reallocation in result.insert(0, _1);
in your code.
Other nitpicks:
- You should add a comment in unsafe section which explains why it is safe. It would make easier to read a code for a other people (or other you after a year of don't touching it).
- You could define your constants as
const _0: u8 = b'0';
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…