seabored 0.0.2

Implementation of the CBOR data format. Implements RFC8949 with the preferred-plus recommendations
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
use serde::Deserialize;

use crate::{
    de::CborDeserialize,
    error::SeaboredDeError,
    ib::{self, InitialByte},
    io::Read,
    mt::MajorType,
    serde::{DYN_TAGGED_TYP_NAME, SimpleValue, parse_tag_from_typ},
};

impl serde::de::Error for SeaboredDeError<'_> {
    fn custom<T: std::fmt::Display>(msg: T) -> Self {
        Self::Serde(msg.to_string())
    }
}

pub struct Deserializer<'de, R: Read<'de>> {
    reader: R,
    _marker: std::marker::PhantomData<&'de ()>,
}

impl<'de, R: Read<'de>> Deserializer<'de, R> {
    pub fn new(reader: R) -> Self {
        Self {
            reader,
            _marker: Default::default(),
        }
    }
}

impl<'de, R: Read<'de>> serde::Deserializer<'de> for &mut Deserializer<'de, R> {
    type Error = SeaboredDeError<'de>;

    #[cfg_attr(feature = "inline-nontrivial", inline)]
    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        let ib = InitialByte::peek(&mut self.reader)?;
        match ib.mt() {
            MajorType::Uint => self.deserialize_u64(visitor),
            MajorType::NegativeUint => self.deserialize_i64(visitor),
            MajorType::Bytes => self.deserialize_bytes(visitor),
            MajorType::String => self.deserialize_str(visitor),
            MajorType::Array => self.deserialize_seq(visitor),
            MajorType::Map => self.deserialize_map(visitor),
            MajorType::Tagged => self.deserialize_newtype_struct(DYN_TAGGED_TYP_NAME, visitor),
            MajorType::SimpleValueOrFloat => match ib.0 {
                ib::consts::IB_TRUE | ib::consts::IB_FALSE => self.deserialize_bool(visitor),
                ib::consts::IB_NULL => self.deserialize_option(visitor),
                ib::consts::IB_UNDEFINED => self.deserialize_unit(visitor),
                ib::consts::IB_FLOAT_16 | ib::consts::IB_FLOAT_32 => self.deserialize_f32(visitor),
                ib::consts::IB_FLOAT_64 => self.deserialize_f64(visitor),
                _ => self.deserialize_newtype_struct(SimpleValue::TYP_NAME, visitor),
            },
        }
    }

    #[inline(always)]
    fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        visitor.visit_bool(bool::cbor_deserialize_from(&mut self.reader)?)
    }

    #[inline(always)]
    fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        visitor.visit_i8(i8::cbor_deserialize_from(&mut self.reader)?)
    }

    #[inline(always)]
    fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        visitor.visit_i16(i16::cbor_deserialize_from(&mut self.reader)?)
    }

    #[inline(always)]
    fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        visitor.visit_i32(i32::cbor_deserialize_from(&mut self.reader)?)
    }

    #[inline(always)]
    fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        visitor.visit_i64(i64::cbor_deserialize_from(&mut self.reader)?)
    }

    #[inline(always)]
    fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        visitor.visit_u8(u8::cbor_deserialize_from(&mut self.reader)?)
    }

    #[inline(always)]
    fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        visitor.visit_u16(u16::cbor_deserialize_from(&mut self.reader)?)
    }

    #[inline(always)]
    fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        visitor.visit_u32(u32::cbor_deserialize_from(&mut self.reader)?)
    }

    #[inline(always)]
    fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        visitor.visit_u64(u64::cbor_deserialize_from(&mut self.reader)?)
    }

    #[inline(always)]
    fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        visitor.visit_f32(f32::cbor_deserialize_from(&mut self.reader)?)
    }

    #[inline(always)]
    fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        visitor.visit_f64(f64::cbor_deserialize_from(&mut self.reader)?)
    }

    #[inline(always)]
    fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        match std::borrow::Cow::<str>::cbor_deserialize_from(&mut self.reader)? {
            std::borrow::Cow::Borrowed(s) => visitor.visit_borrowed_str(s),
            std::borrow::Cow::Owned(s) => visitor.visit_string(s),
        }
    }

    #[inline(always)]
    fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        self.deserialize_str(visitor)
    }

    #[inline(always)]
    fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        match std::borrow::Cow::<[u8]>::cbor_deserialize_from(&mut self.reader)? {
            std::borrow::Cow::Borrowed(buf_ref) => visitor.visit_borrowed_bytes(buf_ref),
            std::borrow::Cow::Owned(buf) => visitor.visit_byte_buf(buf),
        }
    }

    #[inline(always)]
    fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        self.deserialize_bytes(visitor)
    }

    #[inline(always)]
    fn deserialize_char<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        self.deserialize_str(visitor)
    }

    #[inline(always)]
    fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        let ib = InitialByte::peek(&mut self.reader)?;
        if ib.0 != ib::consts::IB_NULL {
            visitor.visit_some(self)
        } else {
            self.reader.advance(1)?;
            visitor.visit_none()
        }
    }

    #[inline(always)]
    fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        let ib = InitialByte::cbor_deserialize_from(&mut self.reader)?;
        if ib.0 != ib::consts::IB_UNDEFINED {
            return Err(SeaboredDeError::IncorrectMajorType {
                actual: ib.mt(),
                expected: &[MajorType::SimpleValueOrFloat],
            });
        }

        visitor.visit_unit()
    }

    #[inline(always)]
    fn deserialize_unit_struct<V>(
        self,
        _name: &'static str,
        visitor: V,
    ) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        self.deserialize_unit(visitor)
    }

    #[cfg_attr(feature = "inline-nontrivial", inline)]
    fn deserialize_newtype_struct<V>(
        self,
        name: &'static str,
        visitor: V,
    ) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        // Dyn taagged value accessor (eg: Value::Tagged contained in a struct)
        if name == DYN_TAGGED_TYP_NAME {
            return visitor
                .visit_newtype_struct(&mut DynamicTaggedValueAccessor { parent: &mut *self });
        }

        // SimpleValue special handling
        if name == SimpleValue::TYP_NAME {
            return visitor.visit_newtype_struct(&mut SimpleValueAccessor { parent: &mut *self });
        }

        // Special TaggedValue struct handling
        // We're going to read the provisional tag from the type name
        // Then we'll deserialize and check it against the wire data
        if let Some(expected_tag) = parse_tag_from_typ(name) {
            // Consume tag and check it
            let ib = InitialByte::cbor_deserialize_from(&mut self.reader)?;
            let (mt, ai) = ib.mt_ai();
            if mt != MajorType::Tagged {
                return Err(SeaboredDeError::IncorrectMajorType {
                    actual: mt,
                    expected: &[MajorType::Tagged],
                });
            }

            let tag: u64 = ai.find_subsequent_len(&mut self.reader)?.into();
            if tag != expected_tag {
                return Err(SeaboredDeError::WrongTag {
                    actual: tag,
                    expected: expected_tag,
                });
            }
        }

        visitor.visit_newtype_struct(self)
    }

    #[cfg_attr(feature = "inline-nontrivial", inline)]
    fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        let ib = InitialByte::cbor_deserialize_from(&mut self.reader)?;
        let (mt, ai) = ib.mt_ai();
        if mt != MajorType::Array {
            return Err(SeaboredDeError::IncorrectMajorType {
                actual: mt,
                expected: &[MajorType::Array],
            });
        }

        let len = ai.find_subsequent_len(&mut self.reader)?;
        visitor.visit_seq(SeqAccessor {
            parent: self,
            len: Some(len.try_into()?),
        })
    }

    #[cfg_attr(feature = "inline-nontrivial", inline)]
    fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        let ib = InitialByte::cbor_deserialize_from(&mut self.reader)?;
        let mt = ib.mt();
        if mt != MajorType::Array {
            return Err(SeaboredDeError::IncorrectMajorType {
                actual: mt,
                expected: &[MajorType::Array],
            });
        }

        // let deser_len: usize = ai.find_subsequent_len(&mut self.reader)?.try_into()?;

        // if deser_len != len {
        // FIXME: Verify if that's needed or not?
        // return Err(SeaboredDeError::Io(std::io::Error::new(
        //     std::io::ErrorKind::UnexpectedEof,
        //     format!("Expected {len} elements, CBOR presents {deser_len} elements"),
        // )));
        // }

        visitor.visit_seq(SeqAccessor {
            parent: self,
            len: Some(len),
        })
    }

    #[inline(always)]
    fn deserialize_tuple_struct<V>(
        self,
        _name: &'static str,
        len: usize,
        visitor: V,
    ) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        self.deserialize_tuple(len, visitor)
    }

    #[cfg_attr(feature = "inline-nontrivial", inline)]
    fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        let ib = InitialByte::cbor_deserialize_from(&mut self.reader)?;
        let (mt, ai) = ib.mt_ai();
        if mt != MajorType::Map {
            return Err(SeaboredDeError::IncorrectMajorType {
                actual: mt,
                expected: &[MajorType::Map],
            });
        }

        let len = ai.find_subsequent_len(&mut self.reader)?;
        visitor.visit_map(SeqAccessor {
            parent: self,
            len: Some(len.try_into()?),
        })
    }

    #[inline(always)]
    fn deserialize_struct<V>(
        self,
        _name: &'static str,
        _fields: &'static [&'static str],
        visitor: V,
    ) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        self.deserialize_map(visitor)
    }

    #[inline(always)]
    fn deserialize_enum<V>(
        self,
        _name: &'static str,
        _variants: &'static [&'static str],
        visitor: V,
    ) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        let ib = InitialByte::peek(&mut self.reader)?;
        if ib.0 == ib::consts::IB_SMALL_MAP | 1 {
            // Skip the map itself basially, otherwise let everything error out
            self.reader.advance(1)?;
        }
        visitor.visit_enum(self)
    }

    #[inline(always)]
    fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        self.deserialize_str(visitor)
    }

    #[inline(always)]
    fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        let _ = crate::Value::deserialize(self)?;
        visitor.visit_unit()
    }

    #[inline(always)]
    fn is_human_readable(&self) -> bool {
        false
    }
}

