From 9857b8a456ff07ac423fa45928cf14db225605c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Kijewski?= Date: Fri, 14 Jun 2024 16:30:16 +0200 Subject: [PATCH] filter: simplify center --- askama/src/filters/mod.rs | 32 ++++++++++---------------------- 1 file changed, 10 insertions(+), 22 deletions(-) diff --git a/askama/src/filters/mod.rs b/askama/src/filters/mod.rs index ed380aa8..22d9059d 100644 --- a/askama/src/filters/mod.rs +++ b/askama/src/filters/mod.rs @@ -486,31 +486,19 @@ pub fn capitalize(s: impl ToString) -> Result { /// Centers the value in a field of a given width #[inline] -pub fn center(src: impl ToString, dst_len: usize) -> Result { - fn center(src: String, dst_len: usize) -> Result { - let len = src.len(); - if dst_len <= len || dst_len >= MAX_LEN { - Ok(src) - } else { - let diff = dst_len - len; - let mid = diff / 2; - let r = diff % 2; - let mut buf = String::with_capacity(dst_len); - - for _ in 0..mid { - buf.push(' '); - } - - buf.push_str(&src); +pub fn center(src: impl fmt::Display, width: usize) -> Result { + Ok(Center { src, width }) +} - for _ in 0..mid + r { - buf.push(' '); - } +struct Center { + src: T, + width: usize, +} - Ok(buf) - } +impl fmt::Display for Center { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{: ^1$}", self.src, self.width.min(MAX_LEN)) } - center(src.to_string(), dst_len) } /// Count the words in that string.