#serde #serialization #json-key #no-alloc

no-std monostate

Type that deserializes only from one specific value

13 releases

0.1.12 Apr 15, 2024
0.1.11 Jan 2, 2024
0.1.10 Nov 14, 2023
0.1.9 Jul 21, 2023
0.1.0 Jan 25, 2022

#1263 in Encoding

Download history 14051/week @ 2024-01-02 18700/week @ 2024-01-09 24938/week @ 2024-01-16 22913/week @ 2024-01-23 23514/week @ 2024-01-30 24635/week @ 2024-02-06 27962/week @ 2024-02-13 27840/week @ 2024-02-20 36991/week @ 2024-02-27 29831/week @ 2024-03-05 32244/week @ 2024-03-12 32213/week @ 2024-03-19 30996/week @ 2024-03-26 32350/week @ 2024-04-02 33632/week @ 2024-04-09 30043/week @ 2024-04-16

132,298 downloads per month
Used in 76 crates (11 directly)

MIT/Apache

52KB
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 identification 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.4–1MB
~23K SLoC