cbor2 0.5.0

A serde implementation of CBOR (RFC 8949) with a dynamic Value type and tag support.
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
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
//! Serde deserialization support for CBOR.

use std::io::Read;

use serde::de::{self, value::BytesDeserializer, Deserializer as _};

use crate::core::{simple, tag, Decoder, Header};
use crate::tag::TagAccess;

/// An error that occurred during deserialization.
#[derive(Debug)]
pub enum Error {
    /// An error from the underlying reader.
    Io(std::io::Error),

    /// The input is not well-formed CBOR.
    ///
    /// Contains the byte offset of the offending item.
    Syntax(usize),

    /// The input is well-formed CBOR but invalid for the target type.
    ///
    /// Contains a description of the error and (optionally) the byte offset
    /// of the item being processed when the error occurred.
    Semantic(Option<usize>, String),

    /// The input is nested deeper than the configured recursion limit.
    ///
    /// This error prevents stack exhaustion from adversarial input.
    RecursionLimitExceeded,
}

impl Error {
    /// A helper for composing a semantic error.
    #[inline]
    pub fn semantic(offset: impl Into<Option<usize>>, msg: impl Into<String>) -> Self {
        Self::Semantic(offset.into(), msg.into())
    }
}

impl From<std::io::Error> for Error {
    #[inline]
    fn from(value: std::io::Error) -> Self {
        Self::Io(value)
    }
}

impl From<crate::core::Error> for Error {
    #[inline]
    fn from(value: crate::core::Error) -> Self {
        match value {
            crate::core::Error::Io(x) => Self::Io(x),
            crate::core::Error::Syntax(x) => Self::Syntax(x),
        }
    }
}

impl core::fmt::Display for Error {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Error::Io(err) => write!(f, "i/o error: {err}"),
            Error::Syntax(offset) => write!(f, "syntax error at offset {offset}"),
            Error::Semantic(Some(offset), msg) => {
                write!(f, "semantic error at offset {offset}: {msg}")
            }
            Error::Semantic(None, msg) => write!(f, "semantic error: {msg}"),
            Error::RecursionLimitExceeded => write!(f, "recursion limit exceeded"),
        }
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Error::Io(err) => Some(err),
            _ => None,
        }
    }
}

impl de::Error for Error {
    #[inline]
    fn custom<U: core::fmt::Display>(msg: U) -> Self {
        Self::Semantic(None, msg.to_string())
    }
}

trait Expected {
    fn expected(self, kind: &'static str) -> Error;
}

impl Expected for Header {
    #[inline]
    fn expected(self, kind: &'static str) -> Error {
        de::Error::invalid_type(
            match self {
                Header::Positive(x) => de::Unexpected::Unsigned(x),
                Header::Negative(x) => de::Unexpected::Signed(x as i64 ^ !0),
                Header::Bytes(..) => de::Unexpected::Other("bytes"),
                Header::Text(..) => de::Unexpected::Other("string"),

                Header::Array(..) => de::Unexpected::Seq,
                Header::Map(..) => de::Unexpected::Map,

                Header::Tag(..) => de::Unexpected::Other("tag"),

                Header::Simple(simple::FALSE) => de::Unexpected::Bool(false),
                Header::Simple(simple::TRUE) => de::Unexpected::Bool(true),
                Header::Simple(simple::NULL) => de::Unexpected::Other("null"),
                Header::Simple(simple::UNDEFINED) => de::Unexpected::Other("undefined"),
                Header::Simple(..) => de::Unexpected::Other("simple"),

                Header::Float(x) => de::Unexpected::Float(x),
                Header::Break => de::Unexpected::Other("break"),
            },
            &kind,
        )
    }
}

// A parsed integer item: either a (possibly negative) integer that was
// encoded with major type 0 or 1, or a bignum (tag 2 or 3) whose payload is
// given with leading zeros stripped.
enum Num {
    Pos(u64),
    Neg(u64),
    BigPos(Vec<u8>),
    BigNeg(Vec<u8>),
}

// Interprets a stripped bignum payload as a `u128`, if it fits.
fn big_to_u128(bytes: &[u8]) -> Option<u128> {
    if bytes.len() > 16 {
        return None;
    }

    let mut buffer = [0u8; 16];
    buffer[16 - bytes.len()..].copy_from_slice(bytes);
    Some(u128::from_be_bytes(buffer))
}

/// A serde deserializer that reads CBOR from a [`std::io::Read`].
pub struct Deserializer<R> {
    decoder: Decoder<R>,
    scratch: Vec<u8>,
    recurse: usize,
}

/// The default recursion limit for nested CBOR items.
pub const DEFAULT_RECURSION_LIMIT: usize = 256;

impl<R: Read> Deserializer<R> {
    /// Creates a deserializer with the default recursion limit.
    ///
    /// For repeated small reads consider wrapping the reader in a
    /// [`std::io::BufReader`].
    pub fn from_reader(reader: R) -> Self {
        Self::with_recursion_limit(reader, DEFAULT_RECURSION_LIMIT)
    }

