Skip to content

Commit

Permalink
Phrase flag in terms of whether core::fmt machinery is required
Browse files Browse the repository at this point in the history
  • Loading branch information
dtolnay committed Feb 11, 2024
1 parent d43b759 commit f790bee
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 10 deletions.
12 changes: 6 additions & 6 deletions impl/src/attr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ pub struct Attrs<'a> {
#[derive(Clone)]
pub struct Display<'a> {
pub original: &'a Attribute,
pub use_write_str: bool,
pub fmt: LitStr,
pub args: TokenStream,
pub requires_fmt_machinery: bool,
pub has_bonus_display: bool,
pub implied_bounds: Set<(usize, Trait)>,
}
Expand Down Expand Up @@ -106,12 +106,12 @@ fn parse_error_attribute<'a>(attrs: &mut Attrs<'a>, attr: &'a Attribute) -> Resu

let fmt: LitStr = input.parse()?;
let args = parse_token_expr(input, false)?;
let requires_fmt_machinery = !args.is_empty();
let display = Display {
original: attr,
// This will be updated later if format_args are still required (i.e. has braces)
use_write_str: args.is_empty(),
fmt,
args,
requires_fmt_machinery,
has_bonus_display: false,
implied_bounds: Set::new(),
};
Expand Down Expand Up @@ -205,13 +205,13 @@ impl ToTokens for Display<'_> {
// Currently `write!(f, "text")` produces less efficient code than
// `f.write_str("text")`. We recognize the case when the format string
// has no braces and no interpolated values, and generate simpler code.
tokens.extend(if self.use_write_str {
tokens.extend(if self.requires_fmt_machinery {
quote! {
__formatter.write_str(#fmt)
::core::write!(__formatter, #fmt #args)
}
} else {
quote! {
::core::write!(__formatter, #fmt #args)
__formatter.write_str(#fmt)
}
});
}
Expand Down
6 changes: 2 additions & 4 deletions impl/src/fmt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,10 @@ impl Display<'_> {
}
}

if self.use_write_str && fmt.contains('}') {
self.use_write_str = false;
}
self.requires_fmt_machinery = self.requires_fmt_machinery || fmt.contains('}');

while let Some(brace) = read.find('{') {
self.use_write_str = false;
self.requires_fmt_machinery = true;
out += &read[..brace + 1];
read = &read[brace + 1..];
if read.starts_with('{') {
Expand Down

0 comments on commit f790bee

Please sign in to comment.