More efficient implementation of `String.truncated_lossy`

โš“ Rust    ๐Ÿ“… 2025-07-08    ๐Ÿ‘ค surdeus    ๐Ÿ‘๏ธ 3      

surdeus

I 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 :slight_smile:

3 posts - 3 participants

Read full topic

๐Ÿท๏ธ rust_feed