deser-value 0.10.0

A dynamic value type for deser
Documentation
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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
use std::sync::Arc;

use deser_core::Text;
use deser_core::de::{self, Deserialize, DeserializeDriver};
use deser_core::ser::{self, Serialize, SerializeDriver};
use deser_core::{Atom, ContainerShape, Error, ErrorKind, Event, Source};

use crate::value::{Kind, Value};

/// Deserializes types from a [`Value`].
///
/// This is a [`Deserializer`](deser_core::de::Deserializer) which emits the
/// events of a value.  It's what
/// [`from_value`] uses, use it directly to configure the deserialization,
/// for instance to add layers:
///
/// ```
/// use std::collections::BTreeMap;
/// use deser_path::{Path, PathLayer};
/// use deser_value::{value, Deserializer};
///
/// let value = value!({"items": [1, "two"]});
/// let err = Deserializer::new(&value)
///     .deserialize_with::<BTreeMap<String, Vec<u32>>, _>(|driver| {
///         driver.push_layer(PathLayer::new());
///     })
///     .unwrap_err();
/// assert_eq!(err.attachment::<Path>().unwrap().to_string(), "items[1]");
/// ```
///
/// Strings and bytes are passed on borrowed from the value, which means
/// that types like `&str` can be deserialized.  The [meta data](crate::Meta)
/// of the values is restored for every event: event data is attached and if
/// the value has spans, the input ranges and the source are published.
/// This means that errors refer to the location in the input the value was
/// deserialized from.
pub struct Deserializer<'a> {
    value: &'a Value,
    // the context the values are deserialized in
    context: deser_core::Context,
}

impl<'a> Deserializer<'a> {
    /// Creates a deserializer for a value.
    pub fn new(value: &'a Value) -> Deserializer<'a> {
        Deserializer {
            value,
            context: deser_core::Context::new(),
        }
    }

    /// Deserializes the value.
    pub fn deserialize<T: Deserialize<'a>>(&mut self) -> Result<T, Error> {
        de::Deserializer::deserialize(self)
    }

    /// Deserializes the value with a configured driver.
    ///
    /// The callback is invoked with the driver before the value is
    /// deserialized, for instance to add [`Layer`](deser_core::de::Layer)s.
    pub fn deserialize_with<T, F>(&mut self, setup: F) -> Result<T, Error>
    where
        T: Deserialize<'a>,
        F: FnOnce(&mut DeserializeDriver<'_, 'a>),
    {
        de::Deserializer::deserialize_with(self, setup)
    }

    /// Sets the context the values are deserialized in.
    ///
    /// The values of the context are the defaults of the extension values
    /// of the state (see [`Context`](deser_core::Context)).  A context set
    /// on the driver (for instance in the setup callback of `deserialize_with`)
    /// takes precedence.
    pub fn set_context(&mut self, context: deser_core::Context) {
        self.context = context;
    }

    /// Returns the context the values are deserialized in.
    pub fn context(&self) -> &deser_core::Context {
        &self.context
    }
}

impl<'de> de::Deserializer<'de> for Deserializer<'de> {
    fn drive(&mut self, driver: &mut DeserializeDriver<'_, 'de>) -> Result<(), Error> {
        if !self.context.is_empty() {
            driver.set_default_context(self.context.clone());
        }
        let mut source = None;
        drive(self.value, driver, &mut source).map_err(|mut err| {
            if let Some(source) = source {
                err.resolve_position(source.as_bytes());
            }
            err
        })
    }
}

/// A map or sequence whose values are emitted.
enum Frame<'a> {
    Seq(std::slice::Iter<'a, Value>, &'a Value),
    Map(MapFrame<'a>, &'a Value),
}

/// A map whose entries are emitted.
struct MapFrame<'a> {
    iter: indexmap::map::Iter<'a, Value, Value>,
    // the value of the key that was emitted
    pending: Option<&'a Value>,
    // the key and the remaining values of a repeated key of a multimap
    repeated: Option<(&'a Value, std::slice::Iter<'a, Value>)>,
    multimap: bool,
}

impl<'a> MapFrame<'a> {
    /// Returns the next key or value.
    fn next(&mut self) -> Option<&'a Value> {
        if let Some(value) = self.pending.take() {
            return Some(value);
        }
        if let Some((key, ref mut values)) = self.repeated {
            if let Some(value) = values.next() {
                self.pending = Some(value);
                return Some(key);
            }
            self.repeated = None;
        }
        let (key, value) = self.iter.next()?;
        // the values of a repeated key are the values of the key given
        // more than once
        if self.multimap
            && let Some(seq) = value.as_seq()
            && seq.is_repeated()
            && !seq.is_empty()
        {
            let mut values = seq.iter();
            self.pending = values.next();
            self.repeated = Some((key, values));
        } else {
            self.pending = Some(value);
        }
        Some(key)
    }
}

