serde-bool

Crates.ioserde-bool
lib.rsserde-bool
version0.1.3
sourcesrc
created_at2023-11-30 17:00:57.983484
updated_at2023-12-01 12:30:05.806123
descriptionSingle value, true or false, boolean deserializers
homepage
repositoryhttps://github.com/x52dev/serde-bool
max_upload_size
id1054316
size35,203
Rob Ede (robjtede)

documentation

README

serde-bool

crates.io Documentation dependency status MIT or Apache 2.0 licensed
CI codecov Version Download

Single value, true or false, boolean deserializers.

Examples

Supporting serde untagged enums where only one boolean value is valid, allowing fallthrough to the next variant. Avoids need to wrap all fields in Option<_> just in case feature is disabled.

#[derive(Debug, serde::Deserialize)]
struct Config {
    feature: FeatureConfig,
}

#[derive(Debug, serde::Deserialize)]
#[serde(untagged)]
enum FeatureConfig {
    Disabled {
        enabled: serde_bool::False
    },

    Enabled {
        #[serde(default)]
        enabled: serde_bool::True,
        key: String,
        secret: String,
    }
}

// disabled variant is matched
let config = toml::from_str::<Config>(r#"
    [feature]
    enabled = false
"#).unwrap();
assert!(matches!(config.feature, FeatureConfig::Disabled { .. }));

// if the type used `enabled: bool`, this would cause issues and require Option<_> wrappers plus
// further validation... instead an error is returned immediately regarding the missing fields
let config = toml::from_str::<Config>(r#"
    [feature]
    enabled = true
"#).unwrap_err();

// using a `#[serde(default)]` annotation makes `enabled = true` optional here
let config = toml::from_str::<Config>(r#"
    [feature]
    key = "foo"
    secret = "bar"
"#).unwrap();
assert!(matches!(config.feature, FeatureConfig::Enabled { .. }));

// extra keys can exists in the disabled case, but as usual will not be captured
let config = toml::from_str::<Config>(r#"
    [feature]
    enabled = false
    key = "foo"
    secret = "bar"
"#).unwrap();
assert!(matches!(config.feature, FeatureConfig::Disabled { .. }));
Commit count: 23

cargo fmt