From 5158e408d771ea3ec09aae530e0dc6509884871f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Commaille?= Date: Wed, 7 May 2025 10:25:34 +0200 Subject: [PATCH] utils: Simplify truncate_end_whitespaces Work with char_indices, it allows us to compute the index after the char easily. --- src/utils/string/mod.rs | 23 ++++++++--------------- 1 file changed, 8 insertions(+), 15 deletions(-) diff --git a/src/utils/string/mod.rs b/src/utils/string/mod.rs index 74a5149a..77af2014 100644 --- a/src/utils/string/mod.rs +++ b/src/utils/string/mod.rs @@ -106,25 +106,18 @@ impl StrMutExt for String { return; } - let rspaces_idx = self - .rfind(|c: char| !c.is_whitespace()) - .map(|idx| { - // We have the position of the last non-whitespace character, so the first - // whitespace character is the next one. - let mut idx = idx + 1; - - while !self.is_char_boundary(idx) { - idx += 1; - } - - idx + let new_len = self + .char_indices() + .rfind(|(_, c)| !c.is_whitespace()) + .map(|(idx, c)| { + // We have the position of the last non-whitespace character, so the last + // whitespace character is the character after it. + idx + c.len_utf8() }) // 0 means that there are only whitespaces in the string. .unwrap_or_default(); - if rspaces_idx < self.len() { - self.truncate(rspaces_idx); - } + self.truncate(new_len); } fn append_ellipsis(&mut self) {