serde_buf 0.1.3

Generic buffering for serde
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
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
use core::fmt;

use alloc::string::ToString;
use serde_core::de::{
    self,
    value::{U32Deserializer, UnitDeserializer},
    Error as _, IntoDeserializer, Unexpected, Visitor,
};

use crate::{
    raw::{
        skip, Cursor, Leaf, MapHeader, PartVisitor, SeqHeader, StructHeader, StructVariantHeader,
        TupleHeader, TupleStructHeader, TupleVariantHeader, VariantHeader,
    },
    Error, Owned, Ref, RefValue,
};

impl de::Error for Error {
    fn custom<T>(msg: T) -> Self
    where
        T: fmt::Display,
    {
        Error(msg.to_string())
    }
}

/**
A deserializer that produces values from buffers.

This is the result of calling `into_deserializer` on [`Owned`] or [`Ref`].
*/
pub struct Deserializer<'de>(RefValue<'de>);

impl<'de> de::Deserializer<'de> for Deserializer<'de> {
    type Error = Error;

    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: de::Visitor<'de>,
    {
        match self.0 {
            RefValue::Leaf(leaf) => deserialize_leaf(leaf, visitor),
            RefValue::Value(value) => {
                // The buffer must stay alive while it's walked; any data
                // handed out for `'de` is borrowed from beyond the buffer,
                // not within it
                let mut cursor = value.cursor();

                deserialize_part(&mut cursor, visitor)
            }
        }
    }

    serde_core::forward_to_deserialize_any! {
        bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
        bytes byte_buf option unit unit_struct newtype_struct seq tuple
        tuple_struct map struct enum identifier ignored_any
    }
}

impl<'de> IntoDeserializer<'de, Error> for Owned {
    type Deserializer = Deserializer<'de>;

    fn into_deserializer(self) -> Self::Deserializer {
        Deserializer(RefValue::Value(self.0.into_vec()))
    }
}

impl<'de> IntoDeserializer<'de, Error> for Ref<'de> {
    type Deserializer = Deserializer<'de>;

    fn into_deserializer(self) -> Self::Deserializer {
        Deserializer(self.0)
    }
}

fn deserialize_leaf<'de, V>(leaf: Leaf<'de>, visitor: V) -> Result<V::Value, Error>
where
    V: Visitor<'de>,
{
    match leaf {
        Leaf::Unit => visitor.visit_unit(),
        Leaf::Bool(v) => visitor.visit_bool(v),
        Leaf::U8(v) => visitor.visit_u8(v),
        Leaf::U16(v) => visitor.visit_u16(v),
        Leaf::U32(v) => visitor.visit_u32(v),
        Leaf::U64(v) => visitor.visit_u64(v),
        Leaf::U128(v) => visitor.visit_u128(v),
        Leaf::I8(v) => visitor.visit_i8(v),
        Leaf::I16(v) => visitor.visit_i16(v),
        Leaf::I32(v) => visitor.visit_i32(v),
        Leaf::I64(v) => visitor.visit_i64(v),
        Leaf::I128(v) => visitor.visit_i128(v),
        Leaf::F32(v) => visitor.visit_f32(v),
        Leaf::F64(v) => visitor.visit_f64(v),
        Leaf::Char(v) => visitor.visit_char(v),
        Leaf::Str(v) => visitor.visit_borrowed_str(v),
        Leaf::Bytes(v) => visitor.visit_borrowed_bytes(v),
        Leaf::None => visitor.visit_none(),
        Leaf::UnitStruct(_) => visitor.visit_unit(),
        Leaf::UnitVariant { variant_index, .. } => {
            // A unit variant has no content, so it doesn't need a real
            // cursor; `Variant::Unit` never reads from it
            let mut cursor = Cursor::empty();

            visitor.visit_enum(Enum {
                variant_index,
                variant: Variant::Unit,
                cursor: &mut cursor,
            })
        }
    }
}

