| 1 | #[cfg(feature = "std")] |
| 2 | mod std_tests { |
| 3 | use std::collections::BTreeMap; |
| 4 | |
| 5 | use serde::{Deserialize, Serialize}; |
| 6 | |
| 7 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] |
| 8 | struct TupleStruct(String, i32, u64); |
| 9 | |
| 10 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] |
| 11 | struct UnitStruct; |
| 12 | |
| 13 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] |
| 14 | struct Struct<'a> { |
| 15 | tuple_struct: TupleStruct, |
| 16 | tuple: (String, f32, f64), |
| 17 | map: BTreeMap<String, String>, |
| 18 | bytes: &'a [u8], |
| 19 | array: Vec<String>, |
| 20 | unit_array: Vec<UnitStruct>, |
| 21 | } |
| 22 | |
| 23 | use serde_cbor_2::value::Value; |
| 24 | use std::iter::FromIterator; |
| 25 | |
| 26 | #[test] |
| 27 | fn serde() { |
| 28 | let tuple_struct = TupleStruct("test".to_owned(), -60, 3000); |
| 29 | |
| 30 | let tuple = ("hello".to_owned(), -50.004_097, -12.094635556478); |
| 31 | |
| 32 | let map = BTreeMap::from_iter( |
| 33 | [ |
| 34 | ("key1".to_owned(), "value1".to_owned()), |
| 35 | ("key2".to_owned(), "value2".to_owned()), |
| 36 | ("key3".to_owned(), "value3".to_owned()), |
| 37 | ("key4".to_owned(), "value4".to_owned()), |
| 38 | ] |
| 39 | .iter() |
| 40 | .cloned(), |
| 41 | ); |
| 42 | |
| 43 | let bytes = b"test byte string"; |
| 44 | |
| 45 | let array = vec![format!("one"), format!("two"), format!("three")]; |
| 46 | let unit_array = vec![UnitStruct, UnitStruct, UnitStruct]; |
| 47 | |
| 48 | let data = Struct { |
| 49 | tuple_struct, |
| 50 | tuple, |
| 51 | map, |
| 52 | bytes, |
| 53 | array, |
| 54 | unit_array, |
| 55 | }; |
| 56 | |
| 57 | let value = serde_cbor_2::value::to_value(data.clone()).unwrap(); |
| 58 | println!("{value:?}"); |
| 59 | |
| 60 | let data_ser = serde_cbor_2::to_vec(&value).unwrap(); |
| 61 | let data_de_value: Value = serde_cbor_2::from_slice(&data_ser).unwrap(); |
| 62 | |
| 63 | fn as_object(value: &Value) -> &BTreeMap<Value, Value> { |
| 64 | if let Value::Map(ref v) = value { |
| 65 | return v; |
| 66 | } |
| 67 | panic!() |
| 68 | } |
| 69 | |
| 70 | for ((k1, v1), (k2, v2)) in as_object(&value) |
| 71 | .iter() |
| 72 | .zip(as_object(&data_de_value).iter()) |
| 73 | { |
| 74 | assert_eq!(k1, k2); |
| 75 | assert_eq!(v1, v2); |
| 76 | } |
| 77 | |
| 78 | assert_eq!(value, data_de_value); |
| 79 | } |
| 80 | |
| 81 | #[derive(Debug, Deserialize, Serialize)] |
| 82 | struct SmallStruct { |
| 83 | spam: u32, |
| 84 | eggs: u32, |
| 85 | } |
| 86 | |
| 87 | #[test] |
| 88 | fn small_struct() { |
| 89 | // Test whether the packed format works. |
| 90 | // Field names should not be serialized, |
| 91 | // instead field indizes are serialized. |
| 92 | let value = SmallStruct { spam: 17, eggs: 42 }; |
| 93 | let data = serde_cbor_2::ser::to_vec_packed(&value).unwrap(); |
| 94 | let reference = b"\xa2\x00\x11\x01\x18\x2a"; |
| 95 | assert_eq!(data, reference); |
| 96 | } |
| 97 | } |