#serde #serialization

no-std monostate

Type that deserializes only from one specific value

6 releases

new 0.1.5 Mar 18, 2023
0.1.4 Mar 5, 2023
0.1.2 Dec 17, 2022
0.1.1 Aug 2, 2022
0.1.0 Jan 25, 2022

#30 in #serde-serialization

Download history 699/week @ 2022-11-29 685/week @ 2022-12-06 601/week @ 2022-12-13 553/week @ 2022-12-20 381/week @ 2022-12-27 852/week @ 2023-01-03 548/week @ 2023-01-10 772/week @ 2023-01-17 1159/week @ 2023-01-24 829/week @ 2023-01-31 741/week @ 2023-02-07 984/week @ 2023-02-14 1246/week @ 2023-02-21 1014/week @ 2023-02-28 930/week @ 2023-03-07 764/week @ 2023-03-14

4,074 downloads per month
Used in 6 crates (4 directly)

MIT/Apache

51KB
1.5K SLoC

Monostate

github crates.io docs.rs build status

This library implements a type macro for a zero-sized type that is Serde deserializable only from one specific value.

[dependencies]
monostate = "0.1"

Examples

use monostate::MustBe;
use serde::Deserialize;

#[derive(Deserialize)]
struct Example {
    kind: MustBe!("success"),
    code: MustBe!(200),
}

The above struct would deserialize from {"kind":"success", "code":200} in JSON, but would fail the deserialization if "kind" or "code" were any other value.

This can sometimes be helpful in processing untagged enums in which the variant indentification is more convoluted than what is handled by Serde's externally tagged and internally tagged representations, for example because the variant tag has an inconsistent type or key.

use monostate::MustBe;
use serde::Deserialize;

#[derive(Deserialize)]
#[serde(untagged)]
pub enum ApiResponse {
    Success {
        success: MustBe!(true),
    },
    Error {
        kind: MustBe!("error"),
        message: String,
    },
}

License

Licensed under either of Apache License, Version 2.0 or MIT license at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Dependencies

~0.8–1.3MB
~31K SLoC