Coverage Report

Created: 2026-10-28 07:08

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/rust/registry/src/index.crates.io-1949cf8c6b5b557f/deser-value-0.10.1/src/convert.rs
Line
Count
Source
1
use std::sync::Arc;
2
3
use deser_core::Text;
4
use deser_core::de::{self, Deserialize, DeserializeDriver};
5
use deser_core::ser::{self, Serialize, SerializeDriver};
6
use deser_core::{Atom, ContainerShape, Error, ErrorKind, Event, Source};
7
8
use crate::value::{Kind, Value};
9
10
/// Deserializes types from a [`Value`].
11
///
12
/// This is a [`Deserializer`](deser_core::de::Deserializer) which emits the
13
/// events of a value.  It's what
14
/// [`from_value`] uses, use it directly to configure the deserialization,
15
/// for instance to add layers:
16
///
17
/// ```
18
/// use std::collections::BTreeMap;
19
/// use deser_path::{Path, PathLayer};
20
/// use deser_value::{value, Deserializer};
21
///
22
/// let value = value!({"items": [1, "two"]});
23
/// let err = Deserializer::new(&value)
24
///     .deserialize_with::<BTreeMap<String, Vec<u32>>, _>(|driver| {
25
///         driver.push_layer(PathLayer::new());
26
///     })
27
///     .unwrap_err();
28
/// assert_eq!(err.attachment::<Path>().unwrap().to_string(), "items[1]");
29
/// ```
30
///
31
/// Strings and bytes are passed on borrowed from the value, which means
32
/// that types like `&str` can be deserialized.  The [meta data](crate::Meta)
33
/// of the values is restored for every event: event data is attached and if
34
/// the value has spans, the input ranges and the source are published.
35
/// This means that errors refer to the location in the input the value was
36
/// deserialized from.
37
pub struct Deserializer<'a> {
38
    value: &'a Value,
39
    // the context the values are deserialized in
40
    context: deser_core::Context,
41
}
42
43
impl<'a> Deserializer<'a> {
44
    /// Creates a deserializer for a value.
45
0
    pub fn new(value: &'a Value) -> Deserializer<'a> {
46
0
        Deserializer {
47
0
            value,
48
0
            context: deser_core::Context::new(),
49
0
        }
50
0
    }
51
52
    /// Deserializes the value.
53
0
    pub fn deserialize<T: Deserialize<'a>>(&mut self) -> Result<T, Error> {
54
0
        de::Deserializer::deserialize(self)
55
0
    }
56
57
    /// Deserializes the value with a configured driver.
58
    ///
59
    /// The callback is invoked with the driver before the value is
60
    /// deserialized, for instance to add [`Layer`](deser_core::de::Layer)s.
61
0
    pub fn deserialize_with<T, F>(&mut self, setup: F) -> Result<T, Error>
62
0
    where
63
0
        T: Deserialize<'a>,
64
0
        F: FnOnce(&mut DeserializeDriver<'_, 'a>),
65
    {
66
0
        de::Deserializer::deserialize_with(self, setup)
67
0
    }
68
69
    /// Sets the context the values are deserialized in.
70
    ///
71
    /// The values of the context are the defaults of the extension values
72
    /// of the state (see [`Context`](deser_core::Context)).  A context set
73
    /// on the driver (for instance in the setup callback of `deserialize_with`)
74
    /// takes precedence.
75
0
    pub fn set_context(&mut self, context: deser_core::Context) {
76
0
        self.context = context;
77
0
    }
78
79
    /// Returns the context the values are deserialized in.
80
0
    pub fn context(&self) -> &deser_core::Context {
81
0
        &self.context
82
0
    }
83
}
84
85
impl<'de> de::Deserializer<'de> for Deserializer<'de> {
86
0
    fn drive(&mut self, driver: &mut DeserializeDriver<'_, 'de>) -> Result<(), Error> {
87
0
        if !self.context.is_empty() {
88
0
            driver.set_default_context(self.context.clone());
89
0
        }
90
0
        let mut source = None;
91
0
        drive(self.value, driver, &mut source).map_err(|mut err| {
92
0
            if let Some(source) = source {
93
0
                err.resolve_position(source.as_bytes());
94
0
            }
95
0
            err
96
0
        })
97
0
    }
98
}
99
100
/// A map or sequence whose values are emitted.
101
enum Frame<'a> {
102
    Seq(std::slice::Iter<'a, Value>, &'a Value),