impl<'de, R: Read<'de>> serde::de::EnumAccess<'de> for &mut Deserializer<'de, R> {
    type Error = SeaboredDeError<'de>;

    type Variant = Self;

    #[inline(always)]
    fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error>
    where
        V: serde::de::DeserializeSeed<'de>,
    {
        let variant = seed.deserialize(&mut *self)?;
        Ok((variant, self))
    }
}

impl<'de, R: Read<'de>> serde::de::VariantAccess<'de> for &mut Deserializer<'de, R> {
    type Error = SeaboredDeError<'de>;

    #[inline(always)]
    fn unit_variant(self) -> Result<(), Self::Error> {
        Ok(())
    }

    #[inline(always)]
    fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Self::Error>
    where
        T: serde::de::DeserializeSeed<'de>,
    {
        seed.deserialize(&mut *self)
    }

    #[inline(always)]
    fn tuple_variant<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        use serde::de::Deserializer as _;
        self.deserialize_tuple(len, visitor)
    }

    #[inline(always)]
    fn struct_variant<V>(
        self,
        _fields: &'static [&'static str],
        visitor: V,
    ) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        use serde::de::Deserializer as _;
        self.deserialize_map(visitor)
    }
}

pub(crate) struct DynamicTaggedValueAccessor<'a, 'de, R: Read<'de>> {
    parent: &'a mut Deserializer<'de, R>,
}

// Lil hack to pass over the serde fence
thread_local! {
    pub(crate) static TAG: std::cell::Cell<Option<u64>> = const { std::cell::Cell::new(None) };
}

impl<'a, 'de, R: Read<'de>> serde::Deserializer<'de>
    for &mut DynamicTaggedValueAccessor<'a, 'de, R>
{
    type Error = SeaboredDeError<'de>;

    #[cfg_attr(feature = "inline-nontrivial", inline)]
    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        // Consume tag and check it
        let ib = InitialByte::cbor_deserialize_from(&mut self.parent.reader)?;
        let (mt, ai) = ib.mt_ai();
        if mt != MajorType::Tagged {
            return Err(SeaboredDeError::IncorrectMajorType {
                actual: mt,
                expected: &[MajorType::Tagged],
            });
        }

        // Cache the tag in the structure, we'll go fetch it on the other side
        TAG.set(Some(
            ai.find_subsequent_len(&mut self.parent.reader)?.into(),
        ));

        visitor.visit_newtype_struct(&mut *self.parent)
    }

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

struct SimpleValueAccessor<'a, 'de, R: Read<'de>> {
    parent: &'a mut Deserializer<'de, R>,
}

impl<'a, 'de, R: Read<'de>> serde::Deserializer<'de> for &mut SimpleValueAccessor<'a, 'de, R> {
    type Error = SeaboredDeError<'de>;

