diff --git a/Cargo.toml b/Cargo.toml index ca1d2b5..82adfa5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,3 +6,4 @@ edition = "2018" [dependencies] term = "0.5.2" +term_size = "0.3.1" diff --git a/src/lib.rs b/src/lib.rs index d4d6b01..88e3cf5 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -178,6 +178,35 @@ pub fn print_lastline(line: &str) { flush_stdout(); } +// thanks https://blog.csdn.net/star_xiong/article/details/89401149 +pub fn find_char_boundary(s: &str, index: usize) -> usize { + if s.len() <= index { + return index; + } + let mut new_index = index; + while !s.is_char_boundary(new_index) { + new_index += 1; + } + new_index +} + +pub fn get_term_width_message(message: &str, left: usize) -> String { + match term_size::dimensions() { + None => message.to_string(), + Some((w, _h)) => { + let len = message.len(); + if w > len { + return message.to_string(); + } + let mut s = String::new(); + s.push_str(&message[0..find_char_boundary(&message, w-10-5-left)]); + s.push_str("[...]"); + s.push_str(&message[find_char_boundary(&message, len-10)..]); + s + }, + } +} + pub fn parse_size(size: &str) -> XResult { let lower_size = size.to_lowercase(); let no_last_b_size = if lower_size.ends_with("b") {