use std::ops::Add; use std::time::Duration; pub(crate) fn truncate_with_dots(to_truncate: String, new_size: usize) -> String { let mut new_string = to_truncate.clone(); let dots = "..."; if new_size as isize - 3 > 0 { new_string.truncate(new_size - 3); new_string.add(dots) } else { let mut dots_to_ret = String::new(); for _i in 0..new_size { dots_to_ret.push('.'); } return dots_to_ret; } } pub(crate) fn human_readable_duration(duration: Duration) -> String { let total_duration = duration.as_secs(); let mut minutes = total_duration / 60; let seconds = total_duration % 60; if minutes >= 60 { let hours = minutes / 60; minutes = minutes % 60; return format!( "{} hour(s), {} minute(s) and {} second(s)", hours, minutes, seconds ); } format!("{} minute(s) and {} second(s)", minutes, seconds) } #[cfg(test)] mod test { use super::*; #[test] fn should_truncate_short_string_as_expected() { let example_string = "example"; let expected_string = ".."; assert_eq!( expected_string, truncate_with_dots(example_string.to_string(), 2) ) } #[test] fn should_truncate_long_string_as_expected() { let example_string = "this is a very long string"; let expected_string = "this i..."; assert_eq!( expected_string, truncate_with_dots(example_string.to_string(), 9) ) } #[test] fn should_print_correct_duration_into_human_readable_format() { let duration: Duration = Duration::new(124, 0); let got = human_readable_duration(duration); assert_eq!("2 minute(s) and 4 second(s)", got) } #[test] fn should_handle_duration_in_hours() { let duration1 = Duration::new(3621, 0); let got1 = human_readable_duration(duration1); assert_eq!("1 hour(s), 0 minute(s) and 21 second(s)", got1); let duration2 = Duration::new(5021, 0); let got2 = human_readable_duration(duration2); assert_eq!("1 hour(s), 23 minute(s) and 41 second(s)", got2); } }