Skip to main content

serialization/
serialization.rs

1//! Zero-allocation JSON (de)serialization via the [`Action`] trait.
2//!
3//! Run with: `cargo run --example serialization -p ocpp-types --features serde`
4
5use ocpp_types::v16::{AuthorizeRequest, IdTag};
6use ocpp_types::Action;
7
8fn main() {
9    let request = AuthorizeRequest {
10        id_tag: IdTag::try_from("ABC123").expect("fits in 20 chars"),
11    };
12
13    // The caller owns the buffer -- nothing here allocates.
14    let mut buf = [0u8; 256];
15    let json: &str = request.to_json_str(&mut buf).expect("buffer is big enough");
16    println!("serialized: {json}");
17
18    let parsed = AuthorizeRequest::from_json_str(json).expect("valid JSON");
19    assert_eq!(parsed, request);
20    println!("round-tripped successfully: {parsed:?}");
21
22    // `to_json_slice`/`from_json_slice` are the same, but for raw bytes
23    // instead of `&str`.
24    let mut byte_buf = [0u8; 256];
25    let bytes: &[u8] = request.to_json_slice(&mut byte_buf).unwrap();
26    println!("as bytes: {bytes:?}");
27}