    /// Creates a deserializer with the given recursion limit.
    ///
    /// Inputs nested deeper than the limit fail with
    /// [`Error::RecursionLimitExceeded`]. Set a high limit at your own risk
    /// of stack exhaustion.
    pub fn with_recursion_limit(reader: R, limit: usize) -> Self {
        Self {
            decoder: reader.into(),
            scratch: Vec::new(),
            recurse: limit,
        }
    }

    /// Returns the byte offset of the next item in the stream.
    #[inline]
    pub fn offset(&self) -> usize {
        self.decoder.offset()
    }

    /// Turns this deserializer into an iterator over consecutive top-level
    /// items.
    ///
    /// CBOR allows concatenating encoded items into a *sequence* (RFC 8742).
    /// The iterator yields decoded items until the input is exhausted; a
    /// clean end of input terminates the iterator, while anything else
    /// (including a truncated item) yields an error.
    // Named for symmetry with `serde_json::Deserializer::into_iter`.
    #[allow(clippy::should_implement_trait)]
    pub fn into_iter<T: de::DeserializeOwned>(self) -> Iter<T, R> {
        Iter {
            de: self,
            _marker: core::marker::PhantomData,
        }
    }

    #[inline]
    fn recurse<V, F: FnOnce(&mut Self) -> Result<V, Error>>(
        &mut self,
        func: F,
    ) -> Result<V, Error> {
        if self.recurse == 0 {
            return Err(Error::RecursionLimitExceeded);
        }

        self.recurse -= 1;
        let result = func(self);
        self.recurse += 1;
        result
    }

    // Pulls the next integer item, skipping any tags other than the bignum
    // tags.
    fn number(&mut self) -> Result<Num, Error> {
        loop {
            let header = self.decoder.pull()?;

            let neg = match header {
                Header::Positive(x) => return Ok(Num::Pos(x)),
                Header::Negative(x) => return Ok(Num::Neg(x)),
                Header::Tag(tag::BIGPOS) => false,
                Header::Tag(tag::BIGNEG) => true,
                Header::Tag(..) => continue,
                header => return Err(header.expected("integer")),
            };

            let bytes = self.bignum()?;
            return Ok(match neg {
                false => Num::BigPos(bytes),
                true => Num::BigNeg(bytes),
            });
        }
    }

    // Reads the byte string payload following a bignum tag (2 or 3) and
    // strips its leading zeros: an empty result encodes zero (RFC 8949
    // ยง3.4.3).
    fn bignum(&mut self) -> Result<Vec<u8>, Error> {
        let mut bytes = Vec::new();
        match self.decoder.pull()? {
            Header::Bytes(len) => self.decoder.bytes_body(len, &mut bytes)?,
            header => return Err(header.expected("bytes")),
        }

        let first = bytes.iter().position(|&b| b != 0).unwrap_or(bytes.len());
        bytes.drain(..first);
        Ok(bytes)
    }

