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(),
"InvalidType: 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, Emit};
use deser::State;
use deser::Error;
struct MyInt(u32);
impl Serialize for MyInt {
fn serialize<'a>(value: &'a Self, state: &mut State) -> Result<Emit<'a>, 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());
u32::serialize(&value.0, 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.
- Path
Layer - A layer that tracks the current
Pathin the state.
Enums§
- Path
Segment - A single segment in the path.