103
    Map(MapFrame<'a>, &'a Value),
104
}
105
106
/// A map whose entries are emitted.
107
struct MapFrame<'a> {
108
    iter: indexmap::map::Iter<'a, Value, Value>,
109
    // the value of the key that was emitted
110
    pending: Option<&'a Value>,
111
    // the key and the remaining values of a repeated key of a multimap
112
    repeated: Option<(&'a Value, std::slice::Iter<'a, Value>)>,
113
    multimap: bool,
114
}
115
116
impl<'a> MapFrame<'a> {
117
    /// Returns the next key or value.
118
0
    fn next(&mut self) -> Option<&'a Value> {
119
0
        if let Some(value) = self.pending.take() {
120
0
            return Some(value);
121
0
        }
122
0
        if let Some((key, ref mut values)) = self.repeated {
123
0
            if let Some(value) = values.next() {
124
0
                self.pending = Some(value);
125
0
                return Some(key);
126
0
            }
127
0
            self.repeated = None;
128
0
        }
129
0
        let (key, value) = self.iter.next()?;
130
        // the values of a repeated key are the values of the key given
131
        // more than once
132
0
        if self.multimap
133
0
            && let Some(seq) = value.as_seq()
134
0
            && seq.is_repeated()
135
0
            && !seq.is_empty()
136
0
        {
137
0
            let mut values = seq.iter();
138
0
            self.pending = values.next();
139
0
            self.repeated = Some((key, values));
140
0
        } else {
141
0
            self.pending = Some(value);
142
0
        }
143
0
        Some(key)
144
0
    }
145
}
146
147
/// Publishes the input range and the source of an event.
148
0
fn set_range<'de>(
149
0
    driver: &mut DeserializeDriver<'_, 'de>,
150
0
    current: &mut Option<&'de Arc<str>>,
151
0
    new: &'de Arc<str>,
152
0
    (start, end): (usize, usize),
153
0
) {
154
0
    if !current.is_some_and(|current| Arc::ptr_eq(current, new)) {
155
0
        Source(new.clone()).set(driver.state_mut());
156
0
        *current = Some(new);
157
0
    }
158
0
    driver.state_mut().set_input_range(start, end);
159
0
}
160
161
0
fn drive<'de>(
162
0
    root: &'de Value,
163
0
    driver: &mut DeserializeDriver<'_, 'de>,
164
0
    source: &mut Option<&'de Arc<str>>,
