1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
//! This crate provides a wrapper type that observes the serialization to communicate
//! the current path of the serialization into the [`SerializerState`].
//!
//! ```rust
//! use deser_path::{Path, PathSerializable};
//! use deser::ser::{Serializable, SerializerState, Chunk};
//! use deser::Error;
//!
//! struct MyInt(u32);
//!
//! impl Serializable for MyInt {
//!     fn serialize(&self, state: &SerializerState) -> Result<Chunk, Error> {
//!         // for as long as we're wrapped with the `PathSerializable` we can at
//!         // any point request the current path from the state.
//!         let path = state.get::<Path>();
//!         println!("{:?}", path.segments());
//!         Ok(Chunk::U64(self.0 as u64))
//!     }
//! }
//!
//! let serializable = vec![MyInt(42), MyInt(23)];
//! let path_serializable = PathSerializable::wrap(&serializable);
//! // now serialize path_serializable instead
//! ```
use std::borrow::Cow;
use std::cell::RefCell;
use std::ptr::NonNull;
use std::rc::Rc;

use deser::ser::{Chunk, MapEmitter, SeqEmitter, Serializable, SerializerState, StructEmitter};
use deser::Error;

macro_rules! extend_lifetime {
    ($expr:expr, $t:ty) => {
        std::mem::transmute::<$t, $t>($expr)
    };
}

/// A single segment in the path.
#[derive(Debug, Clone)]
pub enum PathSegment {
    /// An unknown path segment.
    ///
    /// This can happen if the key was not a string or unsigned integer.
    Unknown,
    /// An unsigned index.
    Index(usize),
    /// A string key.
    Key(String),
}

/// The current path of the serialization.
///
/// This type is stored in the [`SerializerState`] and can be retrieved at any point.
/// By inspecting the [`segments`](Self::segments) a serializer can figure out where
/// it's invoked from.
#[derive(Debug, Default, Clone)]
pub struct Path {
    segments: Vec<PathSegment>,
}

impl Path {
    /// Returns the segments.
    pub fn segments(&self) -> &[PathSegment] {
        &self.segments
    }
}

/// Wraps a serializable so that it tracks the current path.
pub struct PathSerializable<'a> {
    serializable: &'a dyn Serializable,
}

impl<'a> PathSerializable<'a> {
    /// Wraps another serializable.
    pub fn wrap(serializable: &'a dyn Serializable) -> PathSerializable<'a> {
        PathSerializable { serializable }
    }
}

impl<'a> Serializable for PathSerializable<'a> {
    fn serialize(&self, state: &SerializerState) -> Result<Chunk, Error> {
        match self.serializable.serialize(state)? {
            Chunk::Struct(emitter) => Ok(Chunk::Struct(Box::new(PathStructEmitter {
                emitter,
                stashed_serializable: None,
            }))),
            Chunk::Map(emitter) => Ok(Chunk::Map(Box::new(PathMapEmitter {
                emitter,
                key_serializable: None,
                value_serializable: None,
                path_segment: Rc::default(),
            }))),
            Chunk::Seq(emitter) => Ok(Chunk::Seq(Box::new(PathSeqEmitter {
                emitter,
                stashed_serializable: None,
                index: 0,
            }))),
            other => Ok(other),
        }
    }

    fn done(&self, state: &SerializerState) -> Result<(), Error> {
        self.serializable.done(state)
    }
}

struct PathStructEmitter<'a> {
    emitter: Box<dyn StructEmitter + 'a>,
    stashed_serializable: Option<SegmentPushingSerializable>,
}

impl<'a> StructEmitter for PathStructEmitter<'a> {
    fn next(&mut self) -> Option<(Cow<'_, str>, &dyn Serializable)> {
        let (key, value) = self.emitter.next()?;
        let new_segment = PathSegment::Key(key.to_string());
        unsafe {
            self.stashed_serializable = Some(SegmentPushingSerializable {
                real: NonNull::from(extend_lifetime!(value, &dyn Serializable)),
                segment: RefCell::new(Some(new_segment)),
            });
        }
        Some((key, self.stashed_serializable.as_ref().unwrap()))
    }
}

struct PathMapEmitter<'a> {
    emitter: Box<dyn MapEmitter + 'a>,
    key_serializable: Option<SegmentCollectingSerializable>,
    value_serializable: Option<SegmentPushingSerializable>,
    path_segment: Rc<RefCell<Option<PathSegment>>>,
}

impl<'a> MapEmitter for PathMapEmitter<'a> {
    fn next_key(&mut self) -> Option<&dyn Serializable> {
        unsafe {
            self.key_serializable = Some(SegmentCollectingSerializable {
                real: NonNull::from(extend_lifetime!(
                    self.emitter.next_key()?,
                    &dyn Serializable
                )),
                segment: self.path_segment.clone(),
            });
        }
        Some(self.key_serializable.as_ref().unwrap())
    }

    fn next_value(&mut self) -> &dyn Serializable {
        let new_segment = self
            .path_segment
            .borrow_mut()
            .take()
            .unwrap_or(PathSegment::Unknown);
        unsafe {
            self.value_serializable = Some(SegmentPushingSerializable {
                real: NonNull::from(extend_lifetime!(
                    self.emitter.next_value(),
                    &dyn Serializable
                )),
                segment: RefCell::new(Some(new_segment)),
            });
        }
        self.value_serializable.as_ref().unwrap()
    }
}

struct PathSeqEmitter<'a> {
    emitter: Box<dyn SeqEmitter + 'a>,
    stashed_serializable: Option<SegmentPushingSerializable>,
    index: usize,
}

impl<'a> SeqEmitter for PathSeqEmitter<'a> {
    fn next(&mut self) -> Option<&dyn Serializable> {
        let index = self.index;
        self.index += 1;
        let value = self.emitter.next()?;
        let new_segment = PathSegment::Index(index);
        unsafe {
            self.stashed_serializable = Some(SegmentPushingSerializable {
                real: NonNull::from(extend_lifetime!(value, &dyn Serializable)),
                segment: RefCell::new(Some(new_segment)),
            });
        }
        Some(self.stashed_serializable.as_mut().unwrap())
    }
}

struct SegmentPushingSerializable {
    real: NonNull<dyn Serializable>,
    segment: RefCell<Option<PathSegment>>,
}

impl Serializable for SegmentPushingSerializable {
    fn serialize(&self, state: &SerializerState) -> Result<Chunk, Error> {
        {
            let mut path = state.get_mut::<Path>();
            path.segments.push(self.segment.take().unwrap());
        }
        match unsafe { self.real.as_ref().serialize(state)? } {
            Chunk::Struct(emitter) => Ok(Chunk::Struct(Box::new(PathStructEmitter {
                emitter,
                stashed_serializable: None,
            }))),
            Chunk::Map(emitter) => Ok(Chunk::Map(Box::new(PathMapEmitter {
                emitter,
                key_serializable: None,
                value_serializable: None,
                path_segment: Rc::default(),
            }))),
            Chunk::Seq(emitter) => Ok(Chunk::Seq(Box::new(PathSeqEmitter {
                emitter,
                stashed_serializable: None,
                index: 0,
            }))),
            other => Ok(other),
        }
    }

    fn done(&self, state: &SerializerState) -> Result<(), Error> {
        unsafe { self.real.as_ref().done(state)? };
        let mut path = state.get_mut::<Path>();
        path.segments.pop();
        Ok(())
    }
}

struct SegmentCollectingSerializable {
    real: NonNull<dyn Serializable>,
    segment: Rc<RefCell<Option<PathSegment>>>,
}

impl Serializable for SegmentCollectingSerializable {
    fn serialize(&self, state: &SerializerState) -> Result<Chunk, Error> {
        match unsafe { self.real.as_ref().serialize(state) }? {
            Chunk::Str(key) => {
                *self.segment.borrow_mut() = Some(PathSegment::Key(key.to_string()));
                Ok(Chunk::Str(key))
            }
            Chunk::U64(val) => {
                *self.segment.borrow_mut() = Some(PathSegment::Index(val as usize));
                Ok(Chunk::U64(val))
            }
            other => Ok(other),
        }
    }

    fn done(&self, state: &SerializerState) -> Result<(), Error> {
        unsafe { self.real.as_ref().done(state) }
    }
}