    fn unsigned(&mut self) -> Result<u128, Error> {
        match self.number()? {
            Num::Pos(x) => Ok(x.into()),
            Num::BigPos(b) => big_to_u128(&b).ok_or_else(|| de::Error::custom("bigint too large")),
            _ => Err(de::Error::custom("unexpected negative integer")),
        }
    }

    fn signed(&mut self) -> Result<i128, Error> {
        let raw = match self.number()? {
            Num::Pos(x) => return Ok(x.into()),
            Num::Neg(x) => return Ok(x as i128 ^ !0),
            Num::BigPos(b) => {
                return big_to_u128(&b)
                    .and_then(|x| i128::try_from(x).ok())
                    .ok_or_else(|| de::Error::custom("integer too large"));
            }
            Num::BigNeg(b) => {
                big_to_u128(&b).ok_or_else(|| Error::semantic(None, "integer too large"))?
            }
        };

        match i128::try_from(raw) {
            Ok(x) => Ok(x ^ !0),
            Err(..) => Err(de::Error::custom("integer too large")),
        }
    }
}

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

    #[inline]
    fn deserialize_any<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        let header = self.decoder.pull()?;

        // Tags are handled here directly; everything else is pushed back
        // and re-dispatched to the matching typed entry point.
        if let Header::Tag(tag) = header {
            return match tag {
                // Bignums lossy-coerce into plain integers whenever they
                // fit; otherwise they survive as a tagged byte string.
                tag::BIGPOS | tag::BIGNEG => {
                    let b = self.bignum()?;

                    let int = match big_to_u128(&b) {
                        Some(x) if tag == tag::BIGPOS => return visitor.visit_u128(x),
                        Some(x) => i128::try_from(x).ok().map(|x| x ^ !0),
                        None => None,
                    };

                    match int {
                        Some(x) => visitor.visit_i128(x),
                        None => {
                            let access = TagAccess::new(BytesDeserializer::new(&b), Some(tag));
                            visitor.visit_enum(access)
                        }
                    }
                }

                _ => self.recurse(|me| {
                    let access = TagAccess::new(me, Some(tag));
                    visitor.visit_enum(access)
                }),
            };
        }

        self.decoder.push(header);

