Skip to content

Support Formatter::alternate (the # in format string) for another display variant #41

@nyurik

Description

@nyurik

Oxigraph (SPAQRL RDF engine) has two representations of every enum value, e.g. Function::Replace has to be formatted as either replace or REPLACE depending on the usecase. Currently, Oxigraph has a regular fmt::Display implementation with a giant match statement to format the upper case variant, and another function fn fmt_sse(&self, f: &mut impl fmt::Write) -- that looks identical to the Display, but is used by another code path.

I would like to propose parse-display to add support for multiple display variants. When present, parse-display can generate this type of code, which will be used by format!("{func}") vs format!("{func:#}")

// My code
#[derive(parse_display::Display)]
#[display(style = "UPPERCASE", alternate_style = "lowercase")]
enum Function {
  Replace,
  // ...
}

// Generated code
impl fmt::Display for Function {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    if f.alternate() {
      match self {
          Self::Replace => f.write_str("replace"),
          // ...
      }
    } else {
      match self {
          Self::Replace => f.write_str("REPLACE"),
          // ...
      }
    }
  }
}

CC: @Tpt

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions