From 75a855cd8d2c9ab3653e82a8ef94139571e3a7cd Mon Sep 17 00:00:00 2001 From: Lorenz Leitner Date: Tue, 12 Oct 2021 08:59:29 +0200 Subject: Move short url to back of result --- src/util/formatting.rs | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 src/util/formatting.rs (limited to 'src/util/formatting.rs') diff --git a/src/util/formatting.rs b/src/util/formatting.rs new file mode 100644 index 0000000..add3f1b --- /dev/null +++ b/src/util/formatting.rs @@ -0,0 +1,50 @@ +/// Truncates a string after a certain number of characters. +/// Function always tries to truncate on a word boundary. +/// Reimplemented from gonzobot. +pub(crate) fn truncate(text: &str, len: usize) -> String { + if text.len() <= len { + return text.to_string(); + } + format!( + "{}…", + text[..len] + .rsplitn(2, " ") + .collect::>() + .last() + .copied() + .expect("This can never happen >inb4 it happens") + ) +} + +#[cfg(test)] +mod tests { + use super::truncate; + + #[test] + fn test_truncate_with_input_of_lesser_length_than_limit() { + let input = "short text"; + let result = truncate(input, input.len() + 1); + assert_eq!(input, result) + } + + #[test] + fn test_truncate_with_input_of_equal_length_as_limit() { + let input = "short text"; + let result = truncate(input, input.len()); + assert_eq!(input, result) + } + + #[test] + fn test_truncate_with_input_of_greater_length_than_limit() { + let input = "some longer text"; + let result = truncate(input, input.len() - 1); + assert_eq!("some longer…", result) + } + + #[test] + fn test_truncate_with_input_of_greater_length_than_limit_oneword() { + let input = "somelongertext"; + let result = truncate(input, input.len() - 1); + assert_eq!("somelongertex…", result) + } +} -- cgit v1.2.3