        match header {
            Header::Positive(..) => self.deserialize_u64(visitor),
            Header::Negative(x) => match i64::try_from(x) {
                Ok(..) => self.deserialize_i64(visitor),
                Err(..) => self.deserialize_i128(visitor),
            },

            Header::Bytes(..) => self.deserialize_byte_buf(visitor),
            Header::Text(..) => self.deserialize_string(visitor),

            Header::Array(..) => self.deserialize_seq(visitor),
            Header::Map(..) => self.deserialize_map(visitor),

            Header::Float(..) => self.deserialize_f64(visitor),

            Header::Simple(simple::FALSE) => self.deserialize_bool(visitor),
            Header::Simple(simple::TRUE) => self.deserialize_bool(visitor),
            Header::Simple(simple::NULL) => self.deserialize_option(visitor),
            Header::Simple(simple::UNDEFINED) => self.deserialize_option(visitor),
            h @ Header::Simple(..) => Err(h.expected("known simple value")),

            // Only `Break` is left: the tag case was handled above.
            h => Err(h.expected("non-break")),
        }
    }

    #[inline]
    fn deserialize_bool<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        loop {
            let offset = self.decoder.offset();

            return match self.decoder.pull()? {
                Header::Tag(..) => continue,
                Header::Simple(simple::FALSE) => visitor.visit_bool(false),
                Header::Simple(simple::TRUE) => visitor.visit_bool(true),
                _ => Err(Error::semantic(offset, "expected bool")),
            };
        }
    }

    #[inline]
    fn deserialize_f32<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        self.deserialize_f64(visitor)
    }

    #[inline]
    fn deserialize_f64<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        loop {
            return match self.decoder.pull()? {
                Header::Tag(..) => continue,
                Header::Float(x) => visitor.visit_f64(x),
                h => Err(h.expected("float")),
            };
        }
    }

    fn deserialize_i8<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        self.deserialize_i64(visitor)
    }

    fn deserialize_i16<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        self.deserialize_i64(visitor)
    }

    fn deserialize_i32<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        self.deserialize_i64(visitor)
    }

    fn deserialize_i64<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        match self.signed()?.try_into() {
            Ok(x) => visitor.visit_i64(x),
            Err(..) => Err(de::Error::custom("integer too large")),
        }
    }

    fn deserialize_i128<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        visitor.visit_i128(self.signed()?)
    }

    fn deserialize_u8<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        self.deserialize_u64(visitor)
    }

    fn deserialize_u16<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        self.deserialize_u64(visitor)
    }

    fn deserialize_u32<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        self.deserialize_u64(visitor)
    }

    fn deserialize_u64<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        match self.unsigned()?.try_into() {
            Ok(x) => visitor.visit_u64(x),
            Err(..) => Err(de::Error::custom("integer too large")),
        }
    }

    fn deserialize_u128<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        visitor.visit_u128(self.unsigned()?)
    }

    fn deserialize_char<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        loop {
            let offset = self.decoder.offset();
            let header = self.decoder.pull()?;

            return match header {
                Header::Tag(..) => continue,

                Header::Text(Some(len)) if len <= 4 => {
                    let mut buffer = [0u8; 4];
                    self.decoder.read_exact(&mut buffer[..len])?;

                    match core::str::from_utf8(&buffer[..len]) {
                        Ok(s) => {
                            let mut chars = s.chars();
                            match (chars.next(), chars.next()) {
                                (Some(c), None) => visitor.visit_char(c),
                                _ => Err(header.expected("char")),
                            }
                        }
                        Err(..) => Err(Error::Syntax(offset)),
                    }
                }

                _ => Err(header.expected("char")),
            };
        }
    }

    fn deserialize_str<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        self.deserialize_string(visitor)
    }

    fn deserialize_string<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        loop {
            return match self.decoder.pull()? {
                Header::Tag(..) => continue,

                Header::Text(len) => {
                    let mut buffer = String::new();
                    self.decoder.text_body(len, &mut buffer)?;
                    visitor.visit_string(buffer)
                }

                header => Err(header.expected("string")),
            };
        }
    }

    fn deserialize_bytes<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        self.deserialize_byte_buf(visitor)
    }

    fn deserialize_byte_buf<V: de::Visitor<'de>>(
        self,
        visitor: V,
    ) -> Result<V::Value, Self::Error> {
        loop {
            return match self.decoder.pull()? {
                Header::Tag(..) => continue,

                Header::Bytes(len) => {
                    let mut buffer = Vec::new();
                    self.decoder.bytes_body(len, &mut buffer)?;
                    visitor.visit_byte_buf(buffer)
                }

                // Be liberal: accept an array of integers as bytes.
                Header::Array(len) => self.recurse(|me| visitor.visit_seq(Access(me, len))),

                header => Err(header.expected("bytes")),
            };
        }
    }

    fn deserialize_seq<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        loop {
            return match self.decoder.pull()? {
                Header::Tag(..) => continue,

                Header::Array(len) => self.recurse(|me| visitor.visit_seq(Access(me, len))),

                // Be liberal: accept a byte string as a sequence of integers.
                Header::Bytes(len) => {
                    let mut buffer = Vec::new();
                    self.decoder.bytes_body(len, &mut buffer)?;
                    visitor.visit_seq(BytesAccess(0, buffer))
                }

                header => Err(header.expected("array")),
            };
        }
    }

    fn deserialize_map<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        loop {
            return match self.decoder.pull()? {
                Header::Tag(..) => continue,
                Header::Map(len) => self.recurse(|me| visitor.visit_map(Access(me, len))),
                header => Err(header.expected("map")),
            };
        }
    }

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

    fn deserialize_tuple<V: de::Visitor<'de>>(
        self,
        _len: usize,
        visitor: V,
    ) -> Result<V::Value, Self::Error> {
        self.deserialize_seq(visitor)
    }

    fn deserialize_tuple_struct<V: de::Visitor<'de>>(
        self,
        _name: &'static str,
        _len: usize,
        visitor: V,
    ) -> Result<V::Value, Self::Error> {
        self.deserialize_seq(visitor)
    }

    fn deserialize_identifier<V: de::Visitor<'de>>(
        self,
        visitor: V,
    ) -> Result<V::Value, Self::Error> {
        loop {
            let offset = self.decoder.offset();

            return match self.decoder.pull()? {
                Header::Tag(..) => continue,

                Header::Text(Some(len)) => {
                    self.scratch.clear();
                    self.decoder.bytes_body(Some(len), &mut self.scratch)?;

                    match core::str::from_utf8(&self.scratch) {
                        Ok(s) => visitor.visit_str(s),
                        Err(..) => Err(Error::Syntax(offset)),
                    }
                }

                Header::Bytes(Some(len)) => {
                    self.scratch.clear();
                    self.decoder.bytes_body(Some(len), &mut self.scratch)?;
                    visitor.visit_bytes(&self.scratch)
                }

                // Integer keys (as used by COSE, RFC 9052) match struct
                // fields through the marked decimal form generated by the
                // `#[cbor2::int_keys]` attribute macro.
                Header::Positive(x) => {
                    use std::io::Write as _;

                    self.scratch.clear();
                    let _ = write!(&mut self.scratch, "{}{x}", crate::ser::KEY_MARKER);
                    visitor.visit_str(core::str::from_utf8(&self.scratch).expect("decimal"))
                }

                Header::Negative(x) => {
                    use std::io::Write as _;

                    self.scratch.clear();
                    let _ = write!(
                        &mut self.scratch,
                        "{}{}",
                        crate::ser::KEY_MARKER,
                        -1 - i128::from(x)
                    );
                    visitor.visit_str(core::str::from_utf8(&self.scratch).expect("decimal"))
                }

                header => Err(header.expected("str, bytes or an integer")),
            };
        }
    }

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

    #[inline]
    fn deserialize_option<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        match self.decoder.pull()? {
            Header::Simple(simple::UNDEFINED) => visitor.visit_none(),
            Header::Simple(simple::NULL) => visitor.visit_none(),
            header => {
                self.decoder.push(header);
                visitor.visit_some(self)
            }
        }
    }

    #[inline]
    fn deserialize_unit<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        loop {
            return match self.decoder.pull()? {
                Header::Simple(simple::UNDEFINED) => visitor.visit_unit(),
                Header::Simple(simple::NULL) => visitor.visit_unit(),
                Header::Tag(..) => continue,
                header => Err(header.expected("unit")),
            };
        }
    }

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

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

    #[inline]
    fn deserialize_enum<V: de::Visitor<'de>>(
        self,
        name: &'static str,
        _variants: &'static [&'static str],
        visitor: V,
    ) -> Result<V::Value, Self::Error> {
        if name == crate::tag::NAME {
            let tag = match self.decoder.pull()? {
                Header::Tag(x) => Some(x),
                header => {
                    self.decoder.push(header);
                    None
                }
            };

            return self.recurse(|me| visitor.visit_enum(TagAccess::new(me, tag)));
        }

        loop {
            // An enum variant is either encoded as a map with a single entry
            // (the variant name and its payload) or, for a unit variant, as
            // a bare text string.
            let map = match self.decoder.pull()? {
                Header::Tag(..) => continue,
                Header::Map(Some(1)) => true,
                header @ Header::Text(..) => {
                    self.decoder.push(header);
                    false
                }
                header => return Err(header.expected("enum")),
            };

            return self.recurse(|me| visitor.visit_enum(Enum(me, map)));
        }
    }

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

