deser 0.10.0

An experimental serialization and deserialization library for Rust
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
use std::collections::BTreeMap;

use deser::de::{DeserializeDriver, DeserializeOwned, IgnoredFields, Recording, UnknownFields};
use deser::{ContainerShape, Deserialize, Error, Event};

fn deserialize<T: DeserializeOwned>(
    policy: Option<UnknownFields>,
    events: Vec<Event<'_>>,
) -> Result<T, Error> {
    let mut out = None;
    {
        let mut driver = DeserializeDriver::new(&mut out);
        if let Some(policy) = policy {
            policy.set(driver.state_mut());
        }
        for event in events {
            driver.emit(event)?;
        }
    }
    Ok(out.unwrap())
}

fn map<'a>(pairs: &[(&'a str, Event<'a>)]) -> Vec<Event<'a>> {
    let mut events = vec![Event::map_start()];
    for (key, value) in pairs {
        events.push((*key).into());
        events.push(value.clone());
    }
    events.push(Event::MapEnd);
    events
}

/// The events of a recorded map, recordings know the length of maps.
fn recorded_map<'a>(pairs: &[(&'a str, Event<'a>)]) -> Vec<Event<'a>> {
    let mut events = map(pairs);
    events[0] = Event::MapStart(ContainerShape::with_len(pairs.len()));
    events
}

fn message<T: std::fmt::Debug>(rv: Result<T, Error>) -> String {
    rv.unwrap_err().message().to_string()
}

#[derive(Debug, Deserialize, PartialEq)]
struct Point {
    x: u32,
    y: u32,
}

#[derive(Debug, Deserialize, PartialEq)]
#[deser(deny_unknown_fields)]
struct StrictPoint {
    x: u32,
    y: u32,
}

#[test]
fn test_ignored_by_default() {
    let point: Point = deserialize(
        None,
        map(&[("x", 1u64.into()), ("z", 2u64.into()), ("y", 3u64.into())]),
    )
    .unwrap();
    assert_eq!(point, Point { x: 1, y: 3 });
}

#[test]
fn test_policy_error() {
    let rv = deserialize::<Point>(
        Some(UnknownFields::Error),
        map(&[("x", 1u64.into()), ("z", 2u64.into()), ("y", 3u64.into())]),
    );
    assert_eq!(message(rv), "unknown field `z`, expected `x` or `y`");

    // compound values of unknown keys are rejected before they start
    let mut events = map(&[("x", 1u64.into()), ("y", 3u64.into())]);
    events.splice(1..1, ["z".into(), Event::seq_start(), Event::SeqEnd]);
    let rv = deserialize::<Point>(Some(UnknownFields::Error), events);
    assert_eq!(message(rv), "unknown field `z`, expected `x` or `y`");
}

#[test]
fn test_attribute() {
    let rv = deserialize::<StrictPoint>(
        None,
        map(&[("x", 1u64.into()), ("z", 2u64.into()), ("y", 3u64.into())]),
    );
    assert_eq!(message(rv), "unknown field `z`, expected `x` or `y`");

    // the attribute wins over the policy
    let ignored = IgnoredFields::new();
    let rv = deserialize::<StrictPoint>(
        Some(UnknownFields::Collect(ignored.clone())),
        map(&[("x", 1u64.into()), ("z", 2u64.into()), ("y", 3u64.into())]),
    );
    assert_eq!(message(rv), "unknown field `z`, expected `x` or `y`");
    assert!(ignored.is_empty());

    let point: StrictPoint =
        deserialize(None, map(&[("x", 1u64.into()), ("y", 3u64.into())])).unwrap();
    assert_eq!(point, StrictPoint { x: 1, y: 3 });
}

#[test]
fn test_collect() {
    let ignored = IgnoredFields::new();
    let point: Point = deserialize(
        Some(UnknownFields::Collect(ignored.clone())),
        map(&[
            ("x", 1u64.into()),
            ("z", 2u64.into()),
            ("y", 3u64.into()),
            ("w", 4u64.into()),
        ]),
    )
    .unwrap();
    assert_eq!(point, Point { x: 1, y: 3 });
    let ignored = ignored.take();
    let messages = ignored.iter().map(|x| x.message()).collect::<Vec<_>>();
    assert_eq!(
        messages,
        [
            "unknown field `z`, expected `x` or `y`",
            "unknown field `w`, expected `x` or `y`"
        ]
    );
}

#[derive(Debug, Deserialize, PartialEq)]
struct Inner {
    a: u32,
}

#[derive(Debug, Deserialize, PartialEq)]
#[deser(deny_unknown_fields)]
struct Outer {
    b: u32,
    #[deser(flatten)]
    inner: Inner,
}

#[derive(Debug, Deserialize, PartialEq)]
#[deser(deny_unknown_fields)]
struct Nested {
    c: u32,
    #[deser(flatten)]
    outer: Outer,
}

#[test]
fn test_flatten() {
    // the keys of flattened fields are known (serde#1547, serde#2384)
    let outer: Outer = deserialize(None, map(&[("a", 1u64.into()), ("b", 2u64.into())])).unwrap();
    assert_eq!(
        outer,
        Outer {
            b: 2,
            inner: Inner { a: 1 }
        }
    );
    let rv = deserialize::<Outer>(
        None,
        map(&[("a", 1u64.into()), ("x", 2u64.into()), ("b", 2u64.into())]),
    );
    // flattened fields can take any key, the fields are not listed
    assert_eq!(message(rv), "unknown field `x`");

    let nested: Nested = deserialize(
        None,
        map(&[("a", 1u64.into()), ("b", 2u64.into()), ("c", 3u64.into())]),
    )
    .unwrap();
    assert_eq!(nested.outer.inner.a, 1);
    let rv = deserialize::<Nested>(
        None,
        map(&[
            ("a", 1u64.into()),
            ("b", 2u64.into()),
            ("c", 3u64.into()),
            ("d", 4u64.into()),
        ]),
    );
    assert_eq!(message(rv), "unknown field `d`");
}

#[derive(Debug, Deserialize, PartialEq)]
struct WithExtra {
    a: u32,
    #[deser(flatten)]
    extra: BTreeMap<String, u32>,
}

#[test]
fn test_flattened_map_takes_everything() {
    let value: WithExtra = deserialize(
        Some(UnknownFields::Error),
        map(&[("a", 1u64.into()), ("b", 2u64.into())]),
    )
    .unwrap();
    assert_eq!(value.extra.get("b"), Some(&2));
}

#[derive(Debug, Deserialize, PartialEq)]
#[deser(tag = "type", deny_unknown_fields)]
enum Shape {
    Circle { radius: u32 },
    Empty,
    Wrapped(Point),
}

#[test]
fn test_internally_tagged() {
    // the tag is not an unknown field (serde#2666)
    let shape: Shape = deserialize(
        None,
        map(&[("radius", 1u64.into()), ("type", "Circle".into())]),
    )
    .unwrap();
    assert_eq!(shape, Shape::Circle { radius: 1 });
    let rv = deserialize::<Shape>(
        None,
        map(&[
            ("radius", 1u64.into()),
            ("type", "Circle".into()),
            ("x", 1u64.into()),
        ]),
    );
    assert_eq!(message(rv), "unknown field `x`, expected `radius`");

    // keys before the tag are recorded
    let rv = deserialize::<Shape>(None, map(&[("x", 1u64.into()), ("type", "Circle".into())]));
    assert_eq!(message(rv), "unknown field `x`, expected `radius`");

    // unit variants (serde#2294)
    assert_eq!(
        deserialize::<Shape>(None, map(&[("type", "Empty".into())])).unwrap(),
        Shape::Empty
    );
    let rv = deserialize::<Shape>(None, map(&[("type", "Empty".into()), ("x", 1u64.into())]));
    assert_eq!(message(rv), "unknown field `x`, there are no fields");

    // newtype variants are up to the inner type
    assert_eq!(
        deserialize::<Shape>(
            None,
            map(&[
                ("type", "Wrapped".into()),
                ("x", 1u64.into()),
                ("y", 2u64.into()),
                ("z", 3u64.into())
            ])
        )
        .unwrap(),
        Shape::Wrapped(Point { x: 1, y: 2 })
    );
}

#[derive(Debug, Deserialize, PartialEq)]
#[deser(tag = "kind")]
enum Kind {
    A { a: u32 },
    B { b: u32 },
}

#[derive(Debug, Deserialize, PartialEq)]
#[deser(deny_unknown_fields)]
struct Holder {
    id: u32,
    #[deser(flatten)]
    kind: Kind,
}

