1
0
mirror of https://github.com/jht5945/rust_util.git synced 2025-12-27 15:40:03 +08:00

add find_char_boundary, get_term_width_message

This commit is contained in:
2019-08-06 08:33:43 +08:00
parent ba3fe4366d
commit 0a582517aa
2 changed files with 30 additions and 0 deletions

View File

@@ -6,3 +6,4 @@ edition = "2018"
[dependencies]
term = "0.5.2"
term_size = "0.3.1"

View File

@@ -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<i64> {
let lower_size = size.to_lowercase();
let no_last_b_size = if lower_size.ends_with("b") {