struct Access<'a, R>(&'a mut Deserializer<R>, Option<usize>);

impl<'de, R: Read> de::SeqAccess<'de> for Access<'_, R> {
    type Error = Error;

    #[inline]
    fn next_element_seed<U: de::DeserializeSeed<'de>>(
        &mut self,
        seed: U,
    ) -> Result<Option<U::Value>, Self::Error> {
        match self.1 {
            Some(0) => return Ok(None),
            Some(x) => self.1 = Some(x - 1),
            None => match self.0.decoder.pull()? {
                Header::Break => return Ok(None),
                header => self.0.decoder.push(header),
            },
        }

        seed.deserialize(&mut *self.0).map(Some)
    }

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

impl<'de, R: Read> de::MapAccess<'de> for Access<'_, R> {
    type Error = Error;

    #[inline]
    fn next_key_seed<K: de::DeserializeSeed<'de>>(
        &mut self,
        seed: K,
    ) -> Result<Option<K::Value>, Self::Error> {
        match self.1 {
            Some(0) => return Ok(None),
            Some(x) => self.1 = Some(x - 1),
            None => match self.0.decoder.pull()? {
                Header::Break => return Ok(None),
                header => self.0.decoder.push(header),
            },
        }

        seed.deserialize(&mut *self.0).map(Some)
    }

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

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

