expression

Separate parsing from domain validation

Parse the wire shape, then enforce application invariants before constructing a domain type. A u16 quantity prevents negatives but still permits zero. Serde and serde_json are external crates; use the staged Cargo manifest. Expected stdout (not executed): ok 4 invalid invalid Common mistake: Assuming valid JSON proves that the requested operation is allowed.

Formal Syntax & Structure

rust syntaxrust
Deserialize wire type; validate using TryFrom

Working Example

Example Snippetrust
fn main() {    #[derive(serde::Deserialize)]    struct Wire { quantity: u16 }    struct Order(u16);    impl TryFrom<Wire> for Order {        type Error = &'static str;        fn try_from(w: Wire) -> Result<Self, Self::Error> {            if (1..=100).contains(&w.quantity) { Ok(Order(w.quantity)) } else { Err("quantity out of range") }        }    }    for input in [r#"{"quantity":4}"#, r#"{"quantity":0}"#, r#"{"quantity":101}"#] {        let w: Wire = serde_json::from_str(input).unwrap();        match Order::try_from(w) { Ok(o) => println!("ok {}", o.0), Err(_) => println!("invalid") }    }}
Rust Reference