Help me convince my coworkers to make UTF8 parsing safer
Hello :)
I have a large Rust codebase at work, and it has almost no unsafe code. One of the unsafe bits is something. Below a simplified version:
struct AsciiString{
str: [u8; 20],
end: u8,
};
impl StringWrapper<S> {
pub fn as_str(&self) -> &str {
unsafe { std::str::from_utf8_unchecked(&self.str[..self.end as usize]) }
}
}
I want to remove this unsafe code and replace it with something safer, like TryFrom, or, worst case, use std::str::from_utf8 and immediatelyunwrap the result.
I tried to convince my colleagues (who resist changing this part of the code without due reason) to do something about this, giving the argument that it's better to have a localized panic coming from unwrapping the Result of std::str::from_uf8, than to have UB that mysteriously breaks something somewhere else in the code (given that this particular String comes from users, and attackers might input invalid UTF8 to try and crash our system).
Someone asked me why parsing invalid UTf8 would lead to UB, and I realized I didn't really know. i just assumed that was the case, because std::str::from_utf8_unchecked is an unsafe function.
Can from_utf8 actually cause UB in this situation?
Thanks :)