diff options
author | rabite <rabite@posteo.de> | 2020-01-27 02:16:31 +0100 |
---|---|---|
committer | rabite <rabite@posteo.de> | 2020-01-27 02:51:15 +0100 |
commit | 19f08a0eeb95d20c9cc303279b3e58f9bf122b9a (patch) | |
tree | 08350b0f0d7b1b56b610573e9c3ff9ebb6532f60 /src/term.rs | |
parent | 874e7e306f7abebf8336c86051981a246ff894e5 (diff) |
changed sized_string() to return string slice instaed of allocating
Diffstat (limited to 'src/term.rs')
-rw-r--r-- | src/term.rs | 28 |
1 files changed, 19 insertions, 9 deletions
diff --git a/src/term.rs b/src/term.rs index d13ff29..b35dc37 100644 --- a/src/term.rs +++ b/src/term.rs @@ -220,15 +220,25 @@ pub fn cell_ratio() -> HResult<f32> { Ok(ratio) } -pub fn sized_string(string: &str, xsize: u16) -> String { - string.chars().fold("".to_string(), |acc, ch| { - let width: usize = unicode_width::UnicodeWidthStr::width(acc.as_str()); - if width + 1 >= xsize as usize { - acc - } else { - acc + &ch.to_string() - } - }) +pub fn sized_string(string: &str, xsize: u16) -> &str { + let len = string.char_indices() + .map(|(i, ch)| { + if ch.is_ascii() { + (i, 1) + } else { + (i, UnicodeWidthChar::width(ch).unwrap_or(0)) + } + }) + .scan(0, |slen, (i, chlen)| { + *slen += chlen; + Some((i, *slen)) + }) + .take_while(|(_, slen)| slen < &(xsize as usize)) + .map(|(i,_)| i) + .last() + .unwrap_or(0); + + &string[0..len+1] } #[derive(Debug)] |