// Variant access for an enum item.
//
// The boolean field indicates whether the variant was encoded as a
// single-entry map (`true`) or as a bare text string (`false`). The bare
// form only encodes a unit variant, so payload accesses in that form must
// not consume any further items from the stream.
struct Enum<'a, R>(&'a mut Deserializer<R>, bool);

impl<'de, R: Read> de::EnumAccess<'de> for Enum<'_, R> {
    type Error = Error;
    type Variant = Self;

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

impl<'de, R: Read> de::VariantAccess<'de> for Enum<'_, R> {
    type Error = Error;

    #[inline]
    fn unit_variant(self) -> Result<(), Self::Error> {
        if self.1 {
            // The map form carries a payload; require it to be a unit.
            <() as de::Deserialize>::deserialize(&mut *self.0)?;
        }

        Ok(())
    }

    #[inline]
    fn newtype_variant_seed<U: de::DeserializeSeed<'de>>(
        self,
        seed: U,
    ) -> Result<U::Value, Self::Error> {
        if !self.1 {
            return Err(de::Error::invalid_type(
                de::Unexpected::UnitVariant,
                &"newtype variant",
            ));
        }

        seed.deserialize(&mut *self.0)
    }

    #[inline]
    fn tuple_variant<V: de::Visitor<'de>>(
        self,
        _len: usize,
        visitor: V,
    ) -> Result<V::Value, Self::Error> {
        if !self.1 {
            return Err(de::Error::invalid_type(
                de::Unexpected::UnitVariant,
                &"tuple variant",
            ));
        }

        self.0.deserialize_seq(visitor)
    }

    #[inline]
    fn struct_variant<V: de::Visitor<'de>>(
        self,
        _fields: &'static [&'static str],
        visitor: V,
    ) -> Result<V::Value, Self::Error> {
        if !self.1 {
            return Err(de::Error::invalid_type(
                de::Unexpected::UnitVariant,
                &"struct variant",
            ));
        }

        self.0.deserialize_map(visitor)
    }
}

// Yields the contents of a byte string as a sequence of integers.
struct BytesAccess(usize, Vec<u8>);

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

    #[inline]
    fn next_element_seed<U: de::DeserializeSeed<'de>>(
        &mut self,
        seed: U,
    ) -> Result<Option<U::Value>, Self::Error> {
        use de::IntoDeserializer;

        if self.0 < self.1.len() {
            let byte = self.1[self.0];
            self.0 += 1;
            seed.deserialize(byte.into_deserializer()).map(Some)
        } else {
            Ok(None)
        }
    }

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

