Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Find some way for serde to fail to deserialize inputs that break invariants #11

Open
vks opened this issue Jul 27, 2018 · 1 comment
Open

Comments

@vks
Copy link
Owner

vks commented Jul 27, 2018

Deserializing does not currently check for all invalid inputs. Also see #6 and #7.

@vks
Copy link
Owner Author

vks commented Apr 30, 2021

Here is some official advice for how this could be done:

use serde::{de, Deserialize, Deserializer};

#[derive(Deserialize, Debug)]
#[serde(remote = "Self")]
struct Invariant {
    /// len() >= 3
    s: String,
}

impl<'de> Deserialize<'de> for Invariant {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let unchecked = Invariant::deserialize(deserializer)?;
        if unchecked.s.len() < 3 {
            return Err(de::Error::custom("length of `s` must be >= 3"));
        }
        Ok(unchecked)
    }
}

fn main() {
    let j = r#" {"s": "abc"} "#;
    println!("{:?}", serde_json::from_str::<Invariant>(j).unwrap());
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant