aboutsummaryrefslogtreecommitdiff
path: root/src/util/formatting/truncate.rs
diff options
context:
space:
mode:
authorMax Audron <audron@cocaine.farm>2021-10-19 14:03:17 +0200
committerMax Audron <audron@cocaine.farm>2021-10-19 14:06:32 +0200
commite731144025b726670cd85d43acdd93b7636de338 (patch)
tree570e32838f1308eaf79fdc52ec6daf4084e6e2fd /src/util/formatting/truncate.rs
parentfix links in readme (diff)
add formatting trait for irc codes
add an impl off the formatting trait on String to format Strings with the typical irc formatting codes for bold, italic etc
Diffstat (limited to 'src/util/formatting/truncate.rs')
-rw-r--r--src/util/formatting/truncate.rs50
1 files changed, 50 insertions, 0 deletions
diff --git a/src/util/formatting/truncate.rs b/src/util/formatting/truncate.rs
new file mode 100644
index 0000000..c1b6257
--- /dev/null
+++ b/src/util/formatting/truncate.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 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)
+ }
+}