umbra

Crates.ioumbra
lib.rsumbra
version0.1.0
sourcesrc
created_at2024-10-21 00:31:04.860564
updated_at2024-10-21 00:31:04.860564
descriptionA macro to generate optional structs
homepagehttps://github.com/lusingander/umbra
repositoryhttps://github.com/lusingander/umbra
max_upload_size
id1416753
size994
Kyosuke Fujimoto (lusingander)

documentation

https://docs.rs/umbra/

README

umbra

Crate Status

A macro to generate optional structs

Usage

Add the #[optional] and #[nested] attributes as follows:

use umbra::optional;

#[optional]
#[derive(Default)]
struct Foo {
  id: u32,
  name: String,
  #[nested]
  bar: Bar,
}

#[optional(derives = ["Debug"])]
#[derive(Default)]
struct Bar {
  name: String,
  value: Option<i32>,
}

The macro generates following structs:

#[derive(Default)]
struct Foo {
  id: u32,
  name: String,
  bar: Bar,
}

#[derive(Default)]
struct Bar {
  name: String,
  value: Option<i32>,
}

struct OptionalFoo {
  id: Option<u32>,
  name: Option<String>,
  bar: Option<OptionalBar>,
}

impl From<OptionalFoo> for Foo {
  fn from(optional: OptionalFoo) -> Self {
      let mut base = Self::default(); // create base values by default
      if let Some(value) = optional.id {
          base.id = value; // simple field
      }
      if let Some(value) = optional.bar {
          base.bar = value.into(); // nested field
      }
      // ...
      base
  }
}

#[derive(Debug)]
struct OptionalBar {
  name: Option<String>,
  value: Option<i32>,
}

impl From<OptionalBar> for Bar {
  fn from(optional: OptionalBar) -> Self {
      let mut base = Self::default();
      // ...
      base
  }
}

License

MIT

Commit count: 10

cargo fmt