/// An iterator decoding consecutive top-level items from a reader.
///
/// Created by [`Deserializer::into_iter`].
pub struct Iter<T, R> {
    de: Deserializer<R>,
    _marker: core::marker::PhantomData<T>,
}

impl<T: de::DeserializeOwned, R: Read> Iterator for Iter<T, R> {
    type Item = Result<T, Error>;

    fn next(&mut self) -> Option<Self::Item> {
        let start = self.de.decoder.offset();

        // Probe for a clean end of input: end-of-file before the first byte
        // of an item terminates the stream, anywhere else it is an error.
        match self.de.decoder.pull() {
            Ok(header) => self.de.decoder.push(header),
            Err(crate::core::Error::Io(err))
                if err.kind() == std::io::ErrorKind::UnexpectedEof
                    && self.de.decoder.offset() == start =>
            {
                return None;
            }
            Err(err) => return Some(Err(err.into())),
        }

        Some(T::deserialize(&mut self.de))
    }
}

/// Checks that the input contains exactly one well-formed CBOR item.
///
/// The input is walked structurally without building any values: **no heap
/// memory is allocated**. String bodies are skipped through a fixed-size
/// stack buffer and nesting is bounded by [`DEFAULT_RECURSION_LIMIT`], so
/// adversarial input can neither exhaust memory nor the stack.
///
/// Beyond well-formedness (RFC 8949 ยง5.3.1) this verifies that text strings
/// are valid UTF-8 (every segment of an indefinite-length text string on
/// its own, as the RFC requires). Unassigned simple values are accepted:
/// they are well-formed, even though the serde interface has no
/// representation for them.
///
/// Trailing data after the item is an error; to handle a CBOR sequence
/// (RFC 8742), validate items one at a time from the shared reader.
///
/// ```rust
/// assert!(cbor2::validate(&b"\x83\x01\x02\x03"[..]).is_ok()); // [1, 2, 3]
/// assert!(cbor2::validate(&b"\x83\x01\x02"[..]).is_err()); // truncated
/// assert!(cbor2::validate(&b"\x62\xff\xfe"[..]).is_err()); // invalid UTF-8
/// ```
pub fn validate<R: Read>(reader: R) -> Result<(), Error> {
    let mut decoder = Decoder::from(reader);
    validate_item(&mut decoder, DEFAULT_RECURSION_LIMIT)?;
    expect_eof(&mut decoder)
}

// Requires the input to be exhausted.
pub(crate) fn expect_eof<R: Read>(decoder: &mut Decoder<R>) -> Result<(), Error> {
    let offset = decoder.offset();
    let mut probe = [0u8; 1];
    match decoder.read_exact(&mut probe) {
        Err(err) if err.kind() == std::io::ErrorKind::UnexpectedEof => Ok(()),
        Err(err) => Err(Error::Io(err)),
        Ok(()) => Err(Error::semantic(offset, "trailing data after the item")),
    }
}

fn validate_item<R: Read>(decoder: &mut Decoder<R>, depth: usize) -> Result<(), Error> {
    let offset = decoder.offset();
    let header = decoder.pull()?;
    validate_header(decoder, header, offset, depth)
}

