abbrev.rs (991B)
1 #[inline] 2 fn floor_char_boundary(s: &str, index: usize) -> usize { 3 if index >= s.len() { 4 s.len() 5 } else { 6 let lower_bound = index.saturating_sub(3); 7 let new_index = s.as_bytes()[lower_bound..=index] 8 .iter() 9 .rposition(|b| is_utf8_char_boundary(*b)); 10 11 // SAFETY: we know that the character boundary will be within four bytes 12 unsafe { lower_bound + new_index.unwrap_unchecked() } 13 } 14 } 15 16 #[inline] 17 fn is_utf8_char_boundary(c: u8) -> bool { 18 // This is bit magic equivalent to: b < 128 || b >= 192 19 (c as i8) >= -0x40 20 } 21 22 const ABBREV_SIZE: usize = 10; 23 24 pub fn abbrev_str(name: &str) -> String { 25 if name.len() > ABBREV_SIZE { 26 let closest = floor_char_boundary(name, ABBREV_SIZE); 27 format!("{}...", &name[..closest]) 28 } else { 29 name.to_owned() 30 } 31 } 32 33 pub fn abbreviate<'a>(text: &'a str, len: usize) -> &'a str { 34 let closest = floor_char_boundary(text, len); 35 &text[..closest] 36 }