#[test]
fn test_flattened_internally_tagged() {
    // serde#1358: the keys of the variant are known
    let holder: Holder = deserialize(
        None,
        map(&[
            ("a", 1u64.into()),
            ("id", 2u64.into()),
            ("kind", "A".into()),
        ]),
    )
    .unwrap();
    assert_eq!(
        holder,
        Holder {
            id: 2,
            kind: Kind::A { a: 1 }
        }
    );
    let holder: Holder = deserialize(
        None,
        map(&[
            ("kind", "B".into()),
            ("id", 2u64.into()),
            ("b", 1u64.into()),
        ]),
    )
    .unwrap();
    assert_eq!(holder.kind, Kind::B { b: 1 });

    // keys before the tag that the variant does not take
    let rv = deserialize::<Holder>(
        None,
        map(&[
            ("x", 1u64.into()),
            ("kind", "A".into()),
            ("a", 1u64.into()),
            ("id", 2u64.into()),
        ]),
    );
    assert_eq!(message(rv), "unknown field `x`");
    // and after the tag
    let rv = deserialize::<Holder>(
        None,
        map(&[
            ("kind", "A".into()),
            ("a", 1u64.into()),
            ("id", 2u64.into()),
            ("x", 1u64.into()),
        ]),
    );
    assert_eq!(message(rv), "unknown field `x`");

    // the policy applies the same way
    let ignored = IgnoredFields::new();
    #[derive(Debug, Deserialize)]
    struct LaxHolder {
        #[allow(unused)]
        id: u32,
        #[deser(flatten)]
        #[allow(unused)]
        kind: Kind,
    }
    deserialize::<LaxHolder>(
        Some(UnknownFields::Collect(ignored.clone())),
        map(&[
            ("x", 1u64.into()),
            ("kind", "A".into()),
            ("a", 1u64.into()),
            ("y", 1u64.into()),
            ("id", 2u64.into()),
        ]),
    )
    .unwrap();
    let ignored = ignored.take();
    let mut messages = ignored.iter().map(|x| x.message()).collect::<Vec<_>>();
    messages.sort();
    assert_eq!(messages, ["unknown field `x`", "unknown field `y`"]);
}

#[derive(Debug, Deserialize, PartialEq)]
#[deser(tag = "t", content = "c", deny_unknown_fields)]
enum Adjacent {
    A(u32),
    B { b: u32 },
}

#[test]
fn test_adjacently_tagged() {
    assert_eq!(
        deserialize::<Adjacent>(None, map(&[("t", "A".into()), ("c", 1u64.into())])).unwrap(),
        Adjacent::A(1)
    );
    let rv = deserialize::<Adjacent>(
        None,
        map(&[("t", "A".into()), ("x", 1u64.into()), ("c", 1u64.into())]),
    );
    assert_eq!(message(rv), "unknown field `x`, expected `t` or `c`");
    let mut events = vec![Event::map_start(), "t".into(), "B".into(), "c".into()];
    events.extend(map(&[("b", 1u64.into()), ("x", 1u64.into())]));
    events.push(Event::MapEnd);
    let rv = deserialize::<Adjacent>(None, events);
    assert_eq!(message(rv), "unknown field `x`, expected `b`");
}

#[derive(Debug, Deserialize, PartialEq)]
#[deser(untagged, deny_unknown_fields)]
enum Untagged {
    Empty {},
    Point { x: u32, y: u32 },
}

#[test]
fn test_untagged() {
    // strict variants do not match maps with other keys (serde#1560)
    assert_eq!(
        deserialize::<Untagged>(None, map(&[("x", 1u64.into()), ("y", 2u64.into())])).unwrap(),
        Untagged::Point { x: 1, y: 2 }
    );
    assert_eq!(
        deserialize::<Untagged>(None, map(&[])).unwrap(),
        Untagged::Empty {}
    );
}

#[derive(Debug, Deserialize, PartialEq)]
#[deser(untagged)]
enum LooseUntagged {
    Flag(bool),
    Point(Point),
}

