From 6fe8c3e918132236dea127e5e2577f9965ec2e39 Mon Sep 17 00:00:00 2001 From: oech3 <79379754+oech3@users.noreply.github.com> Date: Mon, 4 May 2026 21:08:24 +0900 Subject: [PATCH] factor: remove unsafe str::from_utf8_unchecked --- src/uu/factor/src/factor.rs | 19 +++++-------------- 1 file changed, 5 insertions(+), 14 deletions(-) diff --git a/src/uu/factor/src/factor.rs b/src/uu/factor/src/factor.rs index 6f418387366..3f8cc93fb02 100644 --- a/src/uu/factor/src/factor.rs +++ b/src/uu/factor/src/factor.rs @@ -113,22 +113,13 @@ impl Display for NumError<'_> { /// the invalid ones as escaped octal, like GNU. For example, the /// (escaped) string "\xFFabc\x1C" is formatted as "\377abc\034". fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match str::from_utf8(self.0) { - Ok(s) => write!(f, "{s}"), - Err(e) => { - let valid = e.valid_up_to(); - let cont = valid + e.error_len().unwrap_or(1); - // SAFETY: `self.0` has been checked to contain valid - // UTF-8 sequences up to `valid`. - write!(f, "{}", unsafe { - str::from_utf8_unchecked(&self.0[..valid]) - })?; - for b in &self.0[valid..cont] { - write!(f, "\\{b:03o}")?; - } - ::fmt(&Self(&self.0[cont..]), f) + for chunk in self.0.utf8_chunks() { + f.write_str(chunk.valid())?; + for &b in chunk.invalid() { + write!(f, "\\{b:03o}")?; } } + Ok(()) } }