165
0
) -> Result<(), Error> {
166
0
    let mut stack: Vec<Frame<'de>> = Vec::new();
167
0
    let mut next = Some(root);
168
    loop {
169
0
        if let Some(value) = next.take() {
170
0
            if let Some(ref meta) = value.meta {
171
0
                if !meta.event_data().is_empty() {
172
0
                    driver.state_mut().attach_event_data(meta.event_data());
173
0
                }
174
0
                if let Some(span) = meta.span() {
175
0
                    set_range(driver, source, span.source(), span.start_range());
176
0
                }
177
0
            }
178
0
            match value.kind {
179
0
                Kind::Seq(ref seq) => {
180
0
                    let mut seq_shape = shape(seq.len(), seq.order());
181
0
                    seq_shape.set_ambiguous_empty(seq.is_ambiguous_empty());
182
0
                    driver.emit(Event::SeqStart(seq_shape))?;
183
0
                    stack.push(Frame::Seq(seq.iter(), value));
184
                }
185
0
                Kind::Map(ref map) => {
186
0
                    let mut map_shape = shape(map.len(), map.order());
187
0
                    map_shape.set_ambiguous_empty(map.is_ambiguous_empty());
188
0
                    if map.is_multimap() {
189
0
                        // the entries include the values of repeated keys
190
0
                        map_shape = {
191
0
                            let mut shape = ContainerShape::with_order(map.order());
192
0
                            shape.set_multimap(true);
193
0
                            shape
194
0
                        };
195
0
                    }
196
0
                    driver.emit(Event::MapStart(map_shape))?;
197
0
                    stack.push(Frame::Map(
198
0
                        MapFrame {
199
0
                            iter: map.inner.entries.iter(),
200
0
                            pending: None,
201
0
                            repeated: None,
202
0
                            multimap: map.is_multimap(),
203
0
                        },
204
0
                        value,
205
0
                    ));
206
                }
207
0
                ref leaf => driver.emit_borrowed(leaf_atom(leaf))?,
208
            }
209
0
        }
210
211
0
        let Some(frame) = stack.last_mut() else {
212
0
            return Ok(());
213
        };
214
0
        next = match frame {
215
0
            Frame::Seq(iter, _) => iter.next(),
216
0
            Frame::Map(map, _) => map.next(),
217
        };
218
0
        if next.is_none() {
219
0
            let (container, event) = match stack.pop() {
220
0
                Some(Frame::Seq(_, container)) => (container, Event::SeqEnd),
221
0
                Some(Frame::Map(_, container)) => (container, Event::MapEnd),
222
0
                None => unreachable!(),
223
            };
224
0
            if let Some(span) = container.span()
225
0
                && let Some(range) = span.end_range()
226
0
            {
227
0
                set_range(driver, source, span.source(), range);
228
0
            }
229
0
            driver.emit(event)?;
230
0
        }
231
    }
232
0
}
233
234
0
fn shape(len: usize, order: deser_core::Order) -> ContainerShape {
235
    {
236
0
        let mut shape = ContainerShape::with_len(len);
237
0
        shape.set_order(order);
238
0
        shape
239
    }
240
0
}
241
242
/// Returns the atom of a value without children.
243
0
fn leaf_atom(kind: &Kind) -> Atom<'_> {
244
0
    match kind {
245
0
        Kind::Null => Atom::Null,
246
0
        Kind::Bool(value) => Atom::Bool(*value),
247
0
        Kind::U64(value) => Atom::U64(*value),
248
0
        Kind::I64(value) => Atom::I64(*value),
249
0
        Kind::F32(value) => Atom::F32(*value),
250
0
        Kind::F64(value) => Atom::F64(*value),
251
0
        Kind::Char(value) => Atom::Char(*value),
252
0
        Kind::Str(value) => Atom::Str(Text::borrowed(value)),
253
0
        Kind::Lexical(value) => Atom::Lexical(Text::borrowed(value)),
254
0
        Kind::Bytes(value) => Atom::Bytes(value.as_borrowed()),
255
0
        Kind::Ext(value) => Atom::Ext(value.as_borrowed()),
256
0
        Kind::Implicit(value) => Atom::Implicit(value.as_borrowed()),
257
0
        Kind::Seq(_) | Kind::Map(_) => unreachable!("containers are not atoms"),
258
    }
