Info
This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: More efficient implementation of `String.truncated_lossy`
More efficient implementation of `String.truncated_lossy`
โ Rust ๐ 2025-07-08 ๐ค surdeus ๐๏ธ 3I want to call String.truncate
but it may panic, and this is unacceptable as it introduces a DOS attack vector. So in my ad-hoc std lib ystd I implemented a lossy version of this function that I was already using like this:
/// Like [String::truncate] but doesn't panic.
///
/// Somebody please optimize this implementation
fn truncated_lossy(mut self, new_len: usize) -> String {
// SAFETY: We then copy basically the whole string confirming its all UTF-8
unsafe { self.as_mut_vec() }.truncate(new_len);
String::from_utf8_lossy(self.as_bytes()).into_owned()
}
Source here: YMap/ystd/src/string.rs at 6b8261119e918b2f63dade10b65889a28715912a ยท ActuallyHappening/YMap ยท GitHub
I'm sure some better rustaceons would love to spend a few minuteshours thinking up the optimal solution, so I post it here and will copy+paste+cargo release a new version of ystd when that happens
3 posts - 3 participants
๐ท๏ธ rust_feed