diff options
author | Clement Tsang <34804052+ClementTsang@users.noreply.github.com> | 2023-11-24 08:13:06 +0000 |
---|---|---|
committer | GitHub <noreply@github.com> | 2023-11-24 03:13:06 -0500 |
commit | 94e4573ebcfb25728a0265f1907e203263b889a1 (patch) | |
tree | 1102569b91c5c185672ed66e82abd6383f379238 | |
parent | a93521d2b10b0d3d05c103a7837a5a1a2a1a1b64 (diff) |
refactor: add fast branch if the string is short enough to not be truncated (#1333)
* refactor: add fast branch if the entire string is definitely not truncated
* update comments
-rw-r--r-- | src/utils/gen_util.rs | 27 |
1 files changed, 16 insertions, 11 deletions
diff --git a/src/utils/gen_util.rs b/src/utils/gen_util.rs index 97c6dbc1..e423b6b2 100644 --- a/src/utils/gen_util.rs +++ b/src/utils/gen_util.rs @@ -101,21 +101,26 @@ fn grapheme_width(g: &str) -> usize { fn truncate_str<U: Into<usize>>(content: &str, width: U) -> String { let width = width.into(); - if width > 0 { + if content.len() <= width { + // If the entire string fits in the width, then we just + // need to copy the entire string over. + + content.to_owned() + } else if width > 0 { if content.is_ascii() { - // If the entire string is ASCII, we can use a much simpler approach. + // If the entire string is ASCII, we can use a much simpler approach + // in regards to what we truncate. - if content.len() <= width { - content.to_owned() - } else { - let mut text = String::with_capacity(width); - let (keep, _throw) = content.split_at(width - 1); - text.push_str(keep); - text.push('…'); + let mut text = String::with_capacity(width); + let (keep, _throw) = content.split_at(width - 1); + text.push_str(keep); + text.push('…'); - text - } + text } else { + // Otherwise iterate by grapheme and greedily fit as many graphemes + // as width will allow. + let mut text = String::with_capacity(width); let mut curr_width = 0; let mut early_break = false; |