Rollup merge of #88560 - klensy:formatter-pad-shrink, r=m-ou-se

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

First commit merges two branches of match to call chars().count() only once: that should be faster if this method hits place of 3rd (previous) branch, plus quarter shorter.
Second commit fixes some clippy lints while i'm here (should it be separate PR?).
This commit is contained in:
Mara Bos 2021-09-02 19:10:18 +02:00 committed by GitHub
commit 0d105c0e77
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -402,7 +402,7 @@ impl<'a> Arguments<'a> {
if self.args.is_empty() {
pieces_length
} else if self.pieces[0] == "" && pieces_length < 16 {
} else if !self.pieces.is_empty() && self.pieces[0].is_empty() && pieces_length < 16 {
// If the format string starts with an argument,
// don't preallocate anything, unless length
// of pieces is significant.
@ -1163,7 +1163,7 @@ pub fn write(output: &mut dyn Write, args: Arguments<'_>) -> Result {
}
// SAFETY: arg and args.args come from the same Arguments,
// which guarantees the indexes are always within bounds.
unsafe { run(&mut formatter, arg, &args.args) }?;
unsafe { run(&mut formatter, arg, args.args) }?;
idx += 1;
}
}
@ -1409,7 +1409,7 @@ impl<'a> Formatter<'a> {
// we know that it can't panic. Use `get` + `unwrap_or` to avoid
// `unsafe` and otherwise don't emit any panic-related code
// here.
s.get(..i).unwrap_or(&s)
s.get(..i).unwrap_or(s)
} else {
&s
}
@ -1421,19 +1421,24 @@ impl<'a> Formatter<'a> {
// If we're under the maximum length, and there's no minimum length
// requirements, then we can just emit the string
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
// 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
// up the minimum width with the specified string + some alignment.
Some(width) => {
else {
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)?;
post_padding.write(self.buf)
}
}
}
}
/// Write the pre-padding and return the unwritten post-padding. Callers are
/// responsible for ensuring post-padding is written after the thing that is