    #[cfg_attr(feature = "inline-nontrivial", inline)]
    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        let ib = InitialByte::cbor_deserialize_from(&mut self.parent.reader)?;
        let mt = ib.mt();
        if mt != MajorType::SimpleValueOrFloat {
            return Err(SeaboredDeError::IncorrectMajorType {
                actual: mt,
                expected: &[MajorType::SimpleValueOrFloat],
            });
        }

        let u8_value = match ib.0 {
            value @ ib::consts::IB_SIMPLE_VALUE..ib::consts::IB_FALSE => {
                value - ib::consts::IB_SIMPLE_VALUE
            }
            ib::consts::IB_SIMPLE_VALUE_NEXT_BYTE => self.parent.reader.read_byte()?,
            _ => return Err(SeaboredDeError::ReservedSimpleValue(ib.0)),
        };

        visitor.visit_u8(u8_value)
    }

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

struct SeqAccessor<'a, 'de, R: Read<'de>> {
    parent: &'a mut Deserializer<'de, R>,
    len: Option<usize>,
}

impl<'a, 'de, R: Read<'de>> SeqAccessor<'a, 'de, R> {
    #[cfg_attr(feature = "inline-nontrivial", inline)]
    fn deser_from_seed<S: serde::de::DeserializeSeed<'de>>(
        &mut self,
        seed: S,
    ) -> Result<Option<S::Value>, SeaboredDeError<'de>> {
        Ok(if let Some(len) = &mut self.len {
            if *len > 0 {
                let value = seed.deserialize(&mut *self.parent)?;
                *len -= 1;
                Some(value)
            } else {
                None
            }
        } else {
            let ib = InitialByte::peek(&mut self.parent.reader)?;

            if ib.0 != ib::consts::IB_BREAK {
                Some(seed.deserialize(&mut *self.parent)?)
            } else {
                self.parent.reader.advance(1)?;
                None
            }
        })
    }
}

impl<'a, 'de, R: Read<'de>> serde::de::SeqAccess<'de> for SeqAccessor<'a, 'de, R> {
    type Error = SeaboredDeError<'de>;

    #[inline(always)]
    fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
    where
        T: serde::de::DeserializeSeed<'de>,
    {
        self.deser_from_seed(seed)
    }

    #[inline(always)]
    fn size_hint(&self) -> Option<usize> {
        self.len
    }
}

impl<'a, 'de, R: Read<'de>> serde::de::MapAccess<'de> for SeqAccessor<'a, 'de, R> {
    type Error = SeaboredDeError<'de>;

    #[inline(always)]
    fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error>
    where
        K: serde::de::DeserializeSeed<'de>,
    {
        self.deser_from_seed(seed)
    }

    #[inline(always)]
    fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::DeserializeSeed<'de>,
    {
        seed.deserialize(&mut *self.parent)
    }

    #[inline(always)]
    fn size_hint(&self) -> Option<usize> {
        self.len
    }
}