validate/validate.rs
1//! Checking a payload against the spec limits the types can't carry.
2//!
3//! Run with: `cargo run --example validate -p ocpp-types --features validate`
4
5use ocpp_types::v201::AuthorizeRequest;
6use ocpp_types::v201::common::{IdToken, IdTokenEnum};
7use ocpp_types::validate::{ConstraintClass, Validate};
8
9fn main() {
10 let mut request: AuthorizeRequest = AuthorizeRequest {
11 certificate: None,
12 custom_data: None,
13 id_token: IdToken {
14 additional_info: None,
15 custom_data: None,
16 // Bounded at `maxLength: 36` by the schema, so this is a
17 // `heapless::String<36>` and an over-long value can't be built
18 // in the first place -- nothing for `validate` to check.
19 id_token: heapless::String::try_from("ABC123").unwrap(),
20 r#type: IdTokenEnum::ISO14443,
21 },
22 iso15118_certificate_hash_data: None,
23 };
24
25 println!("conformant: {:?}", request.validate());
26
27 // `certificate` is `maxLength: 5500` in the schema, but 5500 is too
28 // large to inline as a `heapless::String`, so with `alloc` it is a
29 // plain growable `String`. The type accepts this; the spec does not.
30 request.certificate = Some("-".repeat(6000));
31
32 match request.validate() {
33 Ok(()) => println!("no violations"),
34 Err(error) => {
35 println!("rejected: {error}");
36 println!(" kind: {:?}", error.kind());
37 println!(" path: {:?}", error.path());
38
39 // Which `CALLERROR` a CSMS answers with. The code's spelling is
40 // version-specific (1.6J dropped an `r` from "occurrence"), so
41 // the classification is what's shared.
42 let code = match error.kind().constraint_class() {
43 ConstraintClass::Property => "PropertyConstraintViolation",
44 ConstraintClass::Occurrence => "OccurrenceConstraintViolation",
45 };
46 println!(" answer: {code}");
47 }
48 }
49
50 // `minItems: 1` is the other half: no collection type can say "at least
51 // one", so an empty required array is only caught here.
52 request.certificate = None;
53 request.iso15118_certificate_hash_data = Some(heapless::Vec::new());
54
55 if let Err(error) = request.validate() {
56 println!("rejected: {error}");
57 }
58}