pub const ESTIMATED_CHARS_PER_LINE: usize = 64;
pub const LIKELY_CHARS_PER_LINE_MAX: usize = ESTIMATED_CHARS_PER_LINE * 4;
#[inline]
pub fn format_numbered_line(line_number: usize, content: &str, max_line_number: usize) -> String {
let width = max_line_number.checked_ilog10().unwrap_or(0) as usize + 1;
format!("{:>width$}\t{}", line_number, content)
}
pub fn truncate_text(text: &str, max_bytes: usize) -> (&str, bool) {
if text.len() <= max_bytes {
return (text, false);
}
let mut end = max_bytes;
while end > 0 && !text.is_char_boundary(end) {
end -= 1;
}
(&text[..end], true)
}
pub fn truncate_line(line: &str, max_chars: usize) -> (&str, bool) {
if line.len() <= max_chars {
return (line, false);
}
let Some((byte_pos, _)) = line.char_indices().nth(max_chars) else {
return (line, false);
};
(&line[..byte_pos], true)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn format_numbered_line_pads_correctly() {
assert_eq!(format_numbered_line(1, "hello", 9), "1\thello");
assert_eq!(format_numbered_line(1, "hello", 10), " 1\thello");
assert_eq!(format_numbered_line(1, "hello", 100), " 1\thello");
}
#[test]
fn truncate_text_preserves_short_text() {
let (text, truncated) = truncate_text("hello", 10);
assert_eq!(text, "hello");
assert!(!truncated);
}
#[test]
fn truncate_text_truncates_long_text() {
let (text, truncated) = truncate_text("hello world", 5);
assert_eq!(text, "hello");
assert!(truncated);
}
#[test]
fn truncate_text_respects_utf8_boundaries() {
let (text, truncated) = truncate_text("héllo", 2);
assert_eq!(text, "h");
assert!(truncated);
}
#[test]
fn truncate_line_preserves_short_line() {
let (line, truncated) = truncate_line("hello", 10);
assert_eq!(line, "hello");
assert!(!truncated);
}
#[test]
fn truncate_line_truncates_by_char_count() {
let (line, truncated) = truncate_line("héllo", 3);
assert_eq!(line, "hél");
assert!(truncated);
}
}