Crate delegate_display

source ·
Expand description

Lets you derive Display & Debug traits on structs with 0..1 fields & enums where each variant has 0..1 fields - see input/output examples below.

Newtype structs


// Input
#[derive(delegate_display::DelegateDisplay)]
struct Foo(SomeType);

// Output
impl fmt::Display for Foo {
  #[inline]
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    fmt::Display::fmt(&self.0, f)
  }
}

Structs with one field


// Input
#[derive(delegate_display::DelegateDebug)]
struct Foo { some_field: SomeType }

// Output
impl fmt::Debug for Foo {
  #[inline]
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    fmt::Debug::fmt(&self.some_field, f)
  }
}

Enums


// Input
enum MyEnum {
  Foo,
  Bar(SomeType),
  Qux { baz: SomeType }
}

// Output
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  match self {
    Self::Foo => f.write_str("Foo"),
    Self::Bar(inner) => DebugOrDisplay::fmt(inner, f),
    Self::Qux { baz } => DebugOrDisplay::fmt(baz, f),
  }
}

Empty structs & enums


// Input
struct Foo;
struct Bar{}
struct Qux();
enum Baz {}

// Output
fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result {
  Ok(())
}

Invalid inputs


struct TooManyFields1 {
  foo: SomeType,
  bar: SomeType, // Only one field permitted
}

struct TooManyFields2(SomeType, SomeType);

enum SomeEnum {
  A, // this is ok
  B(SomeType), // this is ok
  C { foo: SomeType }, // this is ok
  D(SomeType, SomeType), // Only one field permitted
  E { foo: SomeType, bar: SomeType } // Only one field permitted
}

Derive Macros