pub fn format_title(title: &str, max_length: Option<usize>) -> String {
let formatted = title
.to_lowercase()
.chars()
.filter(|c| c.is_alphanumeric() || *c == ' ' || *c == '-')
.collect::<String>()
.split_whitespace() .collect::<Vec<&str>>()
.join("_");
let max_length = max_length.unwrap_or(50);
if formatted.len() <= max_length {
return formatted;
}
let words: Vec<&str> = formatted.split('_').collect();
let mut result = String::new();
for (i, word) in words.iter().enumerate() {
if i > 0 {
if result.len() + word.len() + 1 > max_length {
break;
}
result.push('_');
}
if result.len() + word.len() > max_length {
break;
}
result.push_str(word);
}
result
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_format_title() {
assert_eq!(format_title("Hello World", None), "hello_world");
assert_eq!(
format_title("This Is A Very Long Title Indeed", None),
"this_is_a_very_long_title_indeed"
);
assert_eq!(format_title("This Is A Very Long Title Indeed", Some(20)), "this_is_a_very_long");
assert_eq!(
format_title("This Is A Very Long Title Indeed", Some(30)),
"this_is_a_very_long_title"
);
assert_eq!(format_title("short", None), "short");
assert_eq!(format_title("UPPERCASE TEXT", None), "uppercase_text");
assert_eq!(format_title("No Extra Spaces", None), "no_extra_spaces");
assert_eq!(format_title("Title with: </weird things\\>", None), "title_with_weird_things");
}
}