struct PartDeserializer<'a, 'i, 'de> {
    cursor: &'a mut Cursor<'i, 'de>,
}

impl<'a, 'i, 'de> de::Deserializer<'de> for PartDeserializer<'a, 'i, 'de> {
    type Error = Error;

    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: de::Visitor<'de>,
    {
        deserialize_part(self.cursor, visitor)
    }

    serde_core::forward_to_deserialize_any! {
        bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
        bytes byte_buf option unit unit_struct newtype_struct seq tuple
        tuple_struct map struct enum identifier ignored_any
    }
}

fn deserialize_part<'i, 'de, V>(cursor: &mut Cursor<'i, 'de>, visitor: V) -> Result<V::Value, Error>
where
    V: Visitor<'de>,
{
    // Move the cursor over the whole part once the visitor completes
    struct SkipGuard<'a, 'i, 'de> {
        cursor: &'a mut Cursor<'i, 'de>,
        end: usize,
    }

    impl Drop for SkipGuard<'_, '_, '_> {
        fn drop(&mut self) {
            // SAFETY: The cursor started at a part boundary, so `end` —
            // computed by skipping the whole part — is the boundary of the
            // part that follows it
            unsafe { self.cursor.set_pos(self.end) };
        }
    }

    let end = skip(cursor.bytes(), cursor.pos());
    let guard = SkipGuard { cursor, end };

    deserialize_part_at(guard.cursor, visitor)
}

fn deserialize_part_at<'i, 'de, V>(
    cursor: &mut Cursor<'i, 'de>,
    visitor: V,
) -> Result<V::Value, Error>
where
    V: Visitor<'de>,
{
    // SAFETY: The cursor is at a part boundary: it's either freshly created
    // from a `Value`, or repositioned onto a boundary by the accesses below
    unsafe { cursor.visit_part(DeserializeVisitor { visitor }) }
}

struct DeserializeVisitor<V> {
    visitor: V,
}

