pub fn truncate_chars(text: &str, max_chars: usize) -> String {
text.chars().take(max_chars).collect()
}
pub fn truncate_chars_counted(text: &str, max_chars: usize) -> Option<(String, usize)> {
let total = text.chars().count();
if total <= max_chars {
return None;
}
Some((truncate_chars(text, max_chars), total - max_chars))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_truncate_chars() {
assert_eq!(truncate_chars("hello world", 5), "hello");
assert_eq!(truncate_chars("hello", 5), "hello");
assert_eq!(truncate_chars("hi", 5), "hi");
assert_eq!(truncate_chars("hello", 0), "");
assert_eq!(truncate_chars("", 5), "");
assert_eq!(truncate_chars("ππ", 1), "π");
assert_eq!(truncate_chars("ππ", 2), "ππ");
assert_eq!(truncate_chars("γγγ«γ‘γ―", 2), "γγ");
assert_eq!(truncate_chars("μλ
νμΈμ", 3), "μλ
ν");
assert_eq!(truncate_chars("δ½ ε₯½δΈη", 1), "δ½ ");
}
#[test]
fn test_truncate_chars_counted() {
assert_eq!(truncate_chars_counted("hello", 5), None);
assert_eq!(truncate_chars_counted("δ½ ε₯½δΈη", 4), None);
assert_eq!(
truncate_chars_counted("δ½ ε₯½δΈη", 2),
Some(("δ½ ε₯½".to_string(), 2))
);
let cjk = "ζ₯".repeat(30_000);
let (text, dropped) = truncate_chars_counted(&cjk, 20_000).unwrap();
assert_eq!(text.chars().count(), 20_000);
assert_eq!(dropped, 10_000);
}
}