#serde #const #untagged #serde-json #no-alloc

no-std serde-constant

Const values for serde

1 unstable release

0.1.0 Oct 29, 2023

#1654 in Encoding

Download history 19/week @ 2024-09-25 19/week @ 2024-10-02 16/week @ 2024-10-09 12/week @ 2024-10-16 9/week @ 2024-10-23 4/week @ 2024-10-30 8/week @ 2024-11-06 30/week @ 2024-11-13 11/week @ 2024-11-20 7/week @ 2024-11-27 186/week @ 2024-12-04 112/week @ 2024-12-11 62/week @ 2024-12-18 2/week @ 2024-12-25 5/week @ 2025-01-08

92 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

~100–330KB