259
0
}
260
261
/// Deserializes a type from a value.
262
///
263
/// Types can borrow strings and bytes from the value.
264
///
265
/// ```
266
/// use deser::Deserialize;
267
/// use deser_value::{from_value, value};
268
///
269
/// #[derive(Debug, Deserialize)]
270
/// struct User<'a> {
271
///     name: &'a str,
272
///     id: u64,
273
/// }
274
///
275
/// let value = value!({"name": "Jane", "id": 42});
276
/// let user: User = from_value(&value).unwrap();
277
/// assert_eq!(user.name, "Jane");
278
/// ```
279
///
280
/// To configure the deserialization use the [`Deserializer`].
281
0
pub fn from_value<'de, T: Deserialize<'de>>(value: &'de Value) -> Result<T, Error> {
282
0
    Deserializer::new(value).deserialize()
283
0
}
284
285
/// Serializes a value into a [`Value`].
286
///
287
/// The [event data](deser_core::State::event) of the serialized values (such
288
/// as formatting hints) is captured in the [meta data](crate::Meta) of the
289
/// values.
290
///
291
/// ```
292
/// use std::collections::BTreeMap;
293
/// use deser::Order;
294
/// use deser_value::{to_value, value};
295
///
296
/// let map = BTreeMap::from([("b", 2), ("a", 1)]);
297
/// let value = to_value(&map).unwrap();
298
/// assert_eq!(value, value!({"a": 1, "b": 2}));
299
/// assert_eq!(value.as_map().unwrap().order(), Order::Sorted);
300
/// ```
301
///
302
/// To configure the serialization use the [`Serializer`].
303
0
pub fn to_value<T: Serialize>(value: &T) -> Result<Value, Error> {
304
0
    let mut serializer = Serializer::new();
305
0
    serializer.serialize(value)?;
306
0
    Ok(serializer.finish().pop().expect("a value was serialized"))
307
0
}
308
309
/// Serializes values into [`Value`]s.
310
///
311
/// This is a [`Serializer`](deser_core::ser::Serializer) which builds a value
312
/// from the events of a serialized value.  It's what [`to_value`] uses, use
313
/// it directly to configure the serialization, for instance to add layers.
314
/// Every call to [`serialize`](Self::serialize) adds a value:
315
///
316
/// ```
317
/// use deser::ser::{Layer, Next};
318
/// use deser::{Atom, Error, Event};
319
/// use deser_value::{Serializer, value};
320
///
321
/// /// Writes all numbers as strings.
322
/// struct NumbersAsStrings;
323
///
324
/// impl Layer for NumbersAsStrings {
325
///     fn event(
326
///         &mut self,
327
///         event: Event<'_>,
328
///         next: &mut Next<'_>,
329
///     ) -> Result<(), Error> {
330
///         match event {
331
///             Event::Atom(Atom::U64(value)) => {
332
///                 next.emit(value.to_string().into())
333
///             }
334
///             event => next.emit(event),
335
///         }
336
///     }
337
/// }
338
///
339
/// let mut serializer = Serializer::new();
340
/// serializer.serialize(&true).unwrap();
341
/// serializer
342
///     .serialize_with(&vec![1u64, 2], |driver| {
343
///         driver.push_layer(NumbersAsStrings)
344
///     })
345
///     .unwrap();
346
/// assert_eq!(serializer.finish(), [value!(true), value!(["1", "2"])]);
347
/// ```
348
///
349
/// The [event data](deser_core::State::event) of the serialized values (such as
350
/// formatting hints) is captured in the [meta data](crate::Meta) of the
351
/// values.
352
#[derive(Debug, Default, Clone)]
353
pub struct Serializer {
354
    values: Vec<Value>,
355
    // the context the values are serialized in
356
    context: deser_core::Context,
357
}
358
359
impl Serializer {
360
    /// Creates a serializer.
361
0
    pub fn new() -> Serializer {
362
0
        Serializer::default()
363
0
    }
364
365
    /// Serializes a value.
366
    ///
367
    /// If the value fails to serialize, nothing is added.
368
0
    pub fn serialize<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), Error> {
369
0
        ser::Serializer::serialize(self, value)
370
0
    }
371
372
    /// Serializes a value with a configured driver.
373
    ///
374
    /// The callback is invoked with the driver before the value is
375
    /// serialized, for instance to add [`Layer`](deser_core::ser::Layer)s.
376
0
    pub fn serialize_with<F, T: Serialize + ?Sized>(
377
0
        &mut self,
378
0
        value: &T,
379
0
        setup: F,
380
0
    ) -> Result<(), Error>
381
0
    where
382
0
        F: FnOnce(&mut SerializeDriver<'_>),
383
    {
384
0
        ser::Serializer::serialize_with(self, value, setup)
385
0
    }
386
387
    /// Returns the values serialized so far.
388
0
    pub fn values(&self) -> &[Value] {
389
0
        &self.values
390
0
    }
391
392
    /// Returns the values.
393
0
    pub fn finish(self) -> Vec<Value> {
394
0
        self.values
395
0
    }
396
397
    /// Sets the context the values are serialized in.
398
    ///
399
    /// The values of the context are the defaults of the extension values
400
    /// of the state (see [`Context`](deser_core::Context)).  A context set
401
    /// on the driver (for instance in the setup callback of `serialize_with`)
402
    /// takes precedence.
403
0
    pub fn set_context(&mut self, context: deser_core::Context) {
404
0
        self.context = context;
405
0
    }
406
407
    /// Returns the context the values are serialized in.
408
0
    pub fn context(&self) -> &deser_core::Context {
409
0
        &self.context
410
0
    }
411
}
412
413
impl ser::Serializer for Serializer {
414
0
    fn drive(&mut self, driver: &mut SerializeDriver<'_>) -> Result<(), Error> {
415
0
        if !self.context.is_empty() {
416
0
            driver.set_default_context(self.context.clone());
417
0
        }
418
0
        let mut out = None;
419
        {
420
0
            let mut de = DeserializeDriver::new(&mut out);
421
0
            driver.drive(|event, state| {
422
0
                de.state_mut()
423
0
                    .attach_event_data(&state.capture_event_data());
424
0
                de.emit(event)
425
0
            })?;
426
        }
427
0
        let value =
428
0
            out.ok_or_else(|| Error::new(ErrorKind::EndOfFile, "no value was serialized"))?;
429
0
        self.values.push(value);
430
0
        Ok(())
431
0
    }
432
}