#[test]
fn test_untagged_collect() {
    // the errors of failed variants are thrown away, collected ones are kept
    let ignored = IgnoredFields::new();
    let value: LooseUntagged = deserialize(
        Some(UnknownFields::Collect(ignored.clone())),
        map(&[("x", 1u64.into()), ("z", 2u64.into()), ("y", 3u64.into())]),
    )
    .unwrap();
    assert_eq!(value, LooseUntagged::Point(Point { x: 1, y: 3 }));
    let ignored = ignored.take();
    let messages = ignored.iter().map(|x| x.message()).collect::<Vec<_>>();
    assert_eq!(messages, ["unknown field `z`, expected `x` or `y`"]);
}

#[derive(Debug, Deserialize)]
#[deser(tag = "type")]
enum Passthrough {
    #[allow(unused)]
    Known { a: u32 },
    #[deser(other)]
    #[allow(unused)]
    Unknown(#[deser(tag)] String, Recording),
}

#[test]
fn test_other_variants() {
    // other variants with a recording take everything
    let value: Passthrough = deserialize(
        Some(UnknownFields::Error),
        map(&[("type", "X".into()), ("b", 1u64.into())]),
    )
    .unwrap();
    assert!(matches!(value, Passthrough::Unknown(ref tag, _) if tag == "X"));
}

#[derive(Debug, Deserialize)]
#[deser(deny_unknown_fields)]
struct PassthroughHolder {
    id: u32,
    #[deser(flatten)]
    kind: Passthrough,
}

#[derive(Debug, Deserialize)]
#[deser(deny_unknown_fields)]
struct WithRest {
    id: u32,
    #[deser(flatten)]
    rest: Recording,
}

#[test]
fn test_flattened_recordings() {
    // recordings take all keys when flattened, before and after the tag
    let value: PassthroughHolder = deserialize(
        None,
        map(&[
            ("x", 1u64.into()),
            ("type", "X".into()),
            ("y", 2u64.into()),
            ("id", 3u64.into()),
        ]),
    )
    .unwrap();
    assert_eq!(value.id, 3);
    let Passthrough::Unknown(tag, content) = value.kind else {
        panic!("expected the other variant");
    };
    assert_eq!(tag, "X");
    assert_eq!(
        content.events().cloned().collect::<Vec<_>>(),
        recorded_map(&[("x", 1u64.into()), ("y", 2u64.into())])
    );

    let value: WithRest = deserialize(
        None,
        map(&[("x", 1u64.into()), ("id", 3u64.into()), ("y", 2u64.into())]),
    )
    .unwrap();
    assert_eq!(value.id, 3);
    assert_eq!(
        value.rest.events().cloned().collect::<Vec<_>>(),
        recorded_map(&[("x", 1u64.into()), ("y", 2u64.into())])
    );

    // without keys the recording is an empty map
    let value: WithRest = deserialize(None, map(&[("id", 3u64.into())])).unwrap();
    assert_eq!(
        value.rest.events().cloned().collect::<Vec<_>>(),
        recorded_map(&[])
    );
}

#[test]
fn test_variant_deny_unknown_fields() {
    #[derive(Debug, Deserialize, PartialEq)]
    #[deser(tag = "type")]
    enum Message {
        #[deser(deny_unknown_fields)]
        Strict {
            a: u32,
        },
        Lenient {
            a: u32,
        },
        #[deser(deny_unknown_fields)]
        Empty,
    }

    let rv = deserialize::<Message>(
        None,
        map(&[
            ("type", "Strict".into()),
            ("a", 1u64.into()),
            ("b", 1u64.into()),
        ]),
    );
    assert_eq!(message(rv), "unknown field `b`, expected `a`");
    assert_eq!(
        deserialize::<Message>(
            None,
            map(&[
                ("type", "Lenient".into()),
                ("a", 1u64.into()),
                ("b", 1u64.into()),
            ]),
        )
        .unwrap(),
        Message::Lenient { a: 1 }
    );
    let rv = deserialize::<Message>(None, map(&[("type", "Empty".into()), ("x", 1u64.into())]));
    assert_eq!(message(rv), "unknown field `x`, there are no fields");

    #[derive(Debug, Deserialize, PartialEq)]
    enum External {
        #[deser(deny_unknown_fields)]
        Strict { a: u32 },
    }

    let rv = deserialize::<External>(
        None,
        vec![
            Event::map_start(),
            "Strict".into(),
            Event::map_start(),
            "c".into(),
            1u64.into(),
        ],
    );
    assert_eq!(message(rv), "unknown field `c`, expected `a`");
}