1// SPDX-License-Identifier: Apache-2.0
2
3extern crate std;
4
5use ciborium::cbor;
6use ciborium::tag::Required;
7use ciborium::value::CanonicalValue;
8use rand::prelude::*;
9use std::collections::BTreeMap;
10
11macro_rules! cval {
12 ($x:expr) => {
13 CanonicalValue::from(val!($x))
14 };
15}
16
17macro_rules! val {
18 ($x:expr) => {
19 cbor!($x).unwrap()
20 };
21}
22
23#[test]
24fn 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]
46fn 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]
67fn 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]
95fn 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