serde_enabled

Crates.ioserde_enabled
lib.rsserde_enabled
version0.1.0
sourcesrc
created_at2024-01-17 21:40:10.530457
updated_at2024-01-17 21:40:10.530457
descriptionA small wrapper for enabling/disabling sections in configuartion files easier with Serde.
homepagehttps://github.com/felipesere/erde_enabled
repositoryhttps://github.com/felipesere/erde_enabled
max_upload_size
id1103426
size10,789
Felipe Seré (felipesere)

documentation

README

Enable<T> is a wrapper that adds one extra field enabled when the T is serialized with Serde. That field can be true, in which case all of the fields for T need to be present, or it can be false at which point all fields of T can be ommited.

The use case is for configuration YAMLs where sections can be toggled on or off.

use serde::{Deserialize, Serialize};
use serde_enabled::Enable;

#[derive(Deserialize, Serialize, Debug, PartialEq, Eq)]
struct Outside {
    inside: Enable<Inside>,
}

#[derive(Deserialize, Serialize, Debug, PartialEq, Eq)]
struct Inside {
    thing: u32,
    other: String,
}

let raw = indoc::indoc! {r#"
    inside:
        enable: false
        thing: 1
        other: "Great"
    "#};

let o: Outside = serde_yaml::from_str(raw).unwrap();

 assert!(!o.inside.is_enabled());

 let raw = indoc::indoc! {r#"
     inside:
         enable: true
         thing: 1
         other: "Great"
     "#};

 let o: Outside = serde_yaml::from_str(raw).unwrap();

  assert!(o.inside.is_enabled());
  assert_eq!(
        o,
        Outside {
           inside: Enable::On(Inside {
            thing: 1,
            other: "Great".into()
        })
        }
    );
Commit count: 0

cargo fmt