pub fn truncate_with_ellipsis(s: &str, max_chars: usize) -> String {
match s.char_indices().nth(max_chars) {
Some((idx, _)) => {
let truncated = &s[..idx];
format!("{}...", truncated.trim_end())
}
None => s.to_string(),
}
}
pub enum MaybeSet<T> {
Set(T),
Unset,
Null,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_truncate_ascii_no_truncation() {
assert_eq!(truncate_with_ellipsis("hello", 10), "hello");
assert_eq!(truncate_with_ellipsis("hello world", 50), "hello world");
}
#[test]
fn test_truncate_ascii_with_truncation() {
assert_eq!(truncate_with_ellipsis("hello world", 5), "hello...");
assert_eq!(
truncate_with_ellipsis("This is a long message", 10),
"This is a..."
);
}
#[test]
fn test_truncate_empty_string() {
assert_eq!(truncate_with_ellipsis("", 10), "");
}
#[test]
fn test_truncate_at_exact_boundary() {
assert_eq!(truncate_with_ellipsis("hello", 5), "hello");
}
#[test]
fn test_truncate_emoji_single() {
let s = "π¦";
assert_eq!(truncate_with_ellipsis(s, 10), s);
assert_eq!(truncate_with_ellipsis(s, 1), s);
}
#[test]
fn test_truncate_emoji_multiple() {
let s = "ππππ"; assert_eq!(truncate_with_ellipsis(s, 2), "ππ...");
assert_eq!(truncate_with_ellipsis(s, 3), "πππ...");
}
#[test]
fn test_truncate_mixed_ascii_emoji() {
assert_eq!(truncate_with_ellipsis("Hello π¦ World", 8), "Hello π¦...");
assert_eq!(truncate_with_ellipsis("Hi π", 10), "Hi π");
}
#[test]
fn test_truncate_cjk_characters() {
let s = "θΏζ―δΈδΈͺζ΅θ―ζΆζ―η¨ζ₯触εε΄©ζΊηδΈζ"; let result = truncate_with_ellipsis(s, 16);
assert!(result.ends_with("..."));
assert!(result.is_char_boundary(result.len() - 1));
}
#[test]
fn test_truncate_accented_characters() {
let s = "cafΓ© rΓ©sumΓ© naΓ―ve";
assert_eq!(truncate_with_ellipsis(s, 10), "cafΓ© rΓ©sum...");
}
#[test]
fn test_truncate_unicode_edge_case() {
let s = "aΓ©δ½ ε₯½π¦"; assert_eq!(truncate_with_ellipsis(s, 3), "aΓ©δ½ ...");
}
#[test]
fn test_truncate_long_string() {
let s = "a".repeat(200);
let result = truncate_with_ellipsis(&s, 50);
assert_eq!(result.len(), 53); assert!(result.ends_with("..."));
}
#[test]
fn test_truncate_zero_max_chars() {
assert_eq!(truncate_with_ellipsis("hello", 0), "...");
}
}