fn validate_header<R: Read>(
    decoder: &mut Decoder<R>,
    header: Header,
    offset: usize,
    depth: usize,
) -> Result<(), Error> {
    if depth == 0 {
        return Err(Error::RecursionLimitExceeded);
    }

    match header {
        Header::Positive(..) | Header::Negative(..) | Header::Float(..) | Header::Simple(..) => {
            Ok(())
        }

        Header::Break => Err(Error::Syntax(offset)),

        Header::Tag(..) => validate_item(decoder, depth - 1),

        Header::Bytes(len) => match len {
            Some(len) => skip_body(decoder, len),
            None => loop {
                let offset = decoder.offset();
                match decoder.pull()? {
                    Header::Break => return Ok(()),
                    // Segments must be definite-length strings of the same
                    // major type (RFC 8949 ยง3.2.3).
                    Header::Bytes(Some(len)) => skip_body(decoder, len)?,
                    _ => return Err(Error::Syntax(offset)),
                }
            },
        },

        Header::Text(len) => match len {
            Some(len) => check_utf8_body(decoder, len),
            None => loop {
                let offset = decoder.offset();
                match decoder.pull()? {
                    Header::Break => return Ok(()),
                    Header::Text(Some(len)) => check_utf8_body(decoder, len)?,
                    _ => return Err(Error::Syntax(offset)),
                }
            },
        },

        Header::Array(len) => match len {
            Some(len) => {
                for _ in 0..len {
                    validate_item(decoder, depth - 1)?;
                }
                Ok(())
            }
            None => loop {
                let offset = decoder.offset();
                match decoder.pull()? {
                    Header::Break => return Ok(()),
                    header => validate_header(decoder, header, offset, depth - 1)?,
                }
            },
        },

        Header::Map(len) => match len {
            Some(len) => {
                for _ in 0..len {
                    validate_item(decoder, depth - 1)?; // key
                    validate_item(decoder, depth - 1)?; // value
                }
                Ok(())
            }
            None => {
                let mut expecting_value = false;
                loop {
                    let offset = decoder.offset();
                    match decoder.pull()? {
                        // A break in place of a value leaves a dangling key,
                        // which is not well-formed (RFC 8949 ยง5.3.1).
                        Header::Break if expecting_value => return Err(Error::Syntax(offset)),
                        Header::Break => return Ok(()),
                        header => {
                            validate_header(decoder, header, offset, depth - 1)?;
                            expecting_value = !expecting_value;
                        }
                    }
                }
            }
        },
    }
}

// Discards a definite-length body through a fixed-size buffer; a forged
// length cannot trigger an allocation.
fn skip_body<R: Read>(decoder: &mut Decoder<R>, mut remaining: usize) -> Result<(), Error> {
    let mut buffer = [0u8; 4096];
    while remaining > 0 {
        let n = remaining.min(buffer.len());
        decoder.read_exact(&mut buffer[..n])?;
        remaining -= n;
    }
    Ok(())
}

// Discards a definite-length text body, verifying that the whole body is
// valid UTF-8. Characters may straddle the internal chunk boundaries; up to
// three trailing bytes of an incomplete character carry over to the next
// chunk.
fn check_utf8_body<R: Read>(decoder: &mut Decoder<R>, len: usize) -> Result<(), Error> {
    let offset = decoder.offset();
    let mut buffer = [0u8; 4096];
    let mut carry = 0usize;
    let mut remaining = len;

    while remaining > 0 {
        let n = remaining.min(buffer.len() - carry);
        decoder.read_exact(&mut buffer[carry..carry + n])?;
        remaining -= n;
        let filled = carry + n;

        match core::str::from_utf8(&buffer[..filled]) {
            Ok(..) => carry = 0,
            Err(err) => {
                // An incomplete character is only acceptable while more
                // body bytes are coming.
                if err.error_len().is_some() || remaining == 0 {
                    return Err(Error::Syntax(offset));
                }

                let valid = err.valid_up_to();
                buffer.copy_within(valid..filled, 0);
                carry = filled - valid;
            }
        }
    }

    Ok(())
}

/// Deserializes a value from CBOR read out of a [`std::io::Read`].
///
/// For repeated small reads consider wrapping the reader in a
/// [`std::io::BufReader`].
#[inline]
pub fn from_reader<T: de::DeserializeOwned, R: Read>(reader: R) -> Result<T, Error> {
    let mut deserializer = Deserializer::from_reader(reader);
    T::deserialize(&mut deserializer)
}

/// Deserializes a value from a byte slice of CBOR.
#[inline]
pub fn from_slice<T: de::DeserializeOwned>(slice: &[u8]) -> Result<T, Error> {
    from_reader(slice)
}