From f790bee2a401d71ac6e5492c7d1f8bb3a18a0e1c Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Sun, 11 Feb 2024 10:27:02 -0800 Subject: [PATCH] Phrase flag in terms of whether core::fmt machinery is required --- impl/src/attr.rs | 12 ++++++------ impl/src/fmt.rs | 6 ++---- 2 files changed, 8 insertions(+), 10 deletions(-) diff --git a/impl/src/attr.rs b/impl/src/attr.rs index a54a3b1..0e30d29 100644 --- a/impl/src/attr.rs +++ b/impl/src/attr.rs @@ -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)>, } @@ -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(), }; @@ -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) } }); } diff --git a/impl/src/fmt.rs b/impl/src/fmt.rs index a5b44ce..b38b7bf 100644 --- a/impl/src/fmt.rs +++ b/impl/src/fmt.rs @@ -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('{') {