oasis_cbor_value/
reader.rs

1// Copyright 2019 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//      http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Functionality for deserializing CBOR data into values.
16
17use alloc::{str, vec::Vec};
18
19use super::values::{Constants, SimpleValue, Value};
20use crate::{
21    cbor_array_vec, cbor_bytes_lit, cbor_map_collection, cbor_tagged, cbor_text, cbor_unsigned,
22};
23
24/// Possible errors from a deserialization operation.
25#[derive(Debug, PartialEq)]
26pub enum DecoderError {
27    UnsupportedMajorType,
28    UnknownAdditionalInfo,
29    IncompleteCborData,
30    TooMuchNesting,
31    InvalidUtf8,
32    ExtraneousData,
33    OutOfOrderKey,
34    NonMinimalCborEncoding,
35    UnsupportedSimpleValue,
36    UnsupportedFloatingPointValue,
37}
38
39/// Deserialize CBOR binary data to produce a single [`Value`], expecting that there is no additional data.
40/// Maximum level of nesting supported is 127; more deeply nested structures will fail with
41/// [`DecoderError::TooMuchNesting`].
42pub fn read(encoded_cbor: &[u8]) -> Result<Value, DecoderError> {
43    read_nested(encoded_cbor, Some(i8::MAX))
44}
45
46/// Deserialize CBOR binary data to produce a single [`Value`], expecting that there is no additional data.  If
47/// `max_nest` is `Some(max)`, then nested structures are only supported up to the given limit (returning
48/// [`DecoderError::TooMuchNesting`] if the limit is hit).
49pub fn read_nested(encoded_cbor: &[u8], max_nest: Option<i8>) -> Result<Value, DecoderError> {
50    let mut reader = Reader::new(encoded_cbor);
51    let value = reader.decode_complete_data_item(max_nest)?;
52    if !reader.remaining_cbor.is_empty() {
53        return Err(DecoderError::ExtraneousData);
54    }
55    Ok(value)
56}
57
58/// Deserialize CBOR binary data to produce a single [`Value`].  If `max_nest` is `Some(max)`, then
59/// nested structures are only supported up to the given limit (returning
60/// [`DecoderError::TooMuchNesting`] if the limit is hit).
61pub fn read_nested_non_strict(
62    encoded_cbor: &[u8],
63    max_nest: Option<i8>,
64) -> Result<Value, DecoderError> {
65    let mut reader = Reader::new_non_strict(encoded_cbor);
66    let value = reader.decode_complete_data_item(max_nest)?;
67    Ok(value)
68}
69
70struct Reader<'a> {
71    non_strict: bool,
72    remaining_cbor: &'a [u8],
73}
74
75impl<'a> Reader<'a> {
76    pub fn new(cbor: &'a [u8]) -> Reader<'a> {
77        Reader {
78            non_strict: false,
79            remaining_cbor: cbor,
80        }
81    }
82
83    pub fn new_non_strict(cbor: &'a [u8]) -> Reader<'a> {
84        Reader {
85            non_strict: true,
86            remaining_cbor: cbor,
87        }
88    }
89
90    pub fn decode_complete_data_item(
91        &mut self,
92        remaining_depth: Option<i8>,
93    ) -> Result<Value, DecoderError> {
94        if remaining_depth.map_or(false, |d| d < 0) {
95            return Err(DecoderError::TooMuchNesting);
96        }
97
98        match self.read_bytes(1) {
99            Some([first_byte]) => {
100                // Unsigned byte means logical shift, so only zeros get shifted in.
101                let major_type_value = first_byte >> Constants::MAJOR_TYPE_BIT_SHIFT;
102                let additional_info = first_byte & Constants::ADDITIONAL_INFORMATION_MASK;
103                let size_value = self.read_variadic_length_integer(additional_info)?;
104                match major_type_value {
105                    0 => self.decode_value_to_unsigned(size_value),
106                    1 => self.decode_value_to_negative(size_value),
107                    2 => self.read_byte_string_content(size_value),
108                    3 => self.read_text_string_content(size_value),
109                    4 => self.read_array_content(size_value, remaining_depth),
110                    5 => self.read_map_content(size_value, remaining_depth),
111                    6 => self.read_tagged_content(size_value, remaining_depth),
112                    7 => self.decode_to_simple_value(size_value, additional_info),
113                    _ => Err(DecoderError::UnsupportedMajorType),
114                }
115            }
116            _ => Err(DecoderError::IncompleteCborData),
117        }
118    }
119
120    fn read_bytes(&mut self, num_bytes: usize) -> Option<&[u8]> {
121        if num_bytes > self.remaining_cbor.len() {
122            None
123        } else {
124            let (left, right) = self.remaining_cbor.split_at(num_bytes);
125            self.remaining_cbor = right;
126            Some(left)
127        }
128    }
129
130    fn read_variadic_length_integer(&mut self, additional_info: u8) -> Result<u64, DecoderError> {
131        let additional_bytes_num = match additional_info {
132            0..=Constants::ADDITIONAL_INFORMATION_MAX_INT => return Ok(additional_info as u64),
133            Constants::ADDITIONAL_INFORMATION_1_BYTE => 1,
134            Constants::ADDITIONAL_INFORMATION_2_BYTES => 2,
135            Constants::ADDITIONAL_INFORMATION_4_BYTES => 4,
136            Constants::ADDITIONAL_INFORMATION_8_BYTES => 8,
137            _ => return Err(DecoderError::UnknownAdditionalInfo),
138        };
139        match self.read_bytes(additional_bytes_num) {
140            Some(bytes) => {
141                let mut size_value = 0u64;
142                for byte in bytes {
143                    size_value <<= 8;
144                    size_value += *byte as u64;
145                }
146                if ((additional_bytes_num == 1 && size_value < 24)
147                    || size_value < (1u64 << (8 * (additional_bytes_num >> 1))))
148                    && !self.non_strict
149                {
150                    Err(DecoderError::NonMinimalCborEncoding)
151                } else {
152                    Ok(size_value)
153                }
154            }
155            None => Err(DecoderError::IncompleteCborData),
156        }
157    }
158
159    fn decode_value_to_unsigned(&self, size_value: u64) -> Result<Value, DecoderError> {
160        Ok(cbor_unsigned!(size_value))
161    }
162
163    fn decode_value_to_negative(&self, size_value: u64) -> Result<Value, DecoderError> {
164        Ok(Value::Negative(-(size_value as i128) - 1))
165    }
166
167    fn read_byte_string_content(&mut self, size_value: u64) -> Result<Value, DecoderError> {
168        match self.read_bytes(size_value as usize) {
169            Some(bytes) => Ok(cbor_bytes_lit!(bytes)),
170            None => Err(DecoderError::IncompleteCborData),
171        }
172    }
173
174    fn read_text_string_content(&mut self, size_value: u64) -> Result<Value, DecoderError> {
175        match self.read_bytes(size_value as usize) {
176            Some(bytes) => match str::from_utf8(bytes) {
177                Ok(s) => Ok(cbor_text!(s)),
178                Err(_) => Err(DecoderError::InvalidUtf8),
179            },
180            None => Err(DecoderError::IncompleteCborData),
181        }
182    }
183
184    fn read_array_content(
185        &mut self,
186        size_value: u64,
187        remaining_depth: Option<i8>,
188    ) -> Result<Value, DecoderError> {
189        // Don't set the capacity already, it is an unsanitized input.
190        let mut value_array = Vec::new();
191        for _ in 0..size_value {
192            value_array.push(self.decode_complete_data_item(remaining_depth.map(|d| d - 1))?);
193        }
194        Ok(cbor_array_vec!(value_array))
195    }
196
197    fn read_map_content(
198        &mut self,
199        size_value: u64,
200        remaining_depth: Option<i8>,
201    ) -> Result<Value, DecoderError> {
202        let mut value_map = Vec::<(Value, Value)>::new();
203        for _ in 0..size_value {
204            let key = self.decode_complete_data_item(remaining_depth.map(|d| d - 1))?;
205            if let Some(last_item) = value_map.last() {
206                if last_item.0 >= key && !self.non_strict {
207                    return Err(DecoderError::OutOfOrderKey);
208                }
209            }
210            value_map.push((
211                key,
212                self.decode_complete_data_item(remaining_depth.map(|d| d - 1))?,
213            ));
214        }
215        Ok(cbor_map_collection!(value_map))
216    }
217
218    fn read_tagged_content(
219        &mut self,
220        tag_value: u64,
221        remaining_depth: Option<i8>,
222    ) -> Result<Value, DecoderError> {
223        let inner_value = self.decode_complete_data_item(remaining_depth.map(|d| d - 1))?;
224        Ok(cbor_tagged!(tag_value, inner_value))
225    }
226
227    fn decode_to_simple_value(
228        &self,
229        size_value: u64,
230        additional_info: u8,
231    ) -> Result<Value, DecoderError> {
232        if additional_info > Constants::ADDITIONAL_INFORMATION_MAX_INT
233            && additional_info != Constants::ADDITIONAL_INFORMATION_1_BYTE
234            && !self.non_strict
235        {
236            // TODO(kaczmarczyck) the chromium C++ reference allows equality to 24 here, why?
237            // Also, why not just disallow ANY additional_info != size_value?
238            return Err(DecoderError::UnsupportedFloatingPointValue);
239        }
240        match SimpleValue::from_integer(size_value) {
241            Some(simple_value) => Ok(Value::Simple(simple_value)),
242            None if self.non_strict => Ok(Value::Simple(SimpleValue::Undefined)),
243            None => Err(DecoderError::UnsupportedSimpleValue),
244        }
245    }
246}
247
248#[cfg(test)]
249mod test {
250    use alloc::vec;
251
252    use super::*;
253    use crate::{
254        cbor_array, cbor_bytes, cbor_false, cbor_int, cbor_map, cbor_null, cbor_true,
255        cbor_undefined,
256    };
257
258    #[test]
259    fn test_read_unsigned() {
260        let cases = vec![
261            (0, vec![0x00]),
262            (1, vec![0x01]),
263            (10, vec![0x0A]),
264            (23, vec![0x17]),
265            (24, vec![0x18, 0x18]),
266            (255, vec![0x18, 0xFF]),
267            (256, vec![0x19, 0x01, 0x00]),
268            (65535, vec![0x19, 0xFF, 0xFF]),
269            (65536, vec![0x1A, 0x00, 0x01, 0x00, 0x00]),
270            (0xFFFFFFFF, vec![0x1A, 0xFF, 0xFF, 0xFF, 0xFF]),
271            (
272                0x100000000,
273                vec![0x1B, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00],
274            ),
275            (
276                core::i64::MAX,
277                vec![0x1B, 0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF],
278            ),
279        ];
280        for (unsigned, mut cbor) in cases {
281            assert_eq!(read(&cbor), Ok(cbor_int!(unsigned)));
282            cbor.push(0x01);
283            assert_eq!(read(&cbor), Err(DecoderError::ExtraneousData));
284        }
285    }
286
287    #[test]
288    fn test_read_unsigned_non_minimum_byte_length() {
289        let encodings = vec![
290            // Uint 23 encoded with 1 byte.
291            vec![0x18, 0x17],
292            // Uint 255 encoded with 2 bytes.
293            vec![0x19, 0x00, 0xff],
294            // Uint 65535 encoded with 4 bytes.
295            vec![0x1a, 0x00, 0x00, 0xff, 0xff],
296            // Uint 4294967295 encoded with 8 bytes.
297            vec![0x1b, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff],
298            // When decoding byte has more than one syntax error, the first syntax
299            // error encountered during deserialization is returned as the error code.
300            vec![
301                0xa2, // map with non-minimally encoded key
302                0x17, // key 24
303                0x61, 0x42, // value :"B"
304                0x18, 0x17, // key 23 encoded with extra byte
305                0x61, 0x45, // value "E"
306            ],
307            vec![
308                0xa2, // map with out of order and non-minimally encoded key
309                0x18, 0x17, // key 23 encoded with extra byte
310                0x61, 0x45, // value "E"
311                0x17, // key 23
312                0x61, 0x42, // value :"B"
313            ],
314            vec![
315                0xa2, // map with duplicate non-minimally encoded key
316                0x18, 0x17, // key 23 encoded with extra byte
317                0x61, 0x45, // value "E"
318                0x18, 0x17, // key 23 encoded with extra byte
319                0x61, 0x42, // value :"B"
320            ],
321        ];
322        for encoding in encodings {
323            assert_eq!(read(&encoding), Err(DecoderError::NonMinimalCborEncoding));
324        }
325    }
326
327    #[test]
328    fn test_read_negative() {
329        let cases = vec![
330            (-1, vec![0x20]),
331            (-24, vec![0x37]),
332            (-25, vec![0x38, 0x18]),
333            (-256, vec![0x38, 0xFF]),
334            (-1000, vec![0x39, 0x03, 0xE7]),
335            (-1000000, vec![0x3A, 0x00, 0x0F, 0x42, 0x3F]),
336            (-4294967296, vec![0x3A, 0xFF, 0xFF, 0xFF, 0xFF]),
337            (
338                core::i64::MIN,
339                vec![0x3B, 0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF],
340            ),
341        ];
342        for (negative, mut cbor) in cases {
343            assert_eq!(read(&cbor), Ok(cbor_int!(negative)));
344            cbor.push(0x01);
345            assert_eq!(read(&cbor), Err(DecoderError::ExtraneousData));
346        }
347    }
348
349    #[test]
350    fn test_read_byte_string() {
351        let cases = vec![
352            (Vec::new(), vec![0x40]),
353            (
354                vec![0x01, 0x02, 0x03, 0x04],
355                vec![0x44, 0x01, 0x02, 0x03, 0x04],
356            ),
357        ];
358        for (byte_string, mut cbor) in cases {
359            assert_eq!(read(&cbor), Ok(cbor_bytes!(byte_string)));
360            cbor.push(0x01);
361            assert_eq!(read(&cbor), Err(DecoderError::ExtraneousData));
362        }
363    }
364
365    #[test]
366    fn test_read_text_string() {
367        let unicode_3byte = vec![0xE6, 0xB0, 0xB4];
368        let cases = vec![
369            ("", vec![0x60]),
370            ("a", vec![0x61, 0x61]),
371            ("IETF", vec![0x64, 0x49, 0x45, 0x54, 0x46]),
372            ("\"\\", vec![0x62, 0x22, 0x5C]),
373            ("ü", vec![0x62, 0xC3, 0xBC]),
374            (
375                core::str::from_utf8(&unicode_3byte).unwrap(),
376                vec![0x63, 0xE6, 0xB0, 0xB4],
377            ),
378            ("𐅑", vec![0x64, 0xF0, 0x90, 0x85, 0x91]),
379        ];
380        for (text_string, mut cbor) in cases {
381            assert_eq!(read(&cbor), Ok(cbor_text!(text_string)));
382            cbor.push(0x01);
383            assert_eq!(read(&cbor), Err(DecoderError::ExtraneousData));
384        }
385    }
386
387    #[test]
388    fn test_read_text_string_with_nul() {
389        let cases = vec![
390            (
391                "string_without_nul",
392                vec![
393                    0x72, 0x73, 0x74, 0x72, 0x69, 0x6E, 0x67, 0x5F, 0x77, 0x69, 0x74, 0x68, 0x6F,
394                    0x75, 0x74, 0x5F, 0x6E, 0x75, 0x6C,
395                ],
396            ),
397            (
398                "nul_terminated_string\0",
399                vec![
400                    0x76, 0x6E, 0x75, 0x6C, 0x5F, 0x74, 0x65, 0x72, 0x6D, 0x69, 0x6E, 0x61, 0x74,
401                    0x65, 0x64, 0x5F, 0x73, 0x74, 0x72, 0x69, 0x6E, 0x67, 0x00,
402                ],
403            ),
404            (
405                "embedded\0nul",
406                vec![
407                    0x6C, 0x65, 0x6D, 0x62, 0x65, 0x64, 0x64, 0x65, 0x64, 0x00, 0x6E, 0x75, 0x6C,
408                ],
409            ),
410            (
411                "trailing_nuls\0\0",
412                vec![
413                    0x6F, 0x74, 0x72, 0x61, 0x69, 0x6C, 0x69, 0x6E, 0x67, 0x5F, 0x6E, 0x75, 0x6C,
414                    0x73, 0x00, 0x00,
415                ],
416            ),
417        ];
418        for (text_string, mut cbor) in cases {
419            assert_eq!(read(&cbor), Ok(cbor_text!(text_string)));
420            cbor.push(0x01);
421            assert_eq!(read(&cbor), Err(DecoderError::ExtraneousData));
422        }
423    }
424
425    #[test]
426    fn test_read_text_string_with_invalid_byte_sequence_after_nul() {
427        assert_eq!(
428            read(&vec![0x63, 0x00, 0x00, 0xA6]),
429            Err(DecoderError::InvalidUtf8)
430        );
431    }
432
433    #[test]
434    fn test_read_array() {
435        let value_vec: Vec<_> = (1..26).collect();
436        let mut test_cbor = vec![
437            0x98, 0x19, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c,
438            0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x18, 0x18,
439            0x19,
440        ];
441        assert_eq!(read(&test_cbor.clone()), Ok(cbor_array_vec!(value_vec)));
442        test_cbor.push(0x01);
443        assert_eq!(read(&test_cbor), Err(DecoderError::ExtraneousData));
444    }
445
446    #[test]
447    fn test_read_map() {
448        let value_map = cbor_map! {
449            24 => "abc",
450            "" => ".",
451            "b" => "B",
452            "aa" => "AA",
453        };
454        let mut test_cbor = vec![
455            0xa4, // map with 4 key value pairs:
456            0x18, 0x18, // 24
457            0x63, 0x61, 0x62, 0x63, // "abc"
458            0x60, // ""
459            0x61, 0x2e, // "."
460            0x61, 0x62, // "b"
461            0x61, 0x42, // "B"
462            0x62, 0x61, 0x61, // "aa"
463            0x62, 0x41, 0x41, // "AA"
464        ];
465        assert_eq!(read(&test_cbor), Ok(value_map));
466        test_cbor.push(0x01);
467        assert_eq!(read(&test_cbor), Err(DecoderError::ExtraneousData));
468    }
469
470    #[test]
471    fn test_read_map_with_unsigned_keys() {
472        let value_map = cbor_map! {
473            1 => "a",
474            9 => "b",
475            999 => "c",
476            1111 => "d",
477        };
478        let mut test_cbor = vec![
479            0xa4, // map with 4 key value pairs:
480            0x01, // key : 1
481            0x61, 0x61, // value : "a"
482            0x09, // key : 9
483            0x61, 0x62, // value : "b"
484            0x19, 0x03, 0xE7, // key : 999
485            0x61, 0x63, // value "c"
486            0x19, 0x04, 0x57, // key : 1111
487            0x61, 0x64, // value : "d"
488        ];
489        assert_eq!(read(&test_cbor), Ok(value_map));
490        test_cbor.push(0x01);
491        assert_eq!(read(&test_cbor), Err(DecoderError::ExtraneousData));
492    }
493
494    #[test]
495    fn test_read_map_with_negative_keys() {
496        let value_map = cbor_map! {
497            -1 => 1,
498            -2 => 2,
499            -100 => 3,
500        };
501        let mut test_cbor = vec![
502            0xA3, // map with 3 key value pairs
503            0x20, // key : -1
504            0x01, // value : 1
505            0x21, // key : -2
506            0x02, // value : 2
507            0x38, 0x63, // key : -100
508            0x03, // value : 3
509        ];
510        assert_eq!(read(&test_cbor), Ok(value_map));
511        test_cbor.push(0x01);
512        assert_eq!(read(&test_cbor), Err(DecoderError::ExtraneousData));
513    }
514
515    #[test]
516    fn test_read_map_with_array() {
517        let value_map = cbor_map! {
518            "a" => 1,
519            "b" => cbor_array![2, 3],
520        };
521        let mut test_cbor = vec![
522            0xa2, // map of 2 pairs
523            0x61, 0x61, // "a"
524            0x01, 0x61, 0x62, // "b"
525            0x82, // array with 2 elements
526            0x02, 0x03,
527        ];
528        assert_eq!(read(&test_cbor), Ok(value_map));
529        test_cbor.push(0x01);
530        assert_eq!(read(&test_cbor), Err(DecoderError::ExtraneousData));
531    }
532
533    #[test]
534    fn test_read_map_with_text_string_keys() {
535        let value_map = cbor_map! {
536            "k" => "v",
537            "foo" => "bar",
538        };
539        let mut test_cbor = vec![
540            0xa2, // map of 2 pairs
541            0x61, b'k', // text string "k"
542            0x61, b'v', 0x63, b'f', b'o', b'o', // text string "foo"
543            0x63, b'b', b'a', b'r',
544        ];
545        assert_eq!(read(&test_cbor), Ok(value_map));
546        test_cbor.push(0x01);
547        assert_eq!(read(&test_cbor), Err(DecoderError::ExtraneousData));
548    }
549
550    #[test]
551    fn test_read_map_with_byte_string_keys() {
552        let value_map = cbor_map! {
553            b"k" => b"v",
554            b"foo" => b"bar",
555        };
556        let mut test_cbor = vec![
557            0xa2, // map of 2 pairs
558            0x41, b'k', // text string "k"
559            0x41, b'v', 0x43, b'f', b'o', b'o', // text string "foo"
560            0x43, b'b', b'a', b'r',
561        ];
562        assert_eq!(read(&test_cbor), Ok(value_map));
563        test_cbor.push(0x01);
564        assert_eq!(read(&test_cbor), Err(DecoderError::ExtraneousData));
565    }
566
567    #[test]
568    fn test_read_nested_map() {
569        let value_map = cbor_map! {
570            "a" => 1,
571            "b" => cbor_map! {
572                "c" => 2,
573                "d" => 3,
574            },
575        };
576        let mut test_cbor = vec![
577            0xa2, // map of 2 pairs
578            0x61, 0x61, 0x01, // "a"
579            0x61, 0x62, // "b"
580            0xa2, // map of 2 pairs
581            0x61, 0x63, 0x02, // "c"
582            0x61, 0x64, 0x03, // "d"
583        ];
584        assert_eq!(read(&test_cbor), Ok(value_map));
585        test_cbor.push(0x01);
586        assert_eq!(read(&test_cbor), Err(DecoderError::ExtraneousData));
587    }
588
589    #[test]
590    fn test_read_tagged() {
591        let cases = vec![
592            (cbor_tagged!(6, cbor_int!(0x42)), vec![0xc6, 0x18, 0x42]),
593            (cbor_tagged!(1, cbor_true!()), vec![0xc1, 0xf5]),
594            (
595                cbor_tagged!(
596                    1000,
597                    cbor_map! {
598                        "a" => 1,
599                        "b" => cbor_array![2, 3],
600                    }
601                ),
602                vec![
603                    0xd9, 0x03, 0xe8, 0xa2, // map of 2 pairs
604                    0x61, 0x61, // "a"
605                    0x01, 0x61, 0x62, // "b"
606                    0x82, // array with 2 elements
607                    0x02, 0x03,
608                ],
609            ),
610        ];
611        for (value, mut cbor) in cases {
612            assert_eq!(read(&cbor), Ok(value));
613            cbor.push(0x01);
614            assert_eq!(read(&cbor), Err(DecoderError::ExtraneousData));
615        }
616    }
617
618    #[test]
619    fn test_read_integer_out_of_range() {
620        let cases = vec![
621            // The positive case is impossible since we support u64.
622            // vec![0x1B, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
623            vec![0x3B, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
624        ];
625        for cbor in cases {
626            assert_eq!(read(&cbor), Ok(Value::Negative(-9223372036854775809)));
627        }
628    }
629
630    #[test]
631    fn test_read_simple_value() {
632        let cases = vec![
633            (cbor_false!(), vec![0xF4]),
634            (cbor_true!(), vec![0xF5]),
635            (cbor_null!(), vec![0xF6]),
636            (cbor_undefined!(), vec![0xF7]),
637        ];
638        for (simple, mut cbor) in cases {
639            assert_eq!(read(&cbor.clone()), Ok(simple));
640            cbor.push(0x01);
641            assert_eq!(read(&cbor), Err(DecoderError::ExtraneousData));
642        }
643    }
644
645    #[test]
646    fn test_read_unsupported_floating_point_numbers() {
647        let cases = vec![
648            vec![0xF9, 0x10, 0x00],
649            vec![0xFA, 0x10, 0x00, 0x00, 0x00],
650            vec![0xFB, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
651        ];
652        for cbor in cases {
653            assert_eq!(
654                read(&cbor),
655                Err(DecoderError::UnsupportedFloatingPointValue)
656            );
657        }
658    }
659
660    #[test]
661    fn test_read_incomplete_cbor_data_error() {
662        let cases = vec![
663            vec![0x19, 0x03],
664            vec![0x44, 0x01, 0x02, 0x03],
665            vec![0x65, 0x49, 0x45, 0x54, 0x46],
666            vec![0x82, 0x02],
667            vec![0xA2, 0x61, 0x61, 0x01],
668            vec![0x18],
669            vec![0x99],
670            vec![0xBA],
671            vec![0x5B],
672            vec![0x3B],
673            vec![0x99, 0x01],
674            vec![0xBA, 0x01, 0x02, 0x03],
675            vec![0x3B, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07],
676        ];
677        for cbor in cases {
678            assert_eq!(read(&cbor), Err(DecoderError::IncompleteCborData));
679        }
680    }
681
682    #[test]
683    fn test_read_unknown_additional_info_error() {
684        let cases = vec![
685            vec![0x7C, 0x49, 0x45, 0x54, 0x46],
686            vec![0x7D, 0x22, 0x5C],
687            vec![0x7E, 0xC3, 0xBC],
688            vec![0x7F, 0xE6, 0xB0, 0xB4],
689            vec![0xFC],
690            vec![0xFD],
691            vec![0xFE],
692            vec![0xFF],
693        ];
694        for cbor in cases {
695            assert_eq!(read(&cbor), Err(DecoderError::UnknownAdditionalInfo));
696        }
697    }
698
699    #[test]
700    fn test_read_too_much_nesting_error() {
701        let cases = vec![
702            vec![0x18, 0x64],
703            vec![0x44, 0x01, 0x02, 0x03, 0x04],
704            vec![0x64, 0x49, 0x45, 0x54, 0x46],
705            vec![0x80],
706            vec![0xA0],
707        ];
708        for cbor in cases {
709            let mut reader = Reader::new(&cbor);
710            assert!(reader.decode_complete_data_item(Some(0)).is_ok());
711        }
712        let map_cbor = vec![
713            0xa2, // map of 2 pairs
714            0x61, 0x61, // "a"
715            0x01, 0x61, 0x62, // "b"
716            0x82, // array with 2 elements
717            0x02, 0x03,
718        ];
719        let mut reader = Reader::new(&map_cbor);
720        assert_eq!(
721            reader.decode_complete_data_item(Some(1)),
722            Err(DecoderError::TooMuchNesting)
723        );
724        reader = Reader::new(&map_cbor);
725        assert!(reader.decode_complete_data_item(Some(2)).is_ok());
726    }
727
728    #[test]
729    fn test_read_out_of_order_key_error() {
730        let cases = vec![
731            vec![
732                0xa2, // map with 2 keys with same major type and length
733                0x61, 0x62, // key "b"
734                0x61, 0x42, // value "B"
735                0x61, 0x61, // key "a" (out of order byte-wise lexically)
736                0x61, 0x45, // value "E"
737            ],
738            vec![
739                0xa2, // map with 2 keys with different major type
740                0x61, 0x62, // key "b"
741                0x02, // value 2
742                // key 1000 (out of order since lower major type sorts first)
743                0x19, 0x03, 0xe8, 0x61, 0x61, // value a
744            ],
745            vec![
746                0xa2, // map with 2 keys with same major type
747                0x19, 0x03, 0xe8, // key 1000  (out of order due to longer length)
748                0x61, 0x61, //value "a"
749                0x0a, // key 10
750                0x61, 0x62, // value "b"
751            ],
752            vec![
753                0xa2, // map with 2 text string keys
754                0x62, b'a', b'a', // key text string "aa"
755                // (out of order due to longer length)
756                0x02, 0x61, b'b', // key "b"
757                0x01,
758            ],
759            vec![
760                0xa2, // map with 2 byte string keys
761                0x42, b'x', b'x', // key byte string "xx"
762                // (out of order due to longer length)
763                0x02, 0x41, b'y', // key byte string "y"
764                0x01,
765            ],
766        ];
767        for cbor in cases {
768            assert_eq!(read(&cbor), Err(DecoderError::OutOfOrderKey));
769        }
770    }
771
772    #[test]
773    fn test_read_duplicate_key_error() {
774        let map_with_duplicate_key = vec![
775            0xa6, // map of 6 pairs:
776            0x60, // ""
777            0x61, 0x2e, // "."
778            0x61, 0x62, // "b"
779            0x61, 0x42, // "B"
780            0x61, 0x62, // "b" (Duplicate key)
781            0x61, 0x43, // "C"
782            0x61, 0x64, // "d"
783            0x61, 0x44, // "D"
784            0x61, 0x65, // "e"
785            0x61, 0x44, // "D"
786            0x62, 0x61, 0x61, // "aa"
787            0x62, 0x41, 0x41, // "AA"
788        ];
789        assert_eq!(
790            read(&map_with_duplicate_key),
791            Err(DecoderError::OutOfOrderKey)
792        );
793    }
794
795    #[test]
796    fn test_read_incorrect_string_encoding_error() {
797        let cases = vec![
798            vec![0x63, 0xED, 0x9F, 0xBF],
799            vec![0x63, 0xEE, 0x80, 0x80],
800            vec![0x63, 0xEF, 0xBF, 0xBD],
801        ];
802        for cbor in cases {
803            assert!(read(&cbor).is_ok());
804        }
805        let impossible_utf_byte = vec![0x64, 0xFE, 0xFE, 0xFF, 0xFF];
806        assert_eq!(read(&impossible_utf_byte), Err(DecoderError::InvalidUtf8));
807    }
808
809    #[test]
810    fn test_read_extraneous_cbor_data_error() {
811        let cases = vec![
812            vec![0x19, 0x03, 0x05, 0x00],
813            vec![0x44, 0x01, 0x02, 0x03, 0x04, 0x00],
814            vec![0x64, 0x49, 0x45, 0x54, 0x46, 0x00],
815            vec![0x82, 0x01, 0x02, 0x00],
816            vec![0xa1, 0x61, 0x63, 0x02, 0x61, 0x64, 0x03],
817        ];
818        for cbor in cases {
819            assert_eq!(read(&cbor), Err(DecoderError::ExtraneousData));
820        }
821    }
822
823    #[test]
824    fn test_read_unsupported_simple_type() {
825        let cases = vec![
826            vec![0xE0],
827            vec![0xF3],
828            vec![0xF8, 0x18],
829            vec![0xF8, 0x1C],
830            vec![0xF8, 0x1D],
831            vec![0xF8, 0x1E],
832            vec![0xF8, 0x1F],
833            vec![0xF8, 0x20],
834            vec![0xF8, 0xFF],
835        ];
836        for cbor in cases {
837            assert_eq!(read(&cbor), Err(DecoderError::UnsupportedSimpleValue));
838        }
839    }
840
841    #[test]
842    fn test_read_super_long_content_dont_crash() {
843        let cases = vec![
844            vec![0x9B, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF],
845            vec![0xBB, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF],
846        ];
847        for cbor in cases {
848            assert_eq!(read(&cbor), Err(DecoderError::IncompleteCborData));
849        }
850    }
851}