aboutsummaryrefslogtreecommitdiff
path: root/src/util
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--src/util/formatting.rs50
-rw-r--r--src/util/mod.rs1
2 files changed, 51 insertions, 0 deletions
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::<Vec<&str>>()
+ .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)
+ }
+}
diff --git a/src/util/mod.rs b/src/util/mod.rs
index fdd4603..9442257 100644
--- a/src/util/mod.rs
+++ b/src/util/mod.rs
@@ -1 +1,2 @@
pub mod web;
+pub mod formatting;