#deserialize #serde-derive #serde #utilities #serde-default #no-alloc

no-std serde-bool

Single value, true or false, boolean deserializers

7 releases

0.1.3 Dec 1, 2023
0.1.2 Nov 30, 2023
0.0.3 Nov 30, 2023

#1331 in Encoding

Download history 341/week @ 2024-06-30 530/week @ 2024-07-07 597/week @ 2024-07-14 348/week @ 2024-07-21 374/week @ 2024-07-28 446/week @ 2024-08-04 258/week @ 2024-08-11 367/week @ 2024-08-18 242/week @ 2024-08-25 258/week @ 2024-09-01 188/week @ 2024-09-08 285/week @ 2024-09-15 169/week @ 2024-09-22 295/week @ 2024-09-29 327/week @ 2024-10-06 350/week @ 2024-10-13

1,146 downloads per month

MIT/Apache

12KB
167 lines

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 { .. }));

Dependencies

~110–350KB