deser_path/lib.rs
1//! This crate provides a wrapper type that observes the serialization to communicate
2//! the current path of the serialization into the [`SerializerState`](deser::ser::SerializerState)
3//! and [`DeserializerState`](deser::de::DeserializerState).
4//!
5//! ```rust
6//! use deser_path::{Path, PathSerializable};
7//! use deser::ser::{Serialize, SerializerState, Chunk};
8//! use deser::{Atom, Error};
9//!
10//! struct MyInt(u32);
11//!
12//! impl Serialize for MyInt {
13//! fn serialize(&self, state: &SerializerState) -> Result<Chunk, Error> {
14//! // for as long as we're wrapped with the `PathSerializable` we can at
15//! // any point request the current path from the state.
16//! let path = state.get::<Path>();
17//! println!("{:?}", path.segments());
18//! self.0.serialize(state)
19//! }
20//! }
21//!
22//! let serializable = vec![MyInt(42), MyInt(23)];
23//! let path_serializable = PathSerializable::wrap(&serializable);
24//! // now serialize path_serializable instead
25//! ```
26mod de;
27mod ser;
28
29pub use de::*;
30pub use ser::*;
31
32/// A single segment in the path.
33#[derive(Debug, Clone)]
34pub enum PathSegment {
35 /// An unknown path segment.
36 ///
37 /// This can happen if the key was not a string or unsigned integer.
38 Unknown,
39 /// An unsigned index.
40 Index(usize),
41 /// A string key.
42 Key(String),
43}
44
45/// The current path of the serialization.
46///
47/// This type is stored in the state and can be retrieved at any point. By
48/// inspecting the [`segments`](Self::segments) a serializer can figure out
49/// where it's invoked from.
50#[derive(Debug, Default, Clone)]
51pub struct Path {
52 pub(crate) segments: Vec<PathSegment>,
53}
54
55impl Path {
56 /// Returns the segments.
57 pub fn segments(&self) -> &[PathSegment] {
58 &self.segments
59 }
60}