Skip to content

Commit 6faab55

Browse files
Kijewskidjc
authored andcommitted
filter: simplify center
1 parent 4e829ef commit 6faab55

File tree

1 file changed

+13
-21
lines changed

1 file changed

+13
-21
lines changed

askama/src/filters/mod.rs

+13-21
Original file line numberDiff line numberDiff line change
@@ -486,31 +486,23 @@ pub fn capitalize(s: impl ToString) -> Result<impl fmt::Display, Infallible> {
486486

487487
/// Centers the value in a field of a given width
488488
#[inline]
489-
pub fn center(src: impl ToString, dst_len: usize) -> Result<impl fmt::Display, Infallible> {
490-
fn center(src: String, dst_len: usize) -> Result<String, Infallible> {
491-
let len = src.len();
492-
if dst_len <= len || dst_len >= MAX_LEN {
493-
Ok(src)
494-
} else {
495-
let diff = dst_len - len;
496-
let mid = diff / 2;
497-
let r = diff % 2;
498-
let mut buf = String::with_capacity(dst_len);
499-
500-
for _ in 0..mid {
501-
buf.push(' ');
502-
}
503-
504-
buf.push_str(&src);
489+
pub fn center(src: impl fmt::Display, width: usize) -> Result<impl fmt::Display, Infallible> {
490+
Ok(Center { src, width })
491+
}
505492

506-
for _ in 0..mid + r {
507-
buf.push(' ');
508-
}
493+
struct Center<T> {
494+
src: T,
495+
width: usize,
496+
}
509497

510-
Ok(buf)
498+
impl<T: fmt::Display> fmt::Display for Center<T> {
499+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
500+
if self.width < MAX_LEN {
501+
write!(f, "{: ^1$}", self.src, self.width)
502+
} else {
503+
write!(f, "{}", self.src)
511504
}
512505
}
513-
center(src.to_string(), dst_len)
514506
}
515507

516508
/// Count the words in that string.

0 commit comments

Comments
 (0)