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/hooks/wolfram_alpha.rs | 11 ++++++---- src/util/formatting.rs | 50 ++++++++++++++++++++++++++++++++++++++++++++++ src/util/mod.rs | 1 + 3 files changed, 58 insertions(+), 4 deletions(-) create mode 100644 src/util/formatting.rs diff --git a/src/hooks/wolfram_alpha.rs b/src/hooks/wolfram_alpha.rs index cb4bc4c..e440eb8 100644 --- a/src/hooks/wolfram_alpha.rs +++ b/src/hooks/wolfram_alpha.rs @@ -1,4 +1,4 @@ -use crate::util::web::shorten_url; +use crate::util::{formatting::truncate, web::shorten_url}; use anyhow::{bail, Context, Error, Result}; use futures::try_join; use irc::client::prelude::*; @@ -97,8 +97,8 @@ async fn wa_query( Ok(format!( "{} - {}", + truncate(&to_single_string(wa_res), 250), // Same length as in gonzobot &user_url_shortened, - to_single_string(wa_res) )) } @@ -134,8 +134,11 @@ mod tests { mockito::start(); let res = wa_query("5/10", None, Some(&mockito::server_url())).await?; - let res_without_link = res.splitn(2, "-").collect::>()[1].trim(); - assert_eq!(res_without_link, "Exact result: 1/2 - Decimal form: 0.5"); + let res_without_link = res.rsplitn(2, "-").collect::>()[1..].join(" "); + assert_eq!( + res_without_link.trim(), + "Exact result: 1/2 - Decimal form: 0.5" + ); Ok(()) } } 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) + } +} 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; -- cgit v1.2.3