pub fn truncate_str(s: &str, max_chars: usize) -> String {
truncate_impl(s, max_chars, "...")
}
pub fn truncate_with_note(s: &str, max_chars: usize) -> String {
truncate_impl(s, max_chars, "\n... (truncated)")
}
fn truncate_impl(s: &str, max_chars: usize, suffix: &str) -> String {
if s.len() <= max_chars {
return s.to_string();
}
let char_count = s.chars().count();
if char_count <= max_chars {
return s.to_string();
}
let suffix_len = suffix.chars().count();
if max_chars <= suffix_len {
return suffix.chars().take(max_chars).collect();
}
let truncated: String = s.chars().take(max_chars - suffix_len).collect();
format!("{}{}", truncated, suffix)
}
pub fn floor_char_boundary(s: &str, byte_limit: usize) -> usize {
if byte_limit >= s.len() {
return s.len();
}
let mut i = byte_limit;
while i > 0 && !s.is_char_boundary(i) {
i -= 1;
}
i
}
pub fn truncation_notice(shown_chars: usize, total_chars: usize) -> String {
truncation_notice_with_hint(
shown_chars,
total_chars,
"If the user needs the full result, tell them it is longer than you can see \
and re-run with a narrower filter, a count (e.g. `wc -l`), or pagination.",
)
}
pub fn truncation_notice_with_hint(
shown_chars: usize,
total_chars: usize,
remediation_hint: &str,
) -> String {
let omitted = total_chars.saturating_sub(shown_chars);
format!(
"[⚠OUTPUT TRUNCATED — {shown} of {total} characters shown; {omitted} omitted and \
NOT visible to you. Do NOT enumerate, list, count, or quote any item that is not \
literally present in the text you can see — inventing the omitted content is an \
error. {hint}]",
shown = shown_chars,
total = total_chars,
omitted = omitted,
hint = remediation_hint,
)
}