Skip to content

Commit 6c9e708

Browse files
committed
fmt::Formatter::pad: don't call chars().count() more than one time
1 parent 608b5e1 commit 6c9e708

File tree

1 file changed

+14
-9
lines changed

1 file changed

+14
-9
lines changed

library/core/src/fmt/mod.rs

+14-9
Original file line numberDiff line numberDiff line change
@@ -1421,16 +1421,21 @@ impl<'a> Formatter<'a> {
14211421
// If we're under the maximum length, and there's no minimum length
14221422
// requirements, then we can just emit the string
14231423
None => self.buf.write_str(s),
1424-
// If we're under the maximum width, check if we're over the minimum
1425-
// width, if so it's as easy as just emitting the string.
1426-
Some(width) if s.chars().count() >= width => self.buf.write_str(s),
1427-
// If we're under both the maximum and the minimum width, then fill
1428-
// up the minimum width with the specified string + some alignment.
14291424
Some(width) => {
1430-
let align = rt::v1::Alignment::Left;
1431-
let post_padding = self.padding(width - s.chars().count(), align)?;
1432-
self.buf.write_str(s)?;
1433-
post_padding.write(self.buf)
1425+
let chars_count = s.chars().count();
1426+
// If we're under the maximum width, check if we're over the minimum
1427+
// width, if so it's as easy as just emitting the string.
1428+
if chars_count >= width {
1429+
self.buf.write_str(s)
1430+
}
1431+
// If we're under both the maximum and the minimum width, then fill
1432+
// up the minimum width with the specified string + some alignment.
1433+
else {
1434+
let align = rt::v1::Alignment::Left;
1435+
let post_padding = self.padding(width - chars_count, align)?;
1436+
self.buf.write_str(s)?;
1437+
post_padding.write(self.buf)
1438+
}
14341439
}
14351440
}
14361441
}

0 commit comments

Comments
 (0)