impl<'i, 'de, V: Visitor<'de>> PartVisitor<'i, 'de> for DeserializeVisitor<V> {
    type Output = Result<V::Value, Error>;

    fn visit_unit(self) -> Self::Output {
        self.visitor.visit_unit()
    }

    fn visit_bool(self, v: bool) -> Self::Output {
        self.visitor.visit_bool(v)
    }

    fn visit_u8(self, v: u8) -> Self::Output {
        self.visitor.visit_u8(v)
    }

    fn visit_u16(self, v: u16) -> Self::Output {
        self.visitor.visit_u16(v)
    }

    fn visit_u32(self, v: u32) -> Self::Output {
        self.visitor.visit_u32(v)
    }

    fn visit_u64(self, v: u64) -> Self::Output {
        self.visitor.visit_u64(v)
    }

    fn visit_u128(self, v: u128) -> Self::Output {
        self.visitor.visit_u128(v)
    }

    fn visit_i8(self, v: i8) -> Self::Output {
        self.visitor.visit_i8(v)
    }

    fn visit_i16(self, v: i16) -> Self::Output {
        self.visitor.visit_i16(v)
    }

    fn visit_i32(self, v: i32) -> Self::Output {
        self.visitor.visit_i32(v)
    }

    fn visit_i64(self, v: i64) -> Self::Output {
        self.visitor.visit_i64(v)
    }

    fn visit_i128(self, v: i128) -> Self::Output {
        self.visitor.visit_i128(v)
    }

    fn visit_f32(self, v: f32) -> Self::Output {
        self.visitor.visit_f32(v)
    }

    fn visit_f64(self, v: f64) -> Self::Output {
        self.visitor.visit_f64(v)
    }

    fn visit_char(self, v: char) -> Self::Output {
        self.visitor.visit_char(v)
    }

    fn visit_str(self, v: &'i str) -> Self::Output {
        self.visitor.visit_str(v)
    }

    fn visit_borrowed_str(self, v: &'de str) -> Self::Output {
        self.visitor.visit_borrowed_str(v)
    }

    fn visit_bytes(self, v: &'i [u8]) -> Self::Output {
        self.visitor.visit_bytes(v)
    }

    fn visit_borrowed_bytes(self, v: &'de [u8]) -> Self::Output {
        self.visitor.visit_borrowed_bytes(v)
    }

    fn visit_none(self) -> Self::Output {
        self.visitor.visit_none()
    }

    fn visit_some(self, cursor: &mut Cursor<'i, 'de>) -> Self::Output {
        self.visitor.visit_some(PartDeserializer { cursor })
    }

    fn visit_unit_struct(self, _: &'static str) -> Self::Output {
        self.visitor.visit_unit()
    }

    fn visit_newtype_struct(self, _: &'static str, cursor: &mut Cursor<'i, 'de>) -> Self::Output {
        self.visitor
            .visit_newtype_struct(PartDeserializer { cursor })
    }

    fn visit_unit_variant(
        self,
        header: VariantHeader,
        cursor: &mut Cursor<'i, 'de>,
    ) -> Self::Output {
        self.visitor.visit_enum(Enum {
            variant_index: header.variant_index,
            variant: Variant::Unit,
            cursor,
        })
    }

    fn visit_newtype_variant(
        self,
        header: VariantHeader,
        cursor: &mut Cursor<'i, 'de>,
    ) -> Self::Output {
        self.visitor.visit_enum(Enum {
            variant_index: header.variant_index,
            variant: Variant::Newtype,
            cursor,
        })
    }

    fn visit_seq(self, header: SeqHeader, cursor: &mut Cursor<'i, 'de>) -> Self::Output {
        self.visitor.visit_seq(SeqAccess {
            cursor,
            remaining: header.num,
        })
    }

    fn visit_tuple(self, header: TupleHeader, cursor: &mut Cursor<'i, 'de>) -> Self::Output {
        self.visitor.visit_seq(SeqAccess {
            cursor,
            remaining: header.num,
        })
    }

    fn visit_map(self, header: MapHeader, cursor: &mut Cursor<'i, 'de>) -> Self::Output {
        self.visitor.visit_map(MapAccess {
            cursor,
            remaining: header.num,
            expect_value: false,
        })
    }

    fn visit_tuple_struct(
        self,
        header: TupleStructHeader,
        cursor: &mut Cursor<'i, 'de>,
    ) -> Self::Output {
        self.visitor.visit_seq(SeqAccess {
            cursor,
            remaining: header.num,
        })
    }

    fn visit_struct(self, header: StructHeader, cursor: &mut Cursor<'i, 'de>) -> Self::Output {
        self.visitor.visit_map(StructAccess {
            cursor,
            remaining: header.num,
            expect_value: false,
        })
    }

    fn visit_tuple_variant(
        self,
        header: TupleVariantHeader,
        cursor: &mut Cursor<'i, 'de>,
    ) -> Self::Output {
        self.visitor.visit_enum(Enum {
            variant_index: header.variant_index,
            variant: Variant::Tuple(header.num),
            cursor,
        })
    }

    fn visit_struct_variant(
        self,
        header: StructVariantHeader,
        cursor: &mut Cursor<'i, 'de>,
    ) -> Self::Output {
        self.visitor.visit_enum(Enum {
            variant_index: header.variant_index,
            variant: Variant::Struct(header.num),
            cursor,
        })
    }
}

struct SeqAccess<'a, 'i, 'de> {
    cursor: &'a mut Cursor<'i, 'de>,
    remaining: usize,
}

impl<'a, 'i, 'de> de::SeqAccess<'de> for SeqAccess<'a, 'i, 'de> {
    type Error = Error;

    fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
    where
        T: de::DeserializeSeed<'de>,
    {
        if self.remaining == 0 {
            return Ok(None);
        }

        self.remaining -= 1;

        seed.deserialize(PartDeserializer {
            cursor: &mut *self.cursor,
        })
        .map(Some)
    }

    fn size_hint(&self) -> Option<usize> {
        Some(self.remaining)
    }
}

