Skip to main content

Crate deser_path

Crate deser_path 

Source
Expand description

This crate provides a PathLayer that tracks the path of the current value during serialization and deserialization in the State (see Path).

The layer can be added to both a DeserializeDriver and a SerializeDriver. Types can retrieve the current Path from the state and errors get the path of the value they refer to attached (see Error::attachment):

use deser_path::{Path, PathLayer, PathSegment};

#[derive(deser::Deserialize, Debug)]
struct Server {
    host: String,
    port: u16,
}

let json = r#"[{"host": "a", "port": "80"}]"#;
let err = deser_json::Deserializer::from_str(json)
    .deserialize_with::<Vec<Server>, _>(|driver| {
        driver.push_layer(PathLayer::new())
    })
    .unwrap_err();
let path = err.attachment::<Path>().unwrap();
assert_eq!(path.to_string(), "[0].port");
assert_eq!(path.segments()[0], PathSegment::Index(0));
assert_eq!(
    err.to_string(),
    "Unexpected: unexpected string, expected u16 at line 1 column 24 \
     (path: [0].port)"
);

During serialization, the path is available to the Serialize implementations:

use deser_path::{Path, PathLayer};
use deser::ser::{Serialize, SerializeDriver, Chunk};
use deser::State;
use deser::Error;

struct MyInt(u32);

impl Serialize for MyInt {
    fn serialize(&self, state: &mut State) -> Result<Chunk<'_>, Error> {
        // for as long as the `PathLayer` is added we can at any point
        // request the current path from the state.
        println!("{}", state.get::<Path>().unwrap());
        self.0.serialize(state)
    }
}

let serializable = vec![MyInt(42), MyInt(23)];
let mut driver = SerializeDriver::new(&serializable);
driver.push_layer(PathLayer::new());
driver.drive(|_event, _state| Ok(())).unwrap();

Structs§

Path
The current path of the serialization or deserialization.
PathLayer
A layer that tracks the current Path in the state.

Enums§

PathSegment
A single segment in the path.