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

无std serde-bool

单一值,真或假,布尔反序列化器

7个版本

0.1.3 2023年12月1日
0.1.2 2023年11月30日
0.0.3 2023年11月30日

508编码

Download history 584/week @ 2024-04-06 287/week @ 2024-04-13 440/week @ 2024-04-20 346/week @ 2024-04-27 241/week @ 2024-05-04 344/week @ 2024-05-11 209/week @ 2024-05-18 259/week @ 2024-05-25 418/week @ 2024-06-01 272/week @ 2024-06-08 200/week @ 2024-06-15 253/week @ 2024-06-22 338/week @ 2024-06-29 516/week @ 2024-07-06 612/week @ 2024-07-13 350/week @ 2024-07-20

每月下载量 1,844次

MIT/Apache

12KB
167

serde-bool

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

单一值,真或假,布尔反序列化器。

示例

支持 serde 无标签枚举,其中只有一个布尔值有效,允许跌落到下一个变体。避免了在功能禁用时只需将所有字段包装在 Option<_> 中的需求。

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

依赖项

~110–345KB