use unicode_width::UnicodeWidthChar;
#[must_use]
pub fn truncate(s: &str, max_cols: usize) -> &str {
let mut cols = 0usize;
let mut end = 0usize;
for ch in s.chars() {
let w = ch.width().unwrap_or(0);
if cols + w > max_cols {
break;
}
cols += w;
end += ch.len_utf8();
}
&s[..end]
}
#[must_use]
pub fn truncate_owned(s: &str, max_cols: usize) -> String {
truncate(s, max_cols).to_owned()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn truncate_stops_at_the_column_budget() {
assert_eq!(truncate("hello world", 5), "hello");
assert_eq!(truncate("hi", 10), "hi");
assert_eq!(truncate("hi", 0), "");
}
#[test]
fn truncate_counts_wide_characters_as_two_columns() {
assert_eq!(truncate("aあb", 2), "a");
assert_eq!(truncate("aあb", 3), "aあ");
assert_eq!(truncate("ああ", 3), "あ");
}
}