struct MapAccess<'a, 'i, 'de> {
    cursor: &'a mut Cursor<'i, 'de>,
    remaining: usize,
    // Whether a key has been deserialized without its value yet
    expect_value: bool,
}

impl<'a, 'i, 'de> de::MapAccess<'de> for MapAccess<'a, 'i, 'de> {
    type Error = Error;

    fn next_key_seed<D>(&mut self, seed: D) -> Result<Option<D::Value>, Self::Error>
    where
        D: de::DeserializeSeed<'de>,
    {
        // If the last entry's value was never deserialized, skip over it
        if self.expect_value {
            let pos = skip(self.cursor.bytes(), self.cursor.pos());

            // SAFETY: The cursor is at the unconsumed value's part boundary,
            // so `pos` is the boundary of the part after it
            unsafe { self.cursor.set_pos(pos) };
            self.expect_value = false;
        }

        if self.remaining == 0 {
            return Ok(None);
        }

        self.remaining -= 1;

        let key = seed.deserialize(PartDeserializer {
            cursor: &mut *self.cursor,
        })?;

        self.expect_value = true;

        Ok(Some(key))
    }

    fn next_value_seed<D>(&mut self, seed: D) -> Result<D::Value, Self::Error>
    where
        D: de::DeserializeSeed<'de>,
    {
        if !self.expect_value {
            return Err(Error::custom("missing map value"));
        }

        self.expect_value = false;

        seed.deserialize(PartDeserializer {
            cursor: &mut *self.cursor,
        })
    }

    fn size_hint(&self) -> Option<usize> {
        Some(self.remaining)
    }
}

struct StructAccess<'a, 'i, 'de> {
    cursor: &'a mut Cursor<'i, 'de>,
    remaining: usize,
    // Whether a key has been deserialized without its value yet
    expect_value: bool,
}

impl<'a, 'i, 'de> de::MapAccess<'de> for StructAccess<'a, 'i, 'de> {
    type Error = Error;

    fn next_key_seed<D>(&mut self, seed: D) -> Result<Option<D::Value>, Self::Error>
    where
        D: de::DeserializeSeed<'de>,
    {
        // If the last field's value was never deserialized, skip over it
        if self.expect_value {
            let pos = skip(self.cursor.bytes(), self.cursor.pos());

            // SAFETY: The cursor is at the unconsumed value's part boundary,
            // so `pos` is the next field's key (or the end of the struct)
            unsafe { self.cursor.set_pos(pos) };
            self.expect_value = false;
        }

        if self.remaining == 0 {
            return Ok(None);
        }

        self.remaining -= 1;

        // SAFETY: The cursor is at a field key: the decoded struct header
        // left it at the first key, and reading each field's value part (or
        // skipping it above) leaves it at the next
        let key = unsafe { self.cursor.read_field_key() };

        self.expect_value = true;

        seed.deserialize(key.into_deserializer()).map(Some)
    }

    fn next_value_seed<D>(&mut self, seed: D) -> Result<D::Value, Self::Error>
    where
        D: de::DeserializeSeed<'de>,
    {
        if !self.expect_value {
            return Err(Error::custom("missing map value"));
        }

        self.expect_value = false;

        seed.deserialize(PartDeserializer {
            cursor: &mut *self.cursor,
        })
    }

    fn size_hint(&self) -> Option<usize> {
        Some(self.remaining)
    }
}

struct Enum<'a, 'i, 'de> {
    variant_index: u32,
    variant: Variant,
    cursor: &'a mut Cursor<'i, 'de>,
}

enum Variant {
    Unit,
    Newtype,
    Tuple(usize),
    Struct(usize),
}

impl<'a, 'i, 'de> de::EnumAccess<'de> for Enum<'a, 'i, 'de> {
    type Error = Error;

    type Variant = Self;

    fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error>
    where
        V: de::DeserializeSeed<'de>,
    {
        Ok((
            seed.deserialize(U32Deserializer::new(self.variant_index))?,
            self,
        ))
    }
}

