refactor: forbid clippy::string_slice

This commit is contained in:
link2xt
2024-11-18 22:13:14 +00:00
committed by l
parent 3235c8bc9f
commit c18a476806
7 changed files with 28 additions and 24 deletions

View File

@@ -47,20 +47,27 @@ use crate::stock_str;
/// end of the shortened string.
pub(crate) fn truncate(buf: &str, approx_chars: usize) -> Cow<str> {
let count = buf.chars().count();
if count > approx_chars + DC_ELLIPSIS.len() {
let end_pos = buf
.char_indices()
.nth(approx_chars)
.map(|(n, _)| n)
.unwrap_or_default();
if count <= approx_chars + DC_ELLIPSIS.len() {
return Cow::Borrowed(buf);
}
let end_pos = buf
.char_indices()
.nth(approx_chars)
.map(|(n, _)| n)
.unwrap_or_default();
if let Some(index) = buf[..end_pos].rfind([' ', '\n']) {
Cow::Owned(format!("{}{}", &buf[..=index], DC_ELLIPSIS))
} else {
Cow::Owned(format!("{}{}", &buf[..end_pos], DC_ELLIPSIS))
}
if let Some(index) = buf.get(..end_pos).and_then(|s| s.rfind([' ', '\n'])) {
Cow::Owned(format!(
"{}{}",
&buf.get(..=index).unwrap_or_default(),
DC_ELLIPSIS
))
} else {
Cow::Borrowed(buf)
Cow::Owned(format!(
"{}{}",
&buf.get(..end_pos).unwrap_or_default(),
DC_ELLIPSIS
))
}
}