• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: Apache-2.0
2 
3 extern crate std;
4 
5 use ciborium::cbor;
6 use ciborium::tag::Required;
7 use ciborium::value::CanonicalValue;
8 use rand::prelude::*;
9 use std::collections::BTreeMap;
10 
11 macro_rules! cval {
12     ($x:expr) => {
13         CanonicalValue::from(val!($x))
14     };
15 }
16 
17 macro_rules! val {
18     ($x:expr) => {
19         cbor!($x).unwrap()
20     };
21 }
22 
23 #[test]
rfc8949_example()24 fn rfc8949_example() {
25     let mut array: Vec<CanonicalValue> = vec![
26         cval!(10),
27         cval!(-1),
28         cval!(false),
29         cval!(100),
30         cval!("z"),
31         cval!([-1]),
32         cval!("aa"),
33         cval!([100]),
34     ];
35     let golden = array.clone();
36 
37     // Shuffle the array.
38     array.shuffle(&mut rand::thread_rng());
39 
40     array.sort();
41 
42     assert_eq!(array, golden);
43 }
44 
45 #[test]
map()46 fn map() {
47     let mut map = BTreeMap::new();
48     map.insert(cval!(false), val!(2));
49     map.insert(cval!([-1]), val!(5));
50     map.insert(cval!(-1), val!(1));
51     map.insert(cval!(10), val!(0));
52     map.insert(cval!(100), val!(3));
53     map.insert(cval!([100]), val!(7));
54     map.insert(cval!("z"), val!(4));
55     map.insert(cval!("aa"), val!(6));
56 
57     let mut bytes1 = Vec::new();
58     ciborium::ser::into_writer(&map, &mut bytes1).unwrap();
59 
60     assert_eq!(
61         hex::encode(&bytes1),
62         "a80a002001f402186403617a048120056261610681186407"
63     );
64 }
65 
66 #[test]
negative_numbers()67 fn negative_numbers() {
68     let mut array: Vec<CanonicalValue> = vec![
69         cval!(10),
70         cval!(-1),
71         cval!(-2),
72         cval!(-3),
73         cval!(-4),
74         cval!(false),
75         cval!(100),
76         cval!(-100),
77         cval!(-200),
78         cval!("z"),
79         cval!([-1]),
80         cval!(-300),
81         cval!("aa"),
82         cval!([100]),
83     ];
84     let golden = array.clone();
85 
86     // Shuffle the array.
87     array.shuffle(&mut rand::thread_rng());
88 
89     array.sort();
90 
91     assert_eq!(array, golden);
92 }
93 
94 #[test]
tagged_option()95 fn tagged_option() {
96     let mut opt = Some(Required::<u64, 0xff>(2u32.into()));
97 
98     let mut bytes = Vec::new();
99     ciborium::ser::into_writer(&opt, &mut bytes).unwrap();
100 
101     let output = ciborium::de::from_reader(&bytes[..]).unwrap();
102     assert_eq!(opt, output);
103 
104     opt = None;
105 
106     let mut bytes = Vec::new();
107     ciborium::ser::into_writer(&opt, &mut bytes).unwrap();
108 
109     let output = ciborium::de::from_reader(&bytes[..]).unwrap();
110     assert_eq!(opt, output);
111 }
112