fmt::Formatter::pad: don't call chars().count() more than one time

This commit is contained in:
klensy 2021-09-01 15:35:58 +03:00
parent 608b5e1c20
commit 6c9e708f4b

View file

@ -1421,19 +1421,24 @@ impl<'a> Formatter<'a> {
// If we're under the maximum length, and there's no minimum length // If we're under the maximum length, and there's no minimum length
// requirements, then we can just emit the string // requirements, then we can just emit the string
None => self.buf.write_str(s), None => self.buf.write_str(s),
Some(width) => {
let chars_count = s.chars().count();
// If we're under the maximum width, check if we're over the minimum // If we're under the maximum width, check if we're over the minimum
// width, if so it's as easy as just emitting the string. // width, if so it's as easy as just emitting the string.
Some(width) if s.chars().count() >= width => self.buf.write_str(s), if chars_count >= width {
self.buf.write_str(s)
}
// If we're under both the maximum and the minimum width, then fill // If we're under both the maximum and the minimum width, then fill
// up the minimum width with the specified string + some alignment. // up the minimum width with the specified string + some alignment.
Some(width) => { else {
let align = rt::v1::Alignment::Left; let align = rt::v1::Alignment::Left;
let post_padding = self.padding(width - s.chars().count(), align)?; let post_padding = self.padding(width - chars_count, align)?;
self.buf.write_str(s)?; self.buf.write_str(s)?;
post_padding.write(self.buf) post_padding.write(self.buf)
} }
} }
} }
}
/// Write the pre-padding and return the unwritten post-padding. Callers are /// Write the pre-padding and return the unwritten post-padding. Callers are
/// responsible for ensuring post-padding is written after the thing that is /// responsible for ensuring post-padding is written after the thing that is