1 unstable release

0.1.0 Oct 29, 2023

#1664 in Encoding

Download history 78/week @ 2025-02-09 93/week @ 2025-02-16 87/week @ 2025-02-23 100/week @ 2025-03-02 131/week @ 2025-03-09 139/week @ 2025-03-16 85/week @ 2025-03-23 86/week @ 2025-03-30 149/week @ 2025-04-06 213/week @ 2025-04-13 265/week @ 2025-04-20 171/week @ 2025-04-27 213/week @ 2025-05-04 170/week @ 2025-05-11 113/week @ 2025-05-18 89/week @ 2025-05-25

594 downloads per month

MIT/Apache

16KB
301 lines

serde-constant

This crate provides a type that can represent a single-const serde value. For example, asserting that a particular bool is always true. You can use this for disambiguation in serde(untagged) structures, or just for validation.

Examples

use serde_constant::ConstBool;
#[derive(Deserialize)]
struct Foo {
    bar: String,
    baz: ConstBool<true>,
}
assert!(serde_json::from_value::<Foo>(json!({ "bar": "quux", "baz": true })).is_ok());
assert!(serde_json::from_value::<Foo>(json!({ "bar": "quux", "baz": false })).is_err());
use serde_constant::ConstI64;
// int tags? No problem!
#[derive(Deserialize)]
#[serde(untagged)]
enum Foo {
    Bar {
        tag: ConstI64<1>,
    },
    Baz {
        tag: ConstI64<2>,
        x: Option<String>,
    },
}
assert!(matches!(
    serde_json::from_value(json!({ "tag": 2, "x": null }))?,
    // would have been Bar if `tag` were just `i64`
    Foo::Baz { x: None, .. },
));

Dependencies

~95–315KB