struct BodyDeserializer<'a, 'i, 'de> {
    cursor: &'a mut Cursor<'i, 'de>,
    body: Variant,
}

impl<'a, 'i, 'de> de::Deserializer<'de> for BodyDeserializer<'a, 'i, 'de> {
    type Error = Error;

    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: de::Visitor<'de>,
    {
        match self.body {
            Variant::Tuple(num) => visitor.visit_seq(SeqAccess {
                cursor: self.cursor,
                remaining: num,
            }),
            Variant::Struct(num) => visitor.visit_map(StructAccess {
                cursor: self.cursor,
                remaining: num,
                expect_value: false,
            }),
            Variant::Unit | Variant::Newtype => Err(Error::custom("expected a container body")),
        }
    }

    serde_core::forward_to_deserialize_any! {
        bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
        bytes byte_buf option unit unit_struct newtype_struct seq tuple
        tuple_struct map struct enum identifier ignored_any
    }
}

impl<'a, 'i, 'de> de::VariantAccess<'de> for Enum<'a, 'i, 'de> {
    type Error = Error;

    fn unit_variant(self) -> Result<(), Self::Error> {
        match self.variant {
            Variant::Unit => Ok(()),
            Variant::Newtype if self.cursor.is_unit() => Ok(()),
            Variant::Newtype => Err(Error::invalid_type(
                Unexpected::UnitVariant,
                &"newtype variant",
            )),
            Variant::Tuple(_) => Err(Error::invalid_type(
                Unexpected::UnitVariant,
                &"tuple variant",
            )),
            Variant::Struct(_) => Err(Error::invalid_type(
                Unexpected::UnitVariant,
                &"struct variant",
            )),
        }
    }

    fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Self::Error>
    where
        T: de::DeserializeSeed<'de>,
    {
        match self.variant {
            Variant::Unit => seed.deserialize(UnitDeserializer::new()),
            Variant::Newtype => seed.deserialize(PartDeserializer {
                cursor: self.cursor,
            }),
            body @ (Variant::Tuple(_) | Variant::Struct(_)) => seed.deserialize(BodyDeserializer {
                cursor: self.cursor,
                body,
            }),
        }
    }

    fn tuple_variant<V>(self, _: usize, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        match self.variant {
            Variant::Tuple(num) => visitor.visit_seq(SeqAccess {
                cursor: self.cursor,
                remaining: num,
            }),
            Variant::Unit => Err(Error::invalid_type(
                Unexpected::UnitVariant,
                &"tuple variant",
            )),
            Variant::Newtype if self.cursor.is_unit() => Err(Error::invalid_type(
                Unexpected::UnitVariant,
                &"tuple variant",
            )),
            Variant::Newtype => Err(Error::invalid_type(
                Unexpected::NewtypeVariant,
                &"tuple variant",
            )),
            Variant::Struct(_) => Err(Error::invalid_type(
                Unexpected::StructVariant,
                &"tuple variant",
            )),
        }
    }

    fn struct_variant<V>(
        self,
        _: &'static [&'static str],
        visitor: V,
    ) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        match self.variant {
            Variant::Struct(num) => visitor.visit_map(StructAccess {
                cursor: self.cursor,
                remaining: num,
                expect_value: false,
            }),
            Variant::Unit => Err(Error::invalid_type(
                Unexpected::UnitVariant,
                &"struct variant",
            )),
            Variant::Newtype if self.cursor.is_unit() => Err(Error::invalid_type(
                Unexpected::UnitVariant,
                &"struct variant",
            )),
            Variant::Newtype => Err(Error::invalid_type(
                Unexpected::NewtypeVariant,
                &"struct variant",
            )),
            Variant::Tuple(_) => Err(Error::invalid_type(
                Unexpected::TupleVariant,
                &"struct variant",
            )),
        }
    }
}