/// Publishes the input range and the source of an event.
fn set_range<'de>(
    driver: &mut DeserializeDriver<'_, 'de>,
    current: &mut Option<&'de Arc<str>>,
    new: &'de Arc<str>,
    (start, end): (usize, usize),
) {
    if !current.is_some_and(|current| Arc::ptr_eq(current, new)) {
        Source(new.clone()).set(driver.state_mut());
        *current = Some(new);
    }
    driver.state_mut().set_input_range(start, end);
}

fn drive<'de>(
    root: &'de Value,
    driver: &mut DeserializeDriver<'_, 'de>,
    source: &mut Option<&'de Arc<str>>,
) -> Result<(), Error> {
    let mut stack: Vec<Frame<'de>> = Vec::new();
    let mut next = Some(root);
    loop {
        if let Some(value) = next.take() {
            if let Some(ref meta) = value.meta {
                if !meta.event_data().is_empty() {
                    driver.state_mut().attach_event_data(meta.event_data());
                }
                if let Some(span) = meta.span() {
                    set_range(driver, source, span.source(), span.start_range());
                }
            }
            match value.kind {
                Kind::Seq(ref seq) => {
                    let mut seq_shape = shape(seq.len(), seq.order());
                    seq_shape.set_ambiguous_empty(seq.is_ambiguous_empty());
                    driver.emit(Event::SeqStart(seq_shape))?;
                    stack.push(Frame::Seq(seq.iter(), value));
                }
                Kind::Map(ref map) => {
                    let mut map_shape = shape(map.len(), map.order());
                    map_shape.set_ambiguous_empty(map.is_ambiguous_empty());
                    if map.is_multimap() {
                        // the entries include the values of repeated keys
                        map_shape = {
                            let mut shape = ContainerShape::with_order(map.order());
                            shape.set_multimap(true);
                            shape
                        };
                    }
                    driver.emit(Event::MapStart(map_shape))?;
                    stack.push(Frame::Map(
                        MapFrame {
                            iter: map.inner.entries.iter(),
                            pending: None,
                            repeated: None,
                            multimap: map.is_multimap(),
                        },
                        value,
                    ));
                }
                ref leaf => driver.emit_borrowed(leaf_atom(leaf))?,
            }
        }

        let Some(frame) = stack.last_mut() else {
            return Ok(());
        };
        next = match frame {
            Frame::Seq(iter, _) => iter.next(),
            Frame::Map(map, _) => map.next(),
        };
        if next.is_none() {
            let (container, event) = match stack.pop() {
                Some(Frame::Seq(_, container)) => (container, Event::SeqEnd),
                Some(Frame::Map(_, container)) => (container, Event::MapEnd),
                None => unreachable!(),
            };
            if let Some(span) = container.span()
                && let Some(range) = span.end_range()
            {
                set_range(driver, source, span.source(), range);
            }
            driver.emit(event)?;
        }
    }
}

fn shape(len: usize, order: deser_core::Order) -> ContainerShape {
    {
        let mut shape = ContainerShape::with_len(len);
        shape.set_order(order);
        shape
    }
}

/// Returns the atom of a value without children.
fn leaf_atom(kind: &Kind) -> Atom<'_> {
    match kind {
        Kind::Null => Atom::Null,
        Kind::Bool(value) => Atom::Bool(*value),
        Kind::U64(value) => Atom::U64(*value),
        Kind::I64(value) => Atom::I64(*value),
        Kind::F32(value) => Atom::F32(*value),
        Kind::F64(value) => Atom::F64(*value),
        Kind::Char(value) => Atom::Char(*value),
        Kind::Str(value) => Atom::Str(Text::borrowed(value)),
        Kind::Lexical(value) => Atom::Lexical(Text::borrowed(value)),
        Kind::Bytes(value) => Atom::Bytes(value.as_borrowed()),
        Kind::Ext(value) => Atom::Ext(value.as_borrowed()),
        Kind::Implicit(value) => Atom::Implicit(value.as_borrowed()),
        Kind::Seq(_) | Kind::Map(_) => unreachable!("containers are not atoms"),
    }
}

/// Deserializes a type from a value.
///
/// Types can borrow strings and bytes from the value.
///
/// ```
/// use deser::Deserialize;
/// use deser_value::{from_value, value};
///
/// #[derive(Debug, Deserialize)]
/// struct User<'a> {
///     name: &'a str,
///     id: u64,
/// }
///
/// let value = value!({"name": "Jane", "id": 42});
/// let user: User = from_value(&value).unwrap();
/// assert_eq!(user.name, "Jane");
/// ```
///
/// To configure the deserialization use the [`Deserializer`].
pub fn from_value<'de, T: Deserialize<'de>>(value: &'de Value) -> Result<T, Error> {
    Deserializer::new(value).deserialize()
}

/// Serializes a value into a [`Value`].
///
/// The [event data](deser_core::State::event) of the serialized values (such
/// as formatting hints) is captured in the [meta data](crate::Meta) of the
/// values.
///
/// ```
/// use std::collections::BTreeMap;
/// use deser::Order;
/// use deser_value::{to_value, value};
///
/// let map = BTreeMap::from([("b", 2), ("a", 1)]);
/// let value = to_value(&map).unwrap();
/// assert_eq!(value, value!({"a": 1, "b": 2}));
/// assert_eq!(value.as_map().unwrap().order(), Order::Sorted);
/// ```
///
/// To configure the serialization use the [`Serializer`].
pub fn to_value<T: Serialize>(value: &T) -> Result<Value, Error> {
    let mut serializer = Serializer::new();
    serializer.serialize(value)?;
    Ok(serializer.finish().pop().expect("a value was serialized"))
}

/// Serializes values into [`Value`]s.
///
/// This is a [`Serializer`](deser_core::ser::Serializer) which builds a value
/// from the events of a serialized value.  It's what [`to_value`] uses, use
/// it directly to configure the serialization, for instance to add layers.
/// Every call to [`serialize`](Self::serialize) adds a value:
///
/// ```
/// use deser::ser::{Layer, Next};
/// use deser::{Atom, Error, Event};
/// use deser_value::{Serializer, value};
///
/// /// Writes all numbers as strings.
/// struct NumbersAsStrings;
///
/// impl Layer for NumbersAsStrings {
///     fn event(
///         &mut self,
///         event: Event<'_>,
///         next: &mut Next<'_>,
///     ) -> Result<(), Error> {
///         match event {
///             Event::Atom(Atom::U64(value)) => {
///                 next.emit(value.to_string().into())
///             }
///             event => next.emit(event),
///         }
///     }
/// }
///
/// let mut serializer = Serializer::new();
/// serializer.serialize(&true).unwrap();
/// serializer
///     .serialize_with(&vec![1u64, 2], |driver| {
///         driver.push_layer(NumbersAsStrings)
///     })
///     .unwrap();
/// assert_eq!(serializer.finish(), [value!(true), value!(["1", "2"])]);
/// ```
///
/// The [event data](deser_core::State::event) of the serialized values (such as
/// formatting hints) is captured in the [meta data](crate::Meta) of the
/// values.
#[derive(Debug, Default, Clone)]
pub struct Serializer {
    values: Vec<Value>,
    // the context the values are serialized in
    context: deser_core::Context,
}

impl Serializer {
    /// Creates a serializer.
    pub fn new() -> Serializer {
        Serializer::default()
    }

    /// Serializes a value.
    ///
    /// If the value fails to serialize, nothing is added.
    pub fn serialize<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), Error> {
        ser::Serializer::serialize(self, value)
    }

    /// Serializes a value with a configured driver.
    ///
    /// The callback is invoked with the driver before the value is
    /// serialized, for instance to add [`Layer`](deser_core::ser::Layer)s.
    pub fn serialize_with<F, T: Serialize + ?Sized>(
        &mut self,
        value: &T,
        setup: F,
    ) -> Result<(), Error>
    where
        F: FnOnce(&mut SerializeDriver<'_>),
    {
        ser::Serializer::serialize_with(self, value, setup)
    }

    /// Returns the values serialized so far.
    pub fn values(&self) -> &[Value] {
        &self.values
    }

    /// Returns the values.
    pub fn finish(self) -> Vec<Value> {
        self.values
    }

    /// Sets the context the values are serialized in.
    ///
    /// The values of the context are the defaults of the extension values
    /// of the state (see [`Context`](deser_core::Context)).  A context set
    /// on the driver (for instance in the setup callback of `serialize_with`)
    /// takes precedence.
    pub fn set_context(&mut self, context: deser_core::Context) {
        self.context = context;
    }

    /// Returns the context the values are serialized in.
    pub fn context(&self) -> &deser_core::Context {
        &self.context
    }
}

impl ser::Serializer for Serializer {
    fn drive(&mut self, driver: &mut SerializeDriver<'_>) -> Result<(), Error> {
        if !self.context.is_empty() {
            driver.set_default_context(self.context.clone());
        }
        let mut out = None;
        {
            let mut de = DeserializeDriver::new(&mut out);
            driver.drive(|event, state| {
                de.state_mut()
                    .attach_event_data(&state.capture_event_data());
                de.emit(event)
            })?;
        }
        let value =
            out.ok_or_else(|| Error::new(ErrorKind::EndOfFile, "no value was serialized"))?;
        self.values.push(value);
        Ok(())
    }
}