1 //! Handling for data represented as CBOR. Cryptographic objects are encoded following COSE.
2
3 mod dice;
4 mod field_value;
5 mod publickey;
6 pub(crate) mod rkp;
7
8 use ciborium::{de::from_reader, value::Value};
9 use std::io::Read;
10
11 type CiboriumError = ciborium::de::Error<std::io::Error>;
12
13 /// Decodes the provided binary CBOR-encoded value and returns a
14 /// ciborium::Value struct wrapped in Result.
value_from_bytes(mut bytes: &[u8]) -> Result<Value, CiboriumError>15 fn value_from_bytes(mut bytes: &[u8]) -> Result<Value, CiboriumError> {
16 let value = from_reader(bytes.by_ref())?;
17 // Ciborium tries to read one Value, but doesn't care if there is trailing data. We do.
18 if !bytes.is_empty() {
19 return Err(CiboriumError::Semantic(Some(0), "unexpected trailing data".to_string()));
20 }
21 Ok(value)
22 }
23
serialize(value: Value) -> Vec<u8>24 fn serialize(value: Value) -> Vec<u8> {
25 let mut data = Vec::new();
26 ciborium::ser::into_writer(&value, &mut data).unwrap();
27 data
28 }
29
30 #[cfg(test)]
31 mod tests {
32 use super::*;
33 use anyhow::Result;
34
35 #[test]
value_from_bytes_valid_succeeds() -> Result<()>36 fn value_from_bytes_valid_succeeds() -> Result<()> {
37 let bytes = [0x82, 0x04, 0x02]; // [4, 2]
38 let val = value_from_bytes(&bytes)?;
39 let array = val.as_array().unwrap();
40 assert_eq!(array.len(), 2);
41 Ok(())
42 }
43
44 #[test]
value_from_bytes_truncated_fails()45 fn value_from_bytes_truncated_fails() {
46 let bytes = [0x82, 0x04];
47 assert!(value_from_bytes(&bytes).is_err());
48 }
49
50 #[test]
value_from_bytes_trailing_bytes_fails()51 fn value_from_bytes_trailing_bytes_fails() {
52 let bytes = [0x82, 0x04, 0x02, 0x00];
53 assert!(value_from_bytes(&